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
habr/ChatTaskAPI
CellMyImage.swift
1
830
// // CellMyImage.swift // Chat // // Created by Kobalt on 04.02.16. // Copyright © 2016 Alamofire. All rights reserved. // import Alamofire import UIKit class CellMyImage: UICollectionViewCell { @IBOutlet weak var timeMess: UILabel! @IBOutlet weak var imageMess: UIImageView! @IBOutlet weak var indicator: UIActivityIndicatorView! func configCell(updated_at: String, imageURL: NSURL) { timeMess?.text = updated_at indicator.startAnimating() Alamofire.request(.GET, imageURL).response() { (_, _, data, _) in dispatch_async(dispatch_get_main_queue()) { if self.imageMess.image == nil { let image = UIImage(data: data!) self.imageMess.image = image self.indicator.stopAnimating() }}} } }
mit
321a3eddbcb437df82f0a8b907f149c2
25.741935
74
0.616405
4.251282
false
false
false
false
SheffieldKevin/swiftsvg2
SwiftSVG/Utilities/Renderer.swift
1
15196
// // Renderer.swift // SwiftSVG // // Created by Jonathan Wight on 8/26/15. // Copyright © 2015 No. All rights reserved. // import SwiftGraphics public protocol Renderer: AnyObject { func concatTransform(transform:CGAffineTransform) func concatCTM(transform:CGAffineTransform) func pushGraphicsState() func restoreGraphicsState() func startDocument(viewBox: CGRect) func startGroup(id: String?) func endElement() func startElement(id: String?) func addPath(path:PathGenerator) func addCGPath(path: CGPath) func drawPath(mode: CGPathDrawingMode) func drawText(textRenderer: TextRenderer) func drawLinearGradient(linearGradient: LinearGradientRenderer, pathGenerator: PathGenerator) func fillPath() func render() -> String var strokeColor:CGColor? { get set } var fillColor:CGColor? { get set } var lineWidth:CGFloat? { get set } var style:Style { get set } } // MARK: - public protocol CustomSourceConvertible { func toSource() -> String } extension CGAffineTransform: CustomSourceConvertible { public func toSource() -> String { return "CGAffineTransform(\(a), \(b), \(c), \(d), \(tx), \(ty))" } } // MARK: - CGContext renderer extension CGContext: Renderer { public func concatTransform(transform:CGAffineTransform) { CGContextConcatCTM(self, transform) } public func concatCTM(transform:CGAffineTransform) { CGContextConcatCTM(self, transform) } public func pushGraphicsState() { CGContextSaveGState(self) } public func restoreGraphicsState() { CGContextRestoreGState(self) } public func startDocument(viewBox: CGRect) { } public func startGroup(id: String?) { } public func endElement() { } public func startElement(id: String?) { } public func addCGPath(path: CGPath) { CGContextAddPath(self, path) } public func addPath(path:PathGenerator) { addCGPath(path.cgpath) } public func drawPath(mode: CGPathDrawingMode) { CGContextDrawPath(self, mode) } public func drawText(textRenderer: TextRenderer) { self.pushGraphicsState() CGContextTranslateCTM(self, 0.0, textRenderer.textOrigin.y) CGContextScaleCTM(self, 1.0, -1.0) let line = CTLineCreateWithAttributedString(textRenderer.cttext) CGContextSetTextPosition(self, textRenderer.textOrigin.x, 0.0) CTLineDraw(line, self) self.restoreGraphicsState() } public func drawLinearGradient(linearGradient: LinearGradientRenderer, pathGenerator: PathGenerator) { guard let theGradient = linearGradient.linearGradient else { return } guard let start = linearGradient.startPoint else { return } guard let end = linearGradient.endPoint else { return } self.pushGraphicsState() self.addPath(pathGenerator) if pathGenerator.evenOdd { CGContextEOClip(self) } else { CGContextClip(self) } CGContextDrawLinearGradient(self, theGradient, start, end, CGGradientDrawingOptions()) self.restoreGraphicsState() } public func fillPath() { CGContextFillPath(self) } public func render() -> String { return "" } } //MARK: - MovingImagesRenderer public class MovingImagesRenderer: Renderer { class MIRenderElement: Node { internal typealias ParentType = MIRenderContainer internal weak var parent: MIRenderContainer? = nil internal var movingImages = [NSString : AnyObject]() internal func generateJSONDict() -> [NSString : AnyObject] { return movingImages } } class MIRenderContainer: MIRenderElement, GroupNode { internal var children = [MIRenderElement]() override init() { super.init() } override internal func generateJSONDict() -> [NSString : AnyObject] { self.movingImages[MIJSONKeyElementType] = MIJSONKeyArrayOfElements let arrayOfElements = children.map { $0.generateJSONDict() } self.movingImages[MIJSONKeyArrayOfElements] = arrayOfElements return self.movingImages } } public init() { current = rootElement } internal var rootElement = MIRenderContainer() private var current: MIRenderElement // internal var movingImagesJSON: [NSString : AnyObject] public func concatTransform(transform:CGAffineTransform) { concatCTM(transform) } public func concatCTM(transform:CGAffineTransform) { current.movingImages[MIJSONKeyAffineTransform] = makeCGAffineTransformDictionary(transform) } public func pushGraphicsState() { } public func restoreGraphicsState() { } public func addCGPath(path: CGPath) { } // Should this be throws? public func startGroup(id: String?) { if let current = self.current as? MIRenderContainer { let newItem = MIRenderContainer() if let id = id { newItem.movingImages[MIJSONKeyElementDebugName] = id } current.children.append(newItem) newItem.parent = current self.current = newItem } else { preconditionFailure("Cannot start a new render group. Current element is a leaf") } } public func startElement(id: String?) { if let current = self.current as? MIRenderContainer { let newItem = MIRenderElement() if let id = id { newItem.movingImages[MIJSONKeyElementDebugName] = id } current.children.append(newItem) newItem.parent = current self.current = newItem } else { preconditionFailure("Cannot start a new render element. Current element is a leaf") } } public func startDocument(viewBox: CGRect) { current.movingImages["viewBox"] = makeRectDictionary(viewBox) } public func addPath(path:PathGenerator) { if let svgPath = path.svgpath { current.movingImages[MIJSONKeySVGPath] = svgPath return } if let mipath = path.mipath { for (key, value) in mipath { current.movingImages[key] = value } } } public func drawText(textRenderer: TextRenderer) { for (key, value) in textRenderer.mitext { current.movingImages[key] = value } } public func drawLinearGradient(linearGradient: LinearGradientRenderer, pathGenerator: PathGenerator) { guard let gradient = linearGradient.miLinearGradient else { return } if let svgPath = pathGenerator.svgpath { current.movingImages[MIJSONKeySVGPath] = svgPath } else if let mipath = pathGenerator.mipath { for (key, value) in mipath { current.movingImages[key] = value } } for (key, value) in gradient { current.movingImages[key] = value } } public func endElement() { if let parent = self.current.parent { self.current = parent } else { preconditionFailure("Cannot end an element when there is no parent.") } } public func drawPath(mode: CGPathDrawingMode) { let miDrawingElement: NSString let evenOdd: NSString? switch(mode) { case CGPathDrawingMode.Fill: miDrawingElement = MIJSONValuePathFillElement evenOdd = Optional.None // evenOdd = "nonwindingrule" case CGPathDrawingMode.Stroke: miDrawingElement = MIJSONValuePathStrokeElement evenOdd = Optional.None case CGPathDrawingMode.EOFill: miDrawingElement = MIJSONValuePathFillElement evenOdd = MIJSONValueEvenOddClippingRule case CGPathDrawingMode.EOFillStroke: miDrawingElement = MIJSONValuePathFillAndStrokeElement evenOdd = MIJSONValueEvenOddClippingRule case CGPathDrawingMode.FillStroke: miDrawingElement = MIJSONValuePathFillAndStrokeElement evenOdd = Optional.None // evenOdd = "nonwindingrule" } if let rule = evenOdd { current.movingImages[MIJSONKeyClippingRule] = rule } if current.movingImages[MIJSONKeyElementType] == nil { current.movingImages[MIJSONKeyElementType] = miDrawingElement } } // Not part of the Render protocol. public func generateJSONDict() -> [NSString : AnyObject] { return rootElement.generateJSONDict() } public func render() -> String { if let jsonString = jsonObjectToString(self.generateJSONDict()) { return jsonString } return "" } public func fillPath() { } public var strokeColor:CGColor? { get { return style.strokeColor } set { style.strokeColor = newValue if let color = newValue { current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeMIColorFromColor(color) } else { current.movingImages[MIJSONKeyStrokeColor] = nil } } } public var fillColor:CGColor? { get { return style.fillColor } set { style.fillColor = newValue if let color = newValue { current.movingImages[MIJSONKeyFillColor] = SVGColors.makeMIColorFromColor(color) } else { current.movingImages[MIJSONKeyFillColor] = nil } } } public var lineWidth:CGFloat? { get { return style.lineWidth } set { style.lineWidth = newValue if let lineWidth = newValue { current.movingImages[MIJSONKeyLineWidth] = lineWidth } else { current.movingImages[MIJSONKeyFillColor] = nil } } } public var style:Style = Style() { didSet { if let fillColor = style.fillColor { current.movingImages[MIJSONKeyFillColor] = SVGColors.makeMIColorFromColor(fillColor) } if let strokeColor = style.strokeColor { current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeMIColorFromColor(strokeColor) } if let lineWidth = style.lineWidth { current.movingImages[MIJSONKeyLineWidth] = lineWidth } if let lineCap = style.lineCap { current.movingImages[MIJSONKeyLineCap] = lineCap.stringValue } if let lineJoin = style.lineJoin { current.movingImages[MIJSONKeyLineJoin] = lineJoin.stringValue } if let miterLimit = style.miterLimit { current.movingImages[MIJSONKeyMiter] = miterLimit } if let alpha = style.alpha { current.movingImages[MIJSONKeyContextAlpha] = alpha } if let lineDash = style.lineDash { if let lineDashPhase = style.lineDashPhase { current.movingImages[MIJSONKeyLineDashArray] = lineDash current.movingImages[MIJSONKeyLineDashPhase] = lineDashPhase } else { current.movingImages[MIJSONKeyLineDashArray] = lineDash } } /* Not yet implemented in SwiftSVG. if let blendMode = newStyle.blendMode { setBlendMode(blendMode) } */ } } } private extension CGLineCap { var stringValue: NSString { switch(self) { case CGLineCap.Butt: return "kCGLineCapButt" case CGLineCap.Round: return "kCGLineCapRound" case CGLineCap.Square: return "kCGLineCapSquare" } } } private extension CGLineJoin { var stringValue: NSString { switch(self) { case CGLineJoin.Bevel: return "kCGLineJoinBevel" case CGLineJoin.Miter: return "kCGLineJoinMiter" case CGLineJoin.Round: return "kCGLineJoinRound" } } } // MARK: - public class SourceCodeRenderer: Renderer { public internal(set) var source = "" public init() { // Shouldn't this be fill color. Default stroke is no stroke. // whereas default fill is black. ktam? self.style.strokeColor = CGColor.blackColor() } public func concatTransform(transform:CGAffineTransform) { concatCTM(transform) } public func concatCTM(transform:CGAffineTransform) { source += "CGContextConcatCTM(context, \(transform.toSource()))\n" } public func pushGraphicsState() { source += "CGContextSaveGState(context)\n" } public func restoreGraphicsState() { source += "CGContextRestoreGState(self)\n" } public func startGroup(id: String?) { } public func endElement() { } public func startElement(id: String?) { } public func startDocument(viewBox: CGRect) { } public func addCGPath(path: CGPath) { source += "CGContextAddPath(context, \(path))\n" } public func addPath(path:PathGenerator) { addCGPath(path.cgpath) } public func drawPath(mode: CGPathDrawingMode) { source += "CGContextDrawPath(context, TODO)\n" } public func drawText(textRenderer: TextRenderer) { } public func drawLinearGradient(linearGradient: LinearGradientRenderer, pathGenerator: PathGenerator) { } public func fillPath() { source += "CGContextFillPath(context)\n" } public func render() -> String { return source } public var strokeColor:CGColor? { get { return style.strokeColor } set { style.strokeColor = newValue source += "CGContextSetStrokeColor(context, TODO)\n" } } public var fillColor:CGColor? { get { return style.fillColor } set { style.fillColor = newValue source += "CGContextSetFillColor(context, TODO)\n" } } public var lineWidth:CGFloat? { get { return style.lineWidth } set { style.lineWidth = newValue source += "CGContextSetLineWidth(context, TODO)\n" } } public var style:Style = Style() { didSet { source += "CGContextSetStrokeColor(context, TODO)\n" source += "CGContextSetFillColor(context, TODO)\n" } } }
bsd-2-clause
fe671626eb932e91159887cf40b01749
27.998092
104
0.594867
5.026464
false
false
false
false
aamays/Twitter
Twitter/AppDelegate.swift
1
3774
// // AppDelegate.swift // Twitter // // Created by Amay Singhal on 9/29/15. // Copyright © 2015 ple. All rights reserved. // import UIKit import BDBOAuth1Manager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { if let query = url.query { TwitterClient.updateAccessTokenFromUrlQuery(query) } return true } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if let archivedUser = UserManager.getLastActiveUser() { UserManager.CurrentUser = archivedUser // load manager VC with menu controller let menuVC = MainStoryboard.Storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.MenuVCIdentifier) as? MenuViewController if let managerVC = MainStoryboard.Storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.ManagerVCIdentifier) as? VCMangerViewController { managerVC.menuViewController = menuVC managerVC.contentViewController = menuVC?.initialViewController menuVC?.delegate = managerVC window?.rootViewController = managerVC } } UIApplication.sharedApplication().statusBarStyle = .LightContent return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. NSNotificationCenter.defaultCenter().removeObserver(self, name: AppConstants.UserDidLogoutNotification, object: nil) UIApplication.sharedApplication().statusBarStyle = .Default } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. NSNotificationCenter.defaultCenter().addObserver(self, selector: "currentUserDidLogout:", name: AppConstants.UserDidLogoutNotification, object: nil) } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Selector methods func currentUserDidLogout(sender: AnyObject?) { let loginVC = MainStoryboard.Storyboard.instantiateInitialViewController() window?.rootViewController = loginVC } }
mit
69bab2b7e076b6996cf3e50f248a6dce
48
285
0.736019
5.840557
false
false
false
false
igorbarinov/powerball-helper
PowerballWidget/TodayViewController.swift
1
1627
// // TodayViewController.swift // PowerballWidget // // Created by Igor Barinov on 9/27/14. // Copyright (c) 2014 Igor Barinov. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { override func viewDidLoad() { super.viewDidLoad() println("ok") // Do any additional setup after loading the view from its nib. // getLastDraw() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getLastDraw() -> String { var ref = Firebase(url:"https://swift-hackathon.firebaseio.com/powerball") println("test") var alanisawesome = ["full_name": "Alan Turing", "date_of_birth": "June 23, 1912"] var gracehop = ["full_name": "Grace Hopper", "date_of_birth": "December 9, 1906"] var usersRef = ref.childByAppendingPath("users") var users = ["alanisawesome": alanisawesome, "gracehop": gracehop] usersRef.setValue(users) var result = "" return result } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } }
mit
8fc2aea887123852d80235af72705324
29.698113
99
0.63614
4.702312
false
false
false
false
akaralar/siesta
Source/Siesta/Support/Siesta-ObjC.swift
2
15038
// // Siesta-ObjC.swift // Siesta // // Created by Paul on 2015/7/14. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation /* Glue for using Siesta from Objective-C. Siesta follows a Swift-first design approach. It uses the full expressiveness of the language to make everything feel “Swift native,” both in interface and implementation. This means many Siesta APIs can’t simply be marked @objc, and require a separate compatibility layer. Rather than sprinkle that mess throughout the code, it’s all quarrantined here. Features exposed to Objective-C: * Resource path navigation (child, relative, etc.) * Resource state * Observers * Request / load * Request completion callbacks * UI components Some things are not exposed in the compatibility layer, and must be done in Swift: * Subclassing Service * Custom ResponseTransformers * Custom NetworkingProviders * Logging config */ // MARK: - Because Swift structs aren’t visible to Obj-C // (Why not just make Entity<Any> and RequestError classes and avoid all these // shenanigans? Because Swift’s lovely mutable/immutable struct handling lets Resource // expose the full struct to Swift clients sans copying, yet still force mutations to // happen via overrideLocalData() so that observers always know about changes.) @objc(BOSEntity) public class _objc_Entity: NSObject { public var content: AnyObject public var contentType: String public var charset: String? public var etag: String? fileprivate var headers: [String:String] public private(set) var timestamp: TimeInterval = 0 public init(content: AnyObject, contentType: String, headers: [String:String]) { self.content = content self.contentType = contentType self.headers = headers } public convenience init(content: AnyObject, contentType: String) { self.init(content: content, contentType: contentType, headers: [:]) } internal init(_ entity: Entity<Any>) { self.content = entity.content as AnyObject self.contentType = entity.contentType self.charset = entity.charset self.etag = entity.etag self.headers = entity.headers } public func header(_ key: String) -> String? { return headers[key.lowercased()] } public override var description: String { return debugStr(Entity<Any>.convertedFromObjc(self)) } } internal extension Entity { static func convertedFromObjc(_ entity: _objc_Entity) -> Entity<Any> { return Entity<Any>(content: entity.content, contentType: entity.contentType, charset: entity.charset, headers: entity.headers) } } @objc(BOSError) public class _objc_Error: NSObject { public var httpStatusCode: Int public var cause: NSError? public var userMessage: String public var entity: _objc_Entity? public let timestamp: TimeInterval internal init(_ error: RequestError) { self.httpStatusCode = error.httpStatusCode ?? -1 self.cause = error.cause as? NSError self.userMessage = error.userMessage self.timestamp = error.timestamp if let errorData = error.entity { self.entity = _objc_Entity(errorData) } } } public extension Service { @objc(resourceWithAbsoluteURL:) public final func _objc_resourceWithAbsoluteURL(absoluteURL url: URL?) -> Resource { return resource(absoluteURL: url) } @objc(resourceWithAbsoluteURLString:) public final func _objc_resourceWithAbsoluteURLString(absoluteURL url: String?) -> Resource { return resource(absoluteURL: url) } } public extension Resource { @objc(latestData) public var _objc_latestData: _objc_Entity? { if let latestData = latestData { return _objc_Entity(latestData) } else { return nil } } @objc(latestError) public var _objc_latestError: _objc_Error? { if let latestError = latestError { return _objc_Error(latestError) } else { return nil } } @objc(jsonDict) public var _objc_jsonDict: NSDictionary { return jsonDict as NSDictionary } @objc(jsonArray) public var _objc_jsonArray: NSArray { return jsonArray as NSArray } @objc(text) public var _objc_text: String { return text } @objc(overrideLocalData:) public func _objc_overrideLocalData(_ entity: _objc_Entity) { overrideLocalData(with: Entity<Any>.convertedFromObjc(entity)) } } // MARK: - Because Swift closures aren’t exposed as Obj-C blocks @objc(BOSRequest) public class _objc_Request: NSObject { fileprivate let request: Request fileprivate init(_ request: Request) { self.request = request } public func onCompletion(_ objcCallback: @escaping @convention(block) (_objc_Entity?, _objc_Error?) -> Void) -> _objc_Request { request.onCompletion { switch $0.response { case .success(let entity): objcCallback(_objc_Entity(entity), nil) case .failure(let error): objcCallback(nil, _objc_Error(error)) } } return self } public func onSuccess(_ objcCallback: @escaping @convention(block) (_objc_Entity) -> Void) -> _objc_Request { request.onSuccess { entity in objcCallback(_objc_Entity(entity)) } return self } public func onNewData(_ objcCallback: @escaping @convention(block) (_objc_Entity) -> Void) -> _objc_Request { request.onNewData { entity in objcCallback(_objc_Entity(entity)) } return self } public func onNotModified(_ objcCallback: @escaping @convention(block) (Void) -> Void) -> _objc_Request { request.onNotModified(objcCallback) return self } public func onFailure(_ objcCallback: @escaping @convention(block) (_objc_Error) -> Void) -> _objc_Request { request.onFailure { error in objcCallback(_objc_Error(error)) } return self } public func onProgress(_ objcCallback: @escaping @convention(block) (Float) -> Void) -> _objc_Request { request.onProgress { p in objcCallback(Float(p)) } return self } public func cancel() { request.cancel() } public override var description: String { return debugStr(request) } } public extension Resource { @objc(load) public func _objc_load() -> _objc_Request { return _objc_Request(load()) } @objc(loadIfNeeded) public func _objc_loadIfNeeded() -> _objc_Request? { if let req = loadIfNeeded() { return _objc_Request(req) } else { return nil } } } // MARK: - Because Swift enums aren’t exposed to Obj-C @objc(BOSResourceObserver) public protocol _objc_ResourceObserver { func resourceChanged(_ resource: Resource, event: String) @objc optional func resourceRequestProgress(_ resource: Resource, progress: Double) @objc optional func stoppedObservingResource(_ resource: Resource) } private class _objc_ResourceObserverGlue: ResourceObserver, CustomDebugStringConvertible { var resource: Resource? var objcObserver: _objc_ResourceObserver init(objcObserver: _objc_ResourceObserver) { self.objcObserver = objcObserver } deinit { if let resource = resource { objcObserver.stoppedObservingResource?(resource) } } func resourceChanged(_ resource: Resource, event: ResourceEvent) { if case .observerAdded = event { self.resource = resource } objcObserver.resourceChanged(resource, event: event._objc_stringForm) } func resourceRequestProgress(_ resource: Resource, progress: Double) { objcObserver.resourceRequestProgress?(resource, progress: progress) } var observerIdentity: AnyHashable { return ObjectIdentifier(objcObserver) } var debugDescription: String { return debugStr(objcObserver) } } extension ResourceEvent { public var _objc_stringForm: String { if case .newData(let source) = self { return "NewData(\(source.description.capitalized))" } else { return String(describing: self).capitalized } } } public extension Resource { @objc(addObserver:) public func _objc_addObserver(_ observerAndOwner: _objc_ResourceObserver & AnyObject) -> Self { return addObserver(_objc_ResourceObserverGlue(objcObserver: observerAndOwner), owner: observerAndOwner) } @objc(addObserver:owner:) public func _objc_addObserver(_ objcObserver: _objc_ResourceObserver, owner: AnyObject) -> Self { return addObserver(_objc_ResourceObserverGlue(objcObserver: objcObserver), owner: owner) } @objc(addObserverWithOwner:callback:) public func _objc_addObserver(owner: AnyObject, block: @escaping @convention(block) (Resource, String) -> Void) -> Self { return addObserver(owner: owner) { block($0, $1._objc_stringForm) } } } public extension Resource { private func _objc_wrapRequest( _ methodString: String, closure: (RequestMethod) -> Request) -> _objc_Request { guard let method = RequestMethod(rawValue: methodString.lowercased()) else { return _objc_Request( Resource.failedRequest( RequestError( userMessage: NSLocalizedString("Cannot create request", comment: "userMessage"), cause: _objc_Error.Cause.InvalidRequestMethod(method: methodString)))) } return _objc_Request(closure(method)) } private func _objc_wrapJSONRequest( _ methodString: String, _ maybeJson: NSObject?, closure: (RequestMethod, JSONConvertible) -> Request) -> _objc_Request { guard let json = maybeJson as? JSONConvertible else { return _objc_Request( Resource.failedRequest( RequestError( userMessage: NSLocalizedString("Cannot send request", comment: "userMessage"), cause: RequestError.Cause.InvalidJSONObject()))) } return _objc_wrapRequest(methodString) { closure($0, json) } } private static func apply(requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?, to request: inout URLRequest) { let mutableReq = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest requestMutation?(mutableReq) request = mutableReq as URLRequest } @objc(requestWithMethod:requestMutation:) public func _objc_request( _ method: String, requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0) { Resource.apply(requestMutation: requestMutation, to: &$0) } } } @objc(requestWithMethod:) public func _objc_request(_ method: String) -> _objc_Request { return _objc_wrapRequest(method) { request($0) } } @objc(requestWithMethod:data:contentType:requestMutation:) public func _objc_request( _ method: String, data: Data, contentType: String, requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, data: data, contentType: contentType) { Resource.apply(requestMutation: requestMutation, to: &$0) } } } @objc(requestWithMethod:text:) public func _objc_request( _ method: String, text: String) -> _objc_Request { return _objc_wrapRequest(method) { request($0, text: text) } } @objc(requestWithMethod:text:contentType:encoding:requestMutation:) public func _objc_request( _ method: String, text: String, contentType: String, encoding: UInt = String.Encoding.utf8.rawValue, requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, text: text, contentType: contentType, encoding: String.Encoding(rawValue: encoding)) { Resource.apply(requestMutation: requestMutation, to: &$0) } } } @objc(requestWithMethod:json:) public func _objc_request( _ method: String, json: NSObject?) -> _objc_Request { return _objc_wrapJSONRequest(method, json) { request($0, json: $1) } } @objc(requestWithMethod:json:contentType:requestMutation:) public func _objc_request( _ method: String, json: NSObject?, contentType: String, requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?) -> _objc_Request { return _objc_wrapJSONRequest(method, json) { request($0, json: $1, contentType: contentType) { Resource.apply(requestMutation: requestMutation, to: &$0) } } } @objc(requestWithMethod:urlEncoded:requestMutation:) public func _objc_request( _ method: String, urlEncoded params: [String:String], requestMutation: (@convention(block) (NSMutableURLRequest) -> ())?) -> _objc_Request { return _objc_wrapRequest(method) { request($0, urlEncoded: params) { Resource.apply(requestMutation: requestMutation, to: &$0) } } } @objc(loadUsingRequest:) public func _objc_load(using req: _objc_Request) -> _objc_Request { load(using: req.request) return req } } public extension _objc_Error { public enum Cause { /// Request method specified as a string does not match any of the values in the RequestMethod enum. public struct InvalidRequestMethod: Error { public let method: String } } }
mit
7bdd3d3187b5d8378a95da257f33f094
31.027719
134
0.602956
4.814423
false
false
false
false
notbenoit/tvOS-Twitch
Code/Common/Networking/TwitchRouter.swift
1
3295
// Copyright (c) 2015 Benoit Layer // // 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 Alamofire enum TwitchRouter { static let baseURLString = Constants.ApiURL static let tokenURLString = Constants.ApiURLToken static let perPage: Int = 20 case gamesTop(page: Int) case searchGames(query: String) case streams(gameName: String?, page: Int) case searchStream(query: String, page: Int) case accessToken(channelName: String) var pathAndParams: (path: String, parameters: [String:Any]) { switch self { case .gamesTop(let page): return ("/games/top", ["limit":TwitchRouter.perPage, "offset":page*TwitchRouter.perPage]) case .searchGames(let query): return ("/search/games", ["live":true, "type":"suggest", "query":query]) case .streams(let gameName, let page): var params: [String:Any] = [:] if let gameName = gameName { params["game"] = gameName } params["limit"] = TwitchRouter.perPage params["offset"] = page*TwitchRouter.perPage return ("/streams", params) case .searchStream(let query, let page): var params: [String:Any] = [:] params["query"] = query params["limit"] = TwitchRouter.perPage params["offset"] = page*TwitchRouter.perPage return ("/search/streams", params) case .accessToken(let channelName): return ("/channels/\(channelName)/access_token", [:]) } } func asURLRequest() throws -> URLRequest { let stringAPIURL: String = { switch self { case .gamesTop(_), .searchGames(_), .streams(_, _), .searchStream(_, _): return TwitchRouter.baseURLString case .accessToken(_): return TwitchRouter.tokenURLString } }() let URL = Foundation.URL(string: stringAPIURL)! let URLRequest = Foundation.URLRequest(url: URL.appendingPathComponent(pathAndParams.path)) let encoding = URLEncoding() return try encoding.encode(URLRequest, with: pathAndParams.parameters) } var URLString: String { let urlDetails = pathAndParams switch self { case .accessToken(_): return TwitchRouter.tokenURLString + urlDetails.path default: return TwitchRouter.baseURLString + urlDetails.path } } var method: Alamofire.HTTPMethod { switch self { default: return .get } } } extension TwitchRouter: URLRequestConvertible { }
bsd-3-clause
a4e66755a14fca07ccf9e09062aa5d4d
34.053191
93
0.723824
3.913302
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift
2
12326
// // YAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class YAxisRendererHorizontalBarChart: YAxisRenderer { public override init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. open override func computeAxis(min: Double, max: Double, inverted: Bool) { guard let transformer = self.transformer else { return } var min = min, max = max // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if !inverted { min = Double(p1.x) max = Double(p2.x) } else { min = Double(p2.x) max = Double(p1.x) } } computeAxisValues(min: min, max: max) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let lineHeight = yAxis.labelFont.lineHeight let baseYOffset: CGFloat = 2.5 let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var yPos: CGFloat = 0.0 if dependency == .left { if labelPosition == .outsideChart { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if labelPosition == .outsideChart { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels( context: context, fixedPosition: yPos, positions: transformedPositions(), offset: yAxis.yOffset) } open override func renderAxisLine(context: CGContext) { guard let yAxis = axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if yAxis.axisLineDashLengths != nil { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if yAxis.axisDependency == .left { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position @objc open func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1) for i in stride(from: from, to: to, by: 1) { let text = yAxis.getFormattedLabel(i) ChartUtils.drawText( context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor]) } } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler.contentRect let dx = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.x -= dx / 2.0 contentRect.size.width += dx return contentRect } open override func drawGridLine( context: CGContext, position: CGPoint) { context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.strokePath() } open override func transformedPositions() -> [CGPoint] { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return [CGPoint]() } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entryCount) let entries = yAxis.entries for i in stride(from: 0, to: yAxis.entryCount, by: 1) { positions.append(CGPoint(x: entries[i], y: 0.0)) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. open override func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= yAxis.zeroLineWidth / 2.0 clippingRect.size.width += yAxis.zeroLineWidth context.clip(to: clippingRect) context.setStrokeColor(zeroLineColor.cgColor) context.setLineWidth(yAxis.zeroLineWidth) let pos = transformer.pixelForValues(x: 0.0, y: 0.0) if yAxis.zeroLineDashLengths != nil { context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.move(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentBottom)) context.drawPath(using: CGPathDrawingMode.stroke) } private var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderLimitLines(context: CGContext) { guard let yAxis = axis as? YAxis, let transformer = self.transformer else { return } var limitLines = yAxis.limitLines if limitLines.count <= 0 { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= l.lineWidth / 2.0 clippingRect.size.width += l.lineWidth context.clip(to: clippingRect) position.x = CGFloat(l.limit) position.y = 0.0 position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = l.lineWidth + l.xOffset let yOffset: CGFloat = 2.0 + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } } } context.restoreGState() } }
apache-2.0
1954de0822f4d404c67142901d2f9ae1
32.585831
137
0.541538
5.4685
false
false
false
false
carlynorama/learningSwift
Projects/Prime Number Checker iOS10/Prime Number Checker iOS10/AppDelegate.swift
1
4626
// // AppDelegate.swift // Prime Number Checker iOS10 // // Created by Carlyn Maw on 8/24/16. // Copyright © 2016 carlynorama. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Prime_Number_Checker_iOS10") 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
e14fd3101e0c0fb931a49c849907f560
48.731183
285
0.686919
5.788486
false
false
false
false
zhxnlai/Algorithms
swift/Remove Element.playground/Contents.swift
2
597
// Playground - noun: a place where people can play import UIKit /*: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn’t matter what you leave beyond the new length. */ var A = [1,2,2,2,3,4,5,5,6,7] func removeElement(a:[Int], e:Int) -> [Int] { var index = 0, r = [Int](a) for var i=0; i<r.count; i++ { if r[i] != e { r[index] = r[i] index++ } } return [Int](r[0..<index]) } removeElement(A, 5) removeElement(A, 1) removeElement(A, 2)
mit
9be4468fc768778af413f17e288e046a
21.846154
192
0.591597
2.975
false
false
false
false
apple/swift-nio
Tests/NIOTestUtilsTests/EventCounterHandlerTest+XCTest.swift
1
1730
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // EventCounterHandlerTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension EventCounterHandlerTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (EventCounterHandlerTest) -> () throws -> Void)] { return [ ("testNothingButEmbeddedChannelInit", testNothingButEmbeddedChannelInit), ("testNothing", testNothing), ("testInboundWrite", testInboundWrite), ("testOutboundWrite", testOutboundWrite), ("testConnectChannel", testConnectChannel), ("testBindChannel", testBindChannel), ("testConnectAndCloseChannel", testConnectAndCloseChannel), ("testError", testError), ("testEventsWithoutArguments", testEventsWithoutArguments), ("testInboundUserEvent", testInboundUserEvent), ("testOutboundUserEvent", testOutboundUserEvent), ] } }
apache-2.0
7ab1800bcd5a9cdb0df2c2235bec0a11
38.318182
162
0.610983
5.389408
false
true
false
false
castial/Quick-Start-iOS
Quick-Start-iOS/Vendors/HYFPSLabel/HYFPSLabel.swift
1
2763
// // HYFPSLabel.swift // Quick-Start-iOS // // Created by work on 2016/11/14. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit class HYFPSLabel: UILabel { fileprivate var link: CADisplayLink = CADisplayLink () fileprivate var count: UInt = 0 fileprivate var lastTime: TimeInterval = TimeInterval () fileprivate var subFont: UIFont = UIFont () override init(frame: CGRect) { super.init(frame: frame) self.layer.cornerRadius = 5 self.clipsToBounds = true self.textAlignment = .center self.isUserInteractionEnabled = false self.backgroundColor = UIColor (white: 0.0, alpha: 0.7) self.font = UIFont (name: "Menlo", size: 14) self.subFont = UIFont (name: "Menlo", size: 8)! self.link = CADisplayLink (target: self, selector: #selector (tick(link:))) self.link .add(to: RunLoop.main, forMode: .commonModes) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeThatFits(_ size: CGSize) -> CGSize { return HYFPSLabel.defaultSize } deinit { self.link.invalidate() } } // MARK: - Public Methods extension HYFPSLabel { open func showFPS() { let window: UIWindow = UIApplication.shared.keyWindow! window.addSubview(self) } } // MARK: - Events extension HYFPSLabel { @objc fileprivate func tick(link: CADisplayLink) { if self.lastTime == 0 { self.lastTime = link.timestamp return } self.count += 1 let delta: TimeInterval = link.timestamp - lastTime if delta < 1 { return } self.lastTime = link.timestamp let fps: Float = Float (self.count) / Float (delta) self.count = 0 let progress: CGFloat = CGFloat (fps / 60.0) let color: UIColor = UIColor (hue: 0.27 * (progress - 0.2), saturation: 1, brightness: 0.9, alpha: 1) let text: NSMutableAttributedString = NSMutableAttributedString (string: "\(round(fps)) FPS") text.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, text.length - 3)) text.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(text.length - 3, 3)) text.addAttribute(NSFontAttributeName, value: self.font, range: NSMakeRange(0, text.length)) text.addAttribute(NSFontAttributeName, value: self.subFont, range: NSMakeRange(text.length - 3, 3)) self.attributedText = text; } } // MARK: - Constants extension HYFPSLabel { static let defaultSize: CGSize = CGSize (width: 65, height: 20) }
mit
29d1dd698a08c1271f209a84eb2f39f6
31.470588
119
0.628623
4.272446
false
false
false
false
jkiley129/Photos
Photos-Demo/Photos-Demo/ImageItem.swift
1
1029
// // ImageItem.swift // Photos-Demo // // Created by Joseph Kiley on 6/10/16. // Copyright © 2016 Joseph Kiley. All rights reserved. // import UIKit class ImageItem: NSObject { // MARK: - Variables var imageURL: String = "" var imageName: String = "" var imageDescription: String = "" var imageData: NSData? var image: UIImage? init(imageURL: String, imageName: String, imageDescription: String) { self.imageURL = imageURL self.imageName = imageName self.imageDescription = imageDescription } // MARK: - Initialization required init?(JSON: [String : AnyObject]) { if let imageURL: String = JSON["imageURL"] as? String { self.imageURL = imageURL } if let imageName: String = JSON["imageName"] as? String { self.imageName = imageName } if let imageDescription: String = JSON["imageDescription"] as? String { self.imageDescription = imageDescription } } }
mit
b98c10d4c03dc5e695ca79de0b2f8ff2
25.358974
79
0.608949
4.431034
false
false
false
false
kildevaeld/location
Pod/Classes/MKMapView.swift
1
1105
// // MKMapView.swift // Pods // // Created by Rasmus Kildevæld on 18/10/2015. // // import Foundation import MapKit public extension MKMapView { /*public var distance : CLLocationDistance { get { var dis: AnyObject! = objc_getAssociatedObject(self, &kDistanceKey) if dis == nil { dis = 100.0 } return dis as! CLLocationDistance } set (value) { objc_setAssociatedObject(self, &kDistanceKey, value,.OBJC_ASSOCIATION_COPY_NONATOMIC) } }*/ public func setLocationWithCoordinates(coordinate: CLLocationCoordinate2D, distance:CLLocationDistance, animated: Bool) { let region = MKCoordinateRegionMakeWithDistance(coordinate, distance, distance) self.setRegion(region, animated: animated) } public func setLocation(location: CLLocation, distance:CLLocationDistance, animated: Bool) { self.setLocationWithCoordinates(location.coordinate, distance: distance, animated: animated) } }
mit
611389bc27cea5cf0498eac9ad8a9f20
26.625
125
0.622283
4.972973
false
false
false
false
zhiquan911/CHKLineChart
CHKLineChart/Example-ObjC/Pods/CHKLineChartKit/CHKLineChart/CHKLineChart/Classes/CHKLineChart.swift
1
63925
// // CHKLineChart.swift // CHKLineChart // // Created by Chance on 16/9/6. // Copyright © 2016年 Chance. All rights reserved. // import UIKit /** 图表滚动到那个位置 - top: 头部 - end: 尾部 - None: 不处理 */ public enum CHChartViewScrollPosition { case top, end, none } /// 图表选中的十字y轴显示位置 /// /// - free: 自由就在显示的点上 /// - onClosePrice: 在收盘价上 public enum CHChartSelectedPosition { case free case onClosePrice } /** * K线数据源代理 */ @objc public protocol CHKLineChartDelegate: class { /** 数据源总数 - parameter chart: - returns: */ func numberOfPointsInKLineChart(chart: CHKLineChartView) -> Int /** 数据源索引为对应的对象 - parameter chart: - parameter index: 索引位 - returns: K线数据对象 */ func kLineChart(chart: CHKLineChartView, valueForPointAtIndex index: Int) -> CHChartItem /** 获取图表Y轴的显示的内容 - parameter chart: - parameter value: 计算得出的y值 - returns: */ func kLineChart(chart: CHKLineChartView, labelOnYAxisForValue value: CGFloat, atIndex index: Int, section: CHSection) -> String /** 获取图表X轴的显示的内容 - parameter chart: - parameter index: 索引位 - returns: */ @objc optional func kLineChart(chart: CHKLineChartView, labelOnXAxisForIndex index: Int) -> String /** 完成绘画图表 */ @objc optional func didFinishKLineChartRefresh(chart: CHKLineChartView) /// 配置各个分区小数位保留数 /// /// - parameter chart: /// - parameter decimalForSection: 分区 /// /// - returns: @objc optional func kLineChart(chart: CHKLineChartView, decimalAt section: Int) -> Int /// 设置y轴标签的宽度 /// /// - parameter chart: /// /// - returns: @objc optional func widthForYAxisLabelInKLineChart(in chart: CHKLineChartView) -> CGFloat /// 点击图表列响应方法 /// /// - Parameters: /// - chart: 图表 /// - index: 点击的位置 /// - item: 数据对象 @objc optional func kLineChart(chart: CHKLineChartView, didSelectAt index: Int, item: CHChartItem) /// X轴的布局高度 /// /// - Parameter chart: 图表 /// - Returns: 返回自定义的高度 @objc optional func heightForXAxisInKLineChart(in chart: CHKLineChartView) -> CGFloat /// 初始化时的显示范围长度 /// /// - Parameter chart: 图表 @objc optional func initRangeInKLineChart(in chart: CHKLineChartView) -> Int /// 自定义选择点时出现的标签样式 /// /// - Parameters: /// - chart: 图表 /// - yAxis: 可给用户自定义的y轴显示标签 /// - viewOfXAxis: 可给用户自定义的x轴显示标签 @objc optional func kLineChart(chart: CHKLineChartView, viewOfYAxis yAxis: UILabel, viewOfXAxis: UILabel) /// 自定义section的头部View显示内容 /// /// - Parameters: /// - chart: 图表 /// - section: 分区的索引位 /// - Returns: 自定义的View @objc optional func kLineChart(chart: CHKLineChartView, viewForHeaderInSection section: Int) -> UIView? /// 自定义section的头部View显示内容 /// /// - Parameters: /// - chart: 图表 /// - section: 分区的索引位 /// - Returns: 自定义的View @objc optional func kLineChart(chart: CHKLineChartView, titleForHeaderInSection section: CHSection, index: Int, item: CHChartItem) -> NSAttributedString? /// 切换分区用分页方式展示的线组 /// @objc optional func kLineChart(chart: CHKLineChartView, didFlipPageSeries section: CHSection, series: CHSeries, seriesIndex: Int) } open class CHKLineChartView: UIView { /// MARK: - 常量 let kMinRange = 13 //最小缩放范围 let kMaxRange = 133 //最大缩放范围 let kPerInterval = 4 //缩放的每段间隔 open let kYAxisLabelWidth: CGFloat = 46 //默认宽度 open let kXAxisHegiht: CGFloat = 16 //默认X坐标的高度 /// MARK: - 成员变量 @IBInspectable open var upColor: UIColor = UIColor.green //升的颜色 @IBInspectable open var downColor: UIColor = UIColor.red //跌的颜色 @IBInspectable open var labelFont = UIFont.systemFont(ofSize: 10) @IBInspectable open var lineColor: UIColor = UIColor(white: 0.2, alpha: 1) //线条颜色 @IBInspectable open var textColor: UIColor = UIColor(white: 0.8, alpha: 1) //文字颜色 @IBInspectable open var xAxisPerInterval: Int = 4 //x轴的间断个数 open var yAxisLabelWidth: CGFloat = 0 //Y轴的宽度 open var handlerOfAlgorithms: [CHChartAlgorithmProtocol] = [CHChartAlgorithmProtocol]() open var padding: UIEdgeInsets = UIEdgeInsets.zero //内边距 open var showYAxisLabel = CHYAxisShowPosition.right //显示y的位置,默认右边 open var isInnerYAxis: Bool = false // 是否把y坐标内嵌到图表中 open var selectedPosition: CHChartSelectedPosition = .onClosePrice //选中显示y值的位置 @IBOutlet open weak var delegate: CHKLineChartDelegate? //代理 open var sections = [CHSection]() open var selectedIndex: Int = -1 //选择索引位 open var scrollToPosition: CHChartViewScrollPosition = .none //图表刷新后开始显示位置 var selectedPoint: CGPoint = CGPoint.zero //是否可缩放 open var enablePinch: Bool = true //是否可滑动 open var enablePan: Bool = true //是否可点选 open var enableTap: Bool = true { didSet { self.showSelection = self.enableTap } } /// 是否显示选中的内容 open var showSelection: Bool = true { didSet { self.selectedXAxisLabel?.isHidden = !self.showSelection self.selectedYAxisLabel?.isHidden = !self.showSelection self.verticalLineView?.isHidden = !self.showSelection self.horizontalLineView?.isHidden = !self.showSelection self.sightView?.isHidden = !self.showSelection } } /// 把X坐标内容显示到哪个索引分区上,默认为-1,表示最后一个,如果用户设置溢出的数值,也以最后一个 open var showXAxisOnSection: Int = -1 /// 是否显示X轴标签 open var showXAxisLabel: Bool = true /// 是否显示所有内容 open var isShowAll: Bool = false /// 显示边线上左下有 open var borderWidth: (top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) = (0.25, 0.25, 0.25, 0.25) var lineWidth: CGFloat = 0.5 var plotCount: Int = 0 var rangeFrom: Int = 0 //可见区域的开始索引位 var rangeTo: Int = 0 //可见区域的结束索引位 open var range: Int = 77 //显示在可见区域的个数 var borderColor: UIColor = UIColor.gray open var labelSize = CGSize(width: 40, height: 16) var datas: [CHChartItem] = [CHChartItem]() //数据源 open var selectedBGColor: UIColor = UIColor(white: 0.4, alpha: 1) //选中点的显示的框背景颜色 open var selectedTextColor: UIColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) //选中点的显示的文字颜色 var verticalLineView: UIView? var horizontalLineView: UIView? var selectedXAxisLabel: UILabel? var selectedYAxisLabel: UILabel? var sightView: UIView? //点击出现的准星 //动力学引擎 lazy var animator: UIDynamicAnimator = UIDynamicAnimator(referenceView: self) //动力的作用点 lazy var dynamicItem = CHDynamicItem() //滚动图表时用于处理线性减速 weak var decelerationBehavior: UIDynamicItemBehavior? //滚动释放后用于反弹回来 weak var springBehavior: UIAttachmentBehavior? //减速开始x var decelerationStartX: CGFloat = 0 /// 用于图表的图层 var drawLayer: CHShapeLayer = CHShapeLayer() /// 点线图层 var chartModelLayer: CHShapeLayer = CHShapeLayer() /// 图表数据信息显示层,显示每个分区的数值内容 var chartInfoLayer: CHShapeLayer = CHShapeLayer() open var style: CHKLineChartStyle! { //显示样式 didSet { //重新配置样式 self.sections = self.style.sections self.backgroundColor = self.style.backgroundColor self.padding = self.style.padding self.handlerOfAlgorithms = self.style.algorithms self.lineColor = self.style.lineColor self.textColor = self.style.textColor self.labelFont = self.style.labelFont self.showYAxisLabel = self.style.showYAxisLabel self.selectedBGColor = self.style.selectedBGColor self.selectedTextColor = self.style.selectedTextColor self.isInnerYAxis = self.style.isInnerYAxis self.enableTap = self.style.enableTap self.enablePinch = self.style.enablePinch self.enablePan = self.style.enablePan self.showSelection = self.style.showSelection self.showXAxisOnSection = self.style.showXAxisOnSection self.isShowAll = self.style.isShowAll self.showXAxisLabel = self.style.showXAxisLabel self.borderWidth = self.style.borderWidth } } public override init(frame: CGRect) { super.init(frame: frame) self.initUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //self.initUI() } open override func awakeFromNib() { super.awakeFromNib() self.initUI() } // convenience init(style: CHKLineChartStyle) { // self.init() // self.initUI() // self.style = style // } /** 初始化UI - returns: */ fileprivate func initUI() { self.isMultipleTouchEnabled = true //初始化点击选择的辅助线显示 self.verticalLineView = UIView(frame: CGRect(x: 0, y: 0, width: lineWidth, height: 0)) self.verticalLineView?.backgroundColor = self.selectedBGColor self.verticalLineView?.isHidden = true self.addSubview(self.verticalLineView!) self.horizontalLineView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: lineWidth)) self.horizontalLineView?.backgroundColor = self.selectedBGColor self.horizontalLineView?.isHidden = true self.addSubview(self.horizontalLineView!) //用户点击图表显示当前y轴的实际值 self.selectedYAxisLabel = UILabel(frame: CGRect.zero) self.selectedYAxisLabel?.backgroundColor = self.selectedBGColor self.selectedYAxisLabel?.isHidden = true self.selectedYAxisLabel?.font = self.labelFont self.selectedYAxisLabel?.minimumScaleFactor = 0.5 self.selectedYAxisLabel?.lineBreakMode = .byClipping self.selectedYAxisLabel?.adjustsFontSizeToFitWidth = true self.selectedYAxisLabel?.textColor = self.selectedTextColor self.selectedYAxisLabel?.textAlignment = NSTextAlignment.center self.addSubview(self.selectedYAxisLabel!) //用户点击图表显示当前x轴的实际值 self.selectedXAxisLabel = UILabel(frame: CGRect.zero) self.selectedXAxisLabel?.backgroundColor = self.selectedBGColor self.selectedXAxisLabel?.isHidden = true self.selectedXAxisLabel?.font = self.labelFont self.selectedXAxisLabel?.textColor = self.selectedTextColor self.selectedXAxisLabel?.textAlignment = NSTextAlignment.center self.addSubview(self.selectedXAxisLabel!) self.sightView = UIView(frame: CGRect(x: 0, y: 0, width: 6, height: 6)) self.sightView?.backgroundColor = self.selectedBGColor self.sightView?.isHidden = true self.sightView?.layer.cornerRadius = 3 self.addSubview(self.sightView!) //绘画图层 self.layer.addSublayer(self.drawLayer) //添加手势操作 let pan = UIPanGestureRecognizer( target: self, action: #selector(doPanAction(_:))) pan.delegate = self self.addGestureRecognizer(pan) //点击手势操作 let tap = UITapGestureRecognizer(target: self, action: #selector(doTapAction(_:))) tap.delegate = self self.addGestureRecognizer(tap) //双指缩放操作 let pinch = UIPinchGestureRecognizer( target: self, action: #selector(doPinchAction(_:))) pinch.delegate = self self.addGestureRecognizer(pinch) //长按手势操作 let longPress = UILongPressGestureRecognizer(target: self, action: #selector(doLongPressAction(_:))) //长按时间为1秒 longPress.minimumPressDuration = 0.5 self.addGestureRecognizer(longPress) //加载一个初始化的Range值 if let userRange = self.delegate?.initRangeInKLineChart?(in: self) { self.range = userRange } //初始数据 self.resetData() } open override func layoutSubviews() { super.layoutSubviews() //布局完成重绘 self.drawLayerView() } /** 初始化数据 */ fileprivate func resetData() { self.datas.removeAll() self.plotCount = self.delegate?.numberOfPointsInKLineChart(chart: self) ?? 0 if plotCount > 0 { //获取代理上的数据源 for i in 0...self.plotCount - 1 { let item = self.delegate?.kLineChart(chart: self, valueForPointAtIndex: i) self.datas.append(item!) } //执行算法方程式计算值,添加到对象中 for algorithm in self.handlerOfAlgorithms { //执行该算法,计算指标数据 self.datas = algorithm.handleAlgorithm(self.datas) } } } /** 获取点击区域所在分区位 - parameter point: 点击坐标 - returns: 返回section和索引位 */ func getSectionByTouchPoint(_ point: CGPoint) -> (Int, CHSection?) { for (i, section) in self.sections.enumerated() { if section.frame.contains(point) { return (i, section) } } return (-1, nil) } /// 取显示X轴坐标的分区 /// /// - Returns: func getSecionWhichShowXAxis() -> CHSection { let visiableSection = self.sections.filter { !$0.hidden } var showSection: CHSection? for (i, section) in visiableSection.enumerated() { //用户自定义显示X轴的分区 if section.index == self.showXAxisOnSection { showSection = section } //如果最后都没有找到,取最后一个做显示 if i == visiableSection.count - 1 && showSection == nil{ showSection = section } } return showSection! } /** 设置选中的数据点 - parameter point: */ func setSelectedIndexByPoint(_ point: CGPoint) { guard self.enableTap else { return } // self.selectedXAxisLabel?.isHidden = !self.showSelection // self.selectedYAxisLabel?.isHidden = !self.showSelection // self.verticalLineView?.isHidden = !self.showSelection // self.horizontalLineView?.isHidden = !self.showSelection // self.sightView?.isHidden = !self.showSelection if point.equalTo(CGPoint.zero) { return } let (_, section) = self.getSectionByTouchPoint(point) if section == nil { return } let visiableSections = self.sections.filter { !$0.hidden } guard let lastSection = visiableSections.last else { return } let showXAxisSection = self.getSecionWhichShowXAxis() //重置文字颜色和字体 self.selectedYAxisLabel?.font = self.labelFont self.selectedYAxisLabel?.backgroundColor = self.selectedBGColor self.selectedYAxisLabel?.textColor = self.selectedTextColor self.selectedXAxisLabel?.font = self.labelFont self.selectedXAxisLabel?.backgroundColor = self.selectedBGColor self.selectedXAxisLabel?.textColor = self.selectedTextColor let yaxis = section!.yAxis let format = "%.".appendingFormat("%df", yaxis.decimal) self.selectedPoint = point //每个点的间隔宽度 let plotWidth = (section!.frame.size.width - section!.padding.left - section!.padding.right) / CGFloat(self.rangeTo - self.rangeFrom) var yVal: CGFloat = 0 //获取y轴坐标的实际值 for i in self.rangeFrom...self.rangeTo - 1 { let ixs = plotWidth * CGFloat(i - self.rangeFrom) + section!.padding.left + self.padding.left let ixe = plotWidth * CGFloat(i - self.rangeFrom + 1) + section!.padding.left + self.padding.left // NSLog("ixs = \(ixs)") // NSLog("ixe = \(ixe)") // NSLog("point.x = \(point.x)") if ixs <= point.x && point.x < ixe { self.selectedIndex = i let item = self.datas[i] var hx = section!.frame.origin.x + section!.padding.left hx = hx + plotWidth * CGFloat(i - self.rangeFrom) + plotWidth / 2 let hy = self.padding.top let hheight = lastSection.frame.maxY //显示辅助线 self.horizontalLineView?.frame = CGRect(x: hx, y: hy, width: self.lineWidth, height: hheight) // self.horizontalLineView?.isHidden = false let vx = section!.frame.origin.x + section!.padding.left var vy: CGFloat = 0 //处理水平线y的值 switch self.selectedPosition { case .free: vy = point.y yVal = section!.getRawValue(point.y) //获取y轴坐标的实际值 case .onClosePrice: if let series = section?.getSeries(key: CHSeriesKey.candle), !series.hidden { yVal = item.closePrice //获取收盘价作为实际值 } else if let series = section?.getSeries(key: CHSeriesKey.timeline), !series.hidden { yVal = item.closePrice //获取收盘价作为实际值 } else if let series = section?.getSeries(key: CHSeriesKey.volume), !series.hidden { yVal = item.vol //获取交易量作为实际值 } vy = section!.getLocalY(yVal) } let hwidth = section!.frame.size.width - section!.padding.left - section!.padding.right //显示辅助线 self.verticalLineView?.frame = CGRect(x: vx, y: vy - self.lineWidth / 2, width: hwidth, height: self.lineWidth) // self.verticalLineView?.isHidden = false //显示y轴辅助内容 //控制y轴的label在左还是右显示 var yAxisStartX: CGFloat = 0 // self.selectedYAxisLabel?.isHidden = false // self.selectedXAxisLabel?.isHidden = false switch self.showYAxisLabel { case .left: yAxisStartX = section!.frame.origin.x case .right: yAxisStartX = section!.frame.maxX - self.yAxisLabelWidth case .none: self.selectedYAxisLabel?.isHidden = true } self.selectedYAxisLabel?.text = String(format: format, yVal) //显示实际值 self.selectedYAxisLabel?.frame = CGRect(x: yAxisStartX, y: vy - self.labelSize.height / 2, width: self.yAxisLabelWidth, height: self.labelSize.height) let time = Date.ch_getTimeByStamp(item.time, format: "yyyy-MM-dd HH:mm") //显示实际值 let size = time.ch_sizeWithConstrained(self.labelFont) self.selectedXAxisLabel?.text = time //判断x是否超过左右边界 let labelWidth = size.width + 6 var x = hx - (labelWidth) / 2 if x < section!.frame.origin.x { x = section!.frame.origin.x } else if x + labelWidth > section!.frame.origin.x + section!.frame.size.width { x = section!.frame.origin.x + section!.frame.size.width - labelWidth } self.selectedXAxisLabel?.frame = CGRect(x: x, y: showXAxisSection.frame.maxY, width: size.width + 6, height: self.labelSize.height) self.sightView?.center = CGPoint(x: hx, y: vy) //给用户进行最后的自定义 self.delegate?.kLineChart?(chart: self, viewOfYAxis: self.selectedXAxisLabel!, viewOfXAxis: self.selectedYAxisLabel!) self.showSelection = true self.bringSubview(toFront: self.verticalLineView!) self.bringSubview(toFront: self.horizontalLineView!) self.bringSubview(toFront: self.selectedXAxisLabel!) self.bringSubview(toFront: self.selectedYAxisLabel!) self.bringSubview(toFront: self.sightView!) //设置选中点 self.setSelectedIndexByIndex(i) break } } } /** 设置选中的数据点 - parameter index: 选中位置 */ func setSelectedIndexByIndex(_ index: Int) { guard index >= self.rangeFrom && index < self.rangeTo else { return } self.selectedIndex = index let item = self.datas[index] //显示分区的header标题 for (_, section) in self.sections.enumerated() { if section.hidden { continue } if let titleString = self.delegate?.kLineChart?(chart: self, titleForHeaderInSection: section, index: index, item: self.datas[index]) { //显示用户自定义的title section.drawTitleForHeader(title: titleString) } else { //显示默认 section.drawTitle(index) } } //回调给代理委托方法 self.delegate?.kLineChart?(chart: self, didSelectAt: index, item: item) } } // MARK: - 绘图相关方法 extension CHKLineChartView { /// 清空图表的子图层 func removeLayerView() { for section in self.sections { section.removeLayerView() for series in section.series { series.removeLayerView() } } _ = self.drawLayer.sublayers?.map { $0.removeFromSuperlayer() } self.drawLayer.sublayers?.removeAll() } /// 通过CALayer方式画图表 func drawLayerView() { //先清空图层 self.removeLayerView() //初始化数据 if self.initChart() { /// 待绘制的x坐标标签 var xAxisToDraw = [(CGRect, String)]() //建立每个分区 self.buildSections { (section, index) in //获取各section的小数保留位数 let decimal = self.delegate?.kLineChart?(chart: self, decimalAt: index) ?? 2 section.decimal = decimal //初始Y轴的数据 self.initYAxis(section) //绘制每个区域 self.drawSection(section) //绘制X轴坐标系,先绘制辅助线,记录标签位置, //返回出来,最后才在需要显示的分区上绘制 xAxisToDraw = self.drawXAxis(section) //绘制Y轴坐标系,但最后的y轴标签放到绘制完线段才做 let yAxisToDraw = self.drawYAxis(section) //绘制图表的点线 self.drawChart(section) //绘制Y轴坐标上的标签 self.drawYAxisLabel(yAxisToDraw) //把标题添加到主绘图层上 self.drawLayer.addSublayer(section.titleLayer) //是否采用用户自定义 if let titleView = self.delegate?.kLineChart?(chart: self, viewForHeaderInSection: index) { //显示用户自定义的View,显示内容交由委托者 section.showTitle = false section.addCustomView(titleView, inView: self) } else { if let titleString = self.delegate?.kLineChart?(chart: self, titleForHeaderInSection: section, index: self.selectedIndex, item: self.datas[self.selectedIndex]) { //显示用户自定义的section title section.drawTitleForHeader(title: titleString) } else { //显示范围最后一个点的内容 section.drawTitle(self.selectedIndex) } } } let showXAxisSection = self.getSecionWhichShowXAxis() //显示在分区下面绘制X轴坐标 self.drawXAxisLabel(showXAxisSection, xAxisToDraw: xAxisToDraw) //重新显示点击选中的坐标 //self.setSelectedIndexByPoint(self.selectedPoint) self.delegate?.didFinishKLineChartRefresh?(chart: self) } } /** 绘制图表 - parameter rect: override open func draw(_ rect: CGRect) { } */ /** 初始化图表结构 - returns: 是否初始化数据 */ fileprivate func initChart() -> Bool { self.plotCount = self.delegate?.numberOfPointsInKLineChart(chart: self) ?? 0 //数据条数不一致,需要重新计算 if self.plotCount != self.datas.count { self.resetData() } if plotCount > 0 { //如果显示全部,显示范围为全部数据量 if self.isShowAll { self.range = self.plotCount self.rangeFrom = 0 self.rangeTo = self.plotCount } //图表刷新滚动为默认时,如果第一次初始化,就默认滚动到最后显示 if self.scrollToPosition == .none { //如果图表尽头的索引为0,则进行初始化 if self.rangeTo == 0 || self.plotCount < self.rangeTo { self.scrollToPosition = .end } } if self.scrollToPosition == .top { self.rangeFrom = 0 if self.rangeFrom + self.range < self.plotCount { self.rangeTo = self.rangeFrom + self.range //计算结束的显示的位置 } else { self.rangeTo = self.plotCount } self.selectedIndex = -1 } else if self.scrollToPosition == .end { self.rangeTo = self.plotCount //默认是数据最后一条为尽头 if self.rangeTo - self.range > 0 { //如果尽头 - 默认显示数大于0 self.rangeFrom = self.rangeTo - range //计算开始的显示的位置 } else { self.rangeFrom = 0 } self.selectedIndex = -1 } } //重置图表刷新滚动默认不处理 self.scrollToPosition = .none //选择最后一个元素选中 if selectedIndex == -1 { self.selectedIndex = self.rangeTo - 1 } let backgroundLayer = CHShapeLayer() let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.bounds.size.width,height: self.bounds.size.height), cornerRadius: 0) backgroundLayer.path = backgroundPath.cgPath backgroundLayer.fillColor = self.backgroundColor?.cgColor self.drawLayer.addSublayer(backgroundLayer) // let context = UIGraphicsGetCurrentContext() // context?.setFillColor(self.backgroundColor!.cgColor) // context?.fill (CGRect (x: 0, y: 0, width: self.bounds.size.width,height: self.bounds.size.height)) return self.datas.count > 0 ? true : false } /** 初始化各个分区 - parameter complete: 初始化后,执行每个分区绘制 */ fileprivate func buildSections( _ complete:(_ section: CHSection, _ index: Int) -> Void) { //计算实际的显示高度和宽度 var height = self.frame.size.height - (self.padding.top + self.padding.bottom) let width = self.frame.size.width - (self.padding.left + self.padding.right) let xAxisHeight = self.delegate?.heightForXAxisInKLineChart?(in: self) ?? self.kXAxisHegiht height = height - xAxisHeight var total = 0 for (index, section) in self.sections.enumerated() { section.index = index if !section.hidden { //如果使用fixHeight,ratios要设置为0 if section.ratios > 0 { total = total + section.ratios } } } var offsetY: CGFloat = self.padding.top //计算每个区域的高度,并绘制 for (index, section) in self.sections.enumerated() { var heightOfSection: CGFloat = 0 let WidthOfSection = width if section.hidden { continue } //计算每个区域的高度 //如果fixHeight大于0,有限使用fixHeight设置高度, if section.fixHeight > 0 { heightOfSection = section.fixHeight height = height - heightOfSection } else { heightOfSection = height * CGFloat(section.ratios) / CGFloat(total) } self.yAxisLabelWidth = self.delegate?.widthForYAxisLabelInKLineChart?(in: self) ?? self.kYAxisLabelWidth //y轴的标签显示方位 switch self.showYAxisLabel { case .left: //左边显示 section.padding.left = self.isInnerYAxis ? section.padding.left : self.yAxisLabelWidth section.padding.right = 0 case .right: //右边显示 section.padding.left = 0 section.padding.right = self.isInnerYAxis ? section.padding.right : self.yAxisLabelWidth case .none: //都不显示 section.padding.left = 0 section.padding.right = 0 } //计算每个section的坐标 section.frame = CGRect(x: 0 + self.padding.left, y: offsetY, width: WidthOfSection, height: heightOfSection) offsetY = offsetY + section.frame.height //如果这个分区设置为显示X轴,下一个分区的Y起始位要加上X轴高度 if self.showXAxisOnSection == index { offsetY = offsetY + xAxisHeight } complete(section, index) } } /** 绘制X轴上的标签 - parameter padding: 内边距 - parameter width: 总宽度 */ fileprivate func drawXAxis(_ section: CHSection) -> [(CGRect, String)] { var xAxisToDraw = [(CGRect, String)]() let xAxis = CHShapeLayer() var startX: CGFloat = section.frame.origin.x + section.padding.left let endX: CGFloat = section.frame.origin.x + section.frame.size.width - section.padding.right let secWidth: CGFloat = section.frame.size.width let secPaddingLeft: CGFloat = section.padding.left let secPaddingRight: CGFloat = section.padding.right //x轴分平均分4个间断,显示5个x轴坐标,按照图表的值个数,计算每个间断的个数 let dataRange = self.rangeTo - self.rangeFrom var xTickInterval: Int = dataRange / self.xAxisPerInterval if xTickInterval <= 0 { xTickInterval = 1 } //绘制x轴标签 //每个点的间隔宽度 let perPlotWidth: CGFloat = (secWidth - secPaddingLeft - secPaddingRight) / CGFloat(self.rangeTo - self.rangeFrom) let startY = section.frame.maxY var k: Int = 0 var showXAxisReference = false //相当 for var i = self.rangeFrom; i < self.rangeTo; i = i + xTickInterval for i in stride(from: self.rangeFrom, to: self.rangeTo, by: xTickInterval) { let xLabel = self.delegate?.kLineChart?(chart: self, labelOnXAxisForIndex: i) ?? "" var textSize = xLabel.ch_sizeWithConstrained(self.labelFont) textSize.width = textSize.width + 4 var xPox = startX - textSize.width / 2 + perPlotWidth / 2 //计算最左最右的x轴标签不越过边界 if (xPox < 0) { xPox = startX } else if (xPox + textSize.width > endX) { xPox = endX - textSize.width } // NSLog(@"xPox = %f", xPox) // NSLog(@"textSize.width = %f", textSize.width) let barLabelRect = CGRect(x: xPox, y: startY, width: textSize.width, height: textSize.height) //记录待绘制的文本 xAxisToDraw.append((barLabelRect, xLabel)) //绘制辅助线 let referencePath = UIBezierPath() let referenceLayer = CHShapeLayer() referenceLayer.lineWidth = self.lineWidth //处理辅助线样式 switch section.xAxis.referenceStyle { case let .dash(color: dashColor, pattern: pattern): referenceLayer.strokeColor = dashColor.cgColor referenceLayer.lineDashPattern = pattern showXAxisReference = true case let .solid(color: solidColor): referenceLayer.strokeColor = solidColor.cgColor showXAxisReference = true default: showXAxisReference = false } //需要画x轴上的辅助线 if showXAxisReference { referencePath.move(to: CGPoint(x: xPox + textSize.width / 2, y: section.frame.minY)) referencePath.addLine(to: CGPoint(x: xPox + textSize.width / 2, y: section.frame.maxY)) referenceLayer.path = referencePath.cgPath xAxis.addSublayer(referenceLayer) } k = k + xTickInterval startX = perPlotWidth * CGFloat(k) } self.drawLayer.addSublayer(xAxis) return xAxisToDraw } /// 绘制X坐标标签 /// /// - Parameters: /// - section: 哪个分区绘制 /// - xAxisToDraw: 待绘制的内容 fileprivate func drawXAxisLabel(_ section: CHSection, xAxisToDraw: [(CGRect, String)]) { guard self.showXAxisLabel else { return } guard xAxisToDraw.count > 0 else { return } let xAxis = CHShapeLayer() let startY = section.frame.maxY //需要显示x坐标标签名字的分区,再最下方显示 //绘制x坐标标签,x的位置通过画辅助线时计算得出 for (var barLabelRect, xLabel) in xAxisToDraw { barLabelRect.origin.y = startY //绘制文本 let xLabelText = CHTextLayer() xLabelText.frame = barLabelRect xLabelText.string = xLabel xLabelText.alignmentMode = kCAAlignmentCenter xLabelText.fontSize = self.labelFont.pointSize xLabelText.foregroundColor = self.textColor.cgColor xLabelText.backgroundColor = UIColor.clear.cgColor xLabelText.contentsScale = UIScreen.main.scale xAxis.addSublayer(xLabelText) } self.drawLayer.addSublayer(xAxis) // context?.strokePath() } /** 绘制分区 - parameter section: */ fileprivate func drawSection(_ section: CHSection) { //画分区的背景 let sectionPath = UIBezierPath(rect: section.frame) let sectionLayer = CHShapeLayer() sectionLayer.fillColor = section.backgroundColor.cgColor sectionLayer.path = sectionPath.cgPath self.drawLayer.addSublayer(sectionLayer) let borderPath = UIBezierPath() //画低部边线 if self.borderWidth.bottom > 0 { borderPath.append(UIBezierPath(rect: CGRect(x: section.frame.origin.x + section.padding.left, y: section.frame.size.height + section.frame.origin.y, width: section.frame.size.width - section.padding.left, height: self.borderWidth.bottom))) } //画顶部边线 if self.borderWidth.top > 0 { borderPath.append(UIBezierPath(rect: CGRect(x: section.frame.origin.x + section.padding.left, y: section.frame.origin.y, width: section.frame.size.width - section.padding.left, height: self.borderWidth.top))) } //画左边线 if self.borderWidth.left > 0 { borderPath.append(UIBezierPath(rect: CGRect(x: section.frame.origin.x + section.padding.left, y: section.frame.origin.y, width: self.borderWidth.left, height: section.frame.size.height))) } //画右边线 if self.borderWidth.right > 0 { borderPath.append(UIBezierPath(rect: CGRect(x: section.frame.origin.x + section.frame.size.width - section.padding.right, y: section.frame.origin.y, width: self.borderWidth.left, height: section.frame.size.height))) } //添加到图层 let borderLayer = CHShapeLayer() borderLayer.lineWidth = self.lineWidth borderLayer.path = borderPath.cgPath // 从贝塞尔曲线获取到形状 borderLayer.fillColor = self.lineColor.cgColor // 闭环填充的颜色 self.drawLayer.addSublayer(borderLayer) } /** 初始化分区上各个线的Y轴 */ fileprivate func initYAxis(_ section: CHSection) { if section.series.count > 0 { //建立分区每条线的坐标系 section.buildYAxis(startIndex: self.rangeFrom, endIndex: self.rangeTo, datas: self.datas) } } /** 绘制Y轴左边 - parameter section: 分区 */ fileprivate func drawYAxis(_ section: CHSection) -> [(CGRect, String)] { var yAxisToDraw = [(CGRect, String)]() var valueToDraw = Set<CGFloat>() var startX: CGFloat = 0, startY: CGFloat = 0, extrude: CGFloat = 0 var showYAxisLabel: Bool = true var showYAxisReference: Bool = true //分区中各个y轴虚线和y轴的label //控制y轴的label在左还是右显示 switch self.showYAxisLabel { case .left: startX = section.frame.origin.x - 3 * (self.isInnerYAxis ? -1 : 1) extrude = section.frame.origin.x + section.padding.left - 2 case .right: startX = section.frame.maxX - self.yAxisLabelWidth + 3 * (self.isInnerYAxis ? -1 : 1) extrude = section.frame.origin.x + section.padding.left + section.frame.size.width - section.padding.right case .none: showYAxisLabel = false } let yaxis = section.yAxis //保持Y轴标签个数偶数显示 // if (yaxis.tickInterval % 2 == 1) { // yaxis.tickInterval += 1 // } //计算y轴的标签及虚线分几段 let step = (yaxis.max - yaxis.min) / CGFloat(yaxis.tickInterval) //从base值绘制Y轴标签到最大值 var i = 0 var yVal = yaxis.baseValue + CGFloat(i) * step while yVal <= yaxis.max && i <= yaxis.tickInterval { valueToDraw.insert(yVal) //递增下一个 i = i + 1 yVal = yaxis.baseValue + CGFloat(i) * step } i = 0 yVal = yaxis.baseValue - CGFloat(i) * step while yVal >= yaxis.min && i <= yaxis.tickInterval { valueToDraw.insert(yVal) //递增下一个 i = i + 1 yVal = yaxis.baseValue - CGFloat(i) * step } for (i, yVal) in valueToDraw.enumerated() { //画虚线和Y标签值 let iy = section.getLocalY(yVal) if self.isInnerYAxis { //y轴标签向内显示,为了不挡住辅助线,所以把y轴的数值位置向上移一些 startY = iy - 14 } else { startY = iy - 7 } let referencePath = UIBezierPath() let referenceLayer = CHShapeLayer() referenceLayer.lineWidth = self.lineWidth //处理辅助线样式 switch section.yAxis.referenceStyle { case let .dash(color: dashColor, pattern: pattern): referenceLayer.strokeColor = dashColor.cgColor referenceLayer.lineDashPattern = pattern showYAxisReference = true case let .solid(color: solidColor): referenceLayer.strokeColor = solidColor.cgColor showYAxisReference = true default: showYAxisReference = false startY = iy - 7 } if showYAxisReference { //突出的线段,y轴向外显示才划突出线段 if !self.isInnerYAxis { referencePath.move(to: CGPoint(x: extrude, y: iy)) referencePath.addLine(to: CGPoint(x: extrude + 2, y: iy)) } referencePath.move(to: CGPoint(x: section.frame.origin.x + section.padding.left, y: iy)) referencePath.addLine(to: CGPoint(x: section.frame.origin.x + section.frame.size.width - section.padding.right, y: iy)) referenceLayer.path = referencePath.cgPath self.drawLayer.addSublayer(referenceLayer) } if showYAxisLabel { //获取调用者回调的label字符串值 let strValue = self.delegate?.kLineChart(chart: self, labelOnYAxisForValue: yVal, atIndex: i, section: section) ?? "" let yLabelRect = CGRect(x: startX, y: startY, width: yAxisLabelWidth, height: 12 ) yAxisToDraw.append((yLabelRect, strValue)) } } return yAxisToDraw } /// 绘制y轴坐标上的标签 /// /// - Parameter yAxisToDraw: fileprivate func drawYAxisLabel(_ yAxisToDraw: [(CGRect, String)]) { var alignmentMode = kCAAlignmentLeft //分区中各个y轴虚线和y轴的label //控制y轴的label在左还是右显示 switch self.showYAxisLabel { case .left: alignmentMode = self.isInnerYAxis ? kCAAlignmentLeft : kCAAlignmentRight case .right: alignmentMode = self.isInnerYAxis ? kCAAlignmentRight : kCAAlignmentLeft case .none: alignmentMode = kCAAlignmentLeft } for (yLabelRect, strValue) in yAxisToDraw { let yAxisLabel = CHTextLayer() yAxisLabel.frame = yLabelRect yAxisLabel.string = strValue yAxisLabel.fontSize = self.labelFont.pointSize yAxisLabel.foregroundColor = self.textColor.cgColor yAxisLabel.backgroundColor = UIColor.clear.cgColor yAxisLabel.alignmentMode = alignmentMode yAxisLabel.contentsScale = UIScreen.main.scale self.drawLayer.addSublayer(yAxisLabel) //NSString(string: strValue).draw(in: yLabelRect, withAttributes: fontAttributes) } } /** 绘制图表上的点线 - parameter section: */ func drawChart(_ section: CHSection) { if section.paging { //如果section以分页显示,则读取当前显示的系列 let serie = section.series[section.selectedIndex] let seriesLayer = self.drawSerie(serie) section.sectionLayer.addSublayer(seriesLayer) } else { //不分页显示,全部系列绘制到图表上 for serie in section.series { let seriesLayer = self.drawSerie(serie) section.sectionLayer.addSublayer(seriesLayer) } } self.drawLayer.addSublayer(section.sectionLayer) } /** 绘制图表分区上的系列点先 */ func drawSerie(_ serie: CHSeries) -> CHShapeLayer { if !serie.hidden { //循环画出每个模型的线 for model in serie.chartModels { let serieLayer = model.drawSerie(self.rangeFrom, endIndex: self.rangeTo) serie.seriesLayer.addSublayer(serieLayer) } } return serie.seriesLayer } } // MARK: - 公开方法 extension CHKLineChartView { /** 刷新视图 */ public func reloadData(toPosition: CHChartViewScrollPosition = .none, resetData: Bool = true) { self.scrollToPosition = toPosition if resetData { self.resetData() } self.drawLayerView() } /// 刷新风格 /// /// - Parameter style: 新风格 public func resetStyle(style: CHKLineChartStyle) { self.style = style self.showSelection = false self.reloadData() } /// 通过key隐藏或显示线系列 /// inSection = -1时,全section都隐藏,否则只隐藏对应的索引的section /// key = "" 时,设置全部线显示或隐藏 public func setSerie(hidden: Bool, by key: String = "", inSection: Int = -1) { var hideSections = [CHSection]() if inSection < 0 { hideSections = self.sections } else { if inSection >= self.sections.count { return //超过界限 } hideSections.append(self.sections[inSection]) } for section in hideSections { for (index, serie) in section.series.enumerated() { if key == "" { if section.paging { section.selectedIndex = 0 } else { serie.hidden = hidden } } else if serie.key == key { if section.paging { if hidden == false { section.selectedIndex = index } } else { serie.hidden = hidden } break } } } // self.drawLayerView() } /** 通过key隐藏或显示分区 */ public func setSection(hidden: Bool, byKey key: String) { for section in self.sections { //副图才能隐藏 if section.key == key && section.valueType == .assistant { section.hidden = hidden break } } // self.drawLayerView() } /** 通过索引位隐藏或显示分区 */ public func setSection(hidden: Bool, byIndex index: Int) { //副图才能隐藏 guard let section = self.sections[safe: index], section.valueType == .assistant else { return } section.hidden = hidden // self.drawLayerView() } /// 缩放图表 /// /// - Parameters: /// - interval: 偏移量 /// - enlarge: 是否放大操作 public func zoomChart(by interval: Int, enlarge: Bool) { var newRangeTo = 0 var newRangeFrom = 0 var newRange = 0 if enlarge { //双指张开 newRangeTo = self.rangeTo - interval newRangeFrom = self.rangeFrom + interval newRange = self.rangeTo - self.rangeFrom if newRange >= kMinRange { if self.plotCount > self.rangeTo - self.rangeFrom { if newRangeFrom < self.rangeTo { self.rangeFrom = newRangeFrom } if newRangeTo > self.rangeFrom { self.rangeTo = newRangeTo } }else{ if newRangeTo > self.rangeFrom { self.rangeTo = newRangeTo } } self.range = self.rangeTo - self.rangeFrom self.drawLayerView() } } else { //双指合拢 newRangeTo = self.rangeTo + interval newRangeFrom = self.rangeFrom - interval newRange = self.rangeTo - self.rangeFrom if newRange <= kMaxRange { if newRangeFrom >= 0 { self.rangeFrom = newRangeFrom } else { self.rangeFrom = 0 newRangeTo = newRangeTo - newRangeFrom //补充负数位到头部 } if newRangeTo <= self.plotCount { self.rangeTo = newRangeTo } else { self.rangeTo = self.plotCount newRangeFrom = newRangeFrom - (newRangeTo - self.plotCount) if newRangeFrom < 0 { self.rangeFrom = 0 } else { self.rangeFrom = newRangeFrom } } self.range = self.rangeTo - self.rangeFrom self.drawLayerView() } } } /// 左右平移图表 /// /// - Parameters: /// - interval: 移动列数 /// - direction: 方向,true:右滑操作,fasle:左滑操作 public func moveChart(by interval: Int, direction: Bool) { if (interval > 0) { //有移动间隔才移动 if direction { //单指向右拖,往后查看数据 if self.plotCount > (self.rangeTo-self.rangeFrom) { if self.rangeFrom - interval >= 0 { self.rangeFrom -= interval self.rangeTo -= interval } else { self.rangeFrom = 0 self.rangeTo -= self.rangeFrom } self.drawLayerView() } } else { //单指向左拖,往前查看数据 if self.plotCount > (self.rangeTo-self.rangeFrom) { if self.rangeTo + interval <= self.plotCount { self.rangeFrom += interval self.rangeTo += interval } else { self.rangeFrom += self.plotCount - self.rangeTo self.rangeTo = self.plotCount } self.drawLayerView() } } } self.range = self.rangeTo - self.rangeFrom } /// 生成截图 open var image: UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) let capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return capturedImage! } /// 手动设置分区头部文本显示内容 /// /// - Parameters: /// - titles: 文本内容及颜色元组 /// - section: 分区位置 open func setHeader(titles: [(title: String, color: UIColor)], inSection section: Int) { guard let section = self.sections[safe: section] else { return } //设置标题 section.setHeader(titles: titles) } /// 向分区添加新线段 /// /// - Parameters: /// - series: 线段 /// - section: 分区位置 open func addSeries(_ series: CHSeries, inSection section: Int) { guard let section = self.sections[safe: section] else { return } section.series.append(series) self.drawLayerView() } /// 通过主键名向分区删除线段 /// /// - Parameters: /// - key: 主键 /// - section: 分区位置 open func removeSeries(key: String, inSection section: Int) { guard let section = self.sections[safe: section] else { return } section.removeSeries(key: key) self.drawLayerView() } } // MARK: - 手势操作 extension CHKLineChartView: UIGestureRecognizerDelegate { /// 控制手势开关 /// public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { switch gestureRecognizer { case is UITapGestureRecognizer: return self.enableTap case is UIPanGestureRecognizer: return self.enablePan case is UIPinchGestureRecognizer: return self.enablePinch default: return false } } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer.view is UITableView{ return true } return false } /// 平移拖动操作 /// /// - Parameter sender: 手势 @objc func doPanAction(_ sender: UIPanGestureRecognizer) { guard self.enablePan else { return } self.showSelection = false //手指滑动总平移量 let translation = sender.translation(in: self) //滑动力度,用于释放手指时完成惯性滚动的效果 let velocity = sender.velocity(in: self) //获取可见的其中一个分区 let visiableSection = self.sections.filter { !$0.hidden } guard let section = visiableSection.first else { return } //该分区每个点的间隔宽度 let plotWidth = (section.frame.size.width - section.padding.left - section.padding.right) / CGFloat(self.rangeTo - self.rangeFrom) switch sender.state { case .began: self.animator.removeAllBehaviors() case .changed: //计算移动距离的绝对值,距离满足超过线条宽度就进行图表平移刷新 let distance = fabs(translation.x) // print("translation.x = \(translation.x)") // print("distance = \(distance)") if distance > plotWidth { let isRight = translation.x > 0 ? true : false let interval = lroundf(fabs(Float(distance / plotWidth))) self.moveChart(by: interval, direction: isRight) //重新计算起始位 sender.setTranslation(CGPoint(x: 0, y: 0), in: self) } case .ended, .cancelled: //重置减速开始 self.decelerationStartX = 0 //添加减速行为 self.dynamicItem.center = self.bounds.origin let decelerationBehavior = UIDynamicItemBehavior(items: [self.dynamicItem]) decelerationBehavior.addLinearVelocity(velocity, for: self.dynamicItem) decelerationBehavior.resistance = 2.0 decelerationBehavior.action = { [weak self]() -> Void in //print("self.dynamicItem.x = \(self?.dynamicItem.center.x ?? 0)") //到边界不执行移动 if self?.rangeFrom == 0 || self?.rangeTo == self?.plotCount{ return } let itemX = self?.dynamicItem.center.x ?? 0 let startX = self?.decelerationStartX ?? 0 //计算移动距离的绝对值,距离满足超过线条宽度就进行图表平移刷新 let distance = fabs(itemX - startX) // print("distance = \(distance)") if distance > plotWidth { let isRight = itemX > 0 ? true : false let interval = lroundf(fabs(Float(distance / plotWidth))) self?.moveChart(by: interval, direction: isRight) //重新计算起始位 self?.decelerationStartX = itemX } } //添加动力行为 self.animator.addBehavior(decelerationBehavior) self.decelerationBehavior = decelerationBehavior default: break } } /** * 点击事件处理 * * @param sender */ @objc func doTapAction(_ sender: UITapGestureRecognizer) { guard self.enableTap else { return } let point = sender.location(in: self) let (_, section) = self.getSectionByTouchPoint(point) if section != nil { if section!.paging { //显示下一页 section!.nextPage() self.drawLayerView() self.delegate?.kLineChart?(chart: self, didFlipPageSeries: section!, series: section!.series[section!.selectedIndex], seriesIndex: section!.selectedIndex) } else { //显示点击选中的内容 self.setSelectedIndexByPoint(point) } } } /// 双指手势缩放图表 /// /// - Parameter sender: 手势 @objc func doPinchAction(_ sender: UIPinchGestureRecognizer) { guard self.enablePinch else { return } //获取可见的其中一个分区 let visiableSection = self.sections.filter { !$0.hidden } guard let section = visiableSection.first else { return } //该分区每个点的间隔宽度 let plotWidth = (section.frame.size.width - section.padding.left - section.padding.right) / CGFloat(self.rangeTo - self.rangeFrom) //双指合拢或张开 let scale = sender.scale var newRange = 0 //根据放大比例计算一个新的列宽 let newPlotWidth = plotWidth * scale let newRangeF = (section.frame.size.width - section.padding.left - section.padding.right) / newPlotWidth newRange = scale > 1 ? Int(newRangeF + 1) : Int(newRangeF) let distance = abs(self.range - newRange) //放大缩小的距离为偶数 if distance % 2 == 0 && distance > 0 { // print("scale = \(scale)") let enlarge = scale > 1 ? true : false self.zoomChart(by: distance / 2, enlarge: enlarge) sender.scale = 1 //恢复比例 } } /// 处理长按操作 /// /// - Parameter sender: @objc func doLongPressAction(_ sender: UILongPressGestureRecognizer) { let point = sender.location(in: self) let (_, section) = self.getSectionByTouchPoint(point) if section != nil { if !section!.paging { //显示点击选中的内容 self.setSelectedIndexByPoint(point) } // self.drawLayerView() } } }
mit
f239a8e77ba8b4fb0fc5794a9d88c07c
32.15831
251
0.526064
4.653752
false
false
false
false
JuanjoArreola/YouTubePlayer
YouTubePlayer/YouTubeVideo.swift
1
4558
// // YouTubeVideo.swift // YouTubePlayer // // Created by Juan Jose Arreola Simon on 4/16/16. // Copyright © 2016 juanjo. All rights reserved. // import Foundation public enum VideoQuality { case liveStreaming case small_240 case medium_360 case hd_720 func value() -> AnyObject { switch self { case .liveStreaming: return "HTTPLiveStreaming" as AnyObject case .small_240: return 36 as AnyObject case .medium_360: return 18 as AnyObject case .hd_720: return 22 as AnyObject } } static func qualityFromString(_ string: String) -> VideoQuality? { switch string { case "36": return .small_240 case "18": return .medium_360 case "22": return .hd_720 case "HTTPLiveStreaming": return .liveStreaming default: return nil } } } open class YouTubeVideo { let identifier: String var title: String? open let streamURLs: [VideoQuality: URL] var duration: Int = 0 var thumbnailSmall: URL? var thumbnailMedium: URL? var thumbnailLarge: URL? var expirationDate: Date? init(identifier: String, info: [String: String], playerScript: PlayerScript?) throws { self.identifier = identifier let streamMap = info["url_encoded_fmt_stream_map"] let httpLiveStream = info["hlsvp"] let adaptiveFormats = info["adaptive_fmts"] if (streamMap?.isEmpty ?? true) && (httpLiveStream?.isEmpty ?? true) { throw YouTubeError.noStreamAvailable(reason: info["reason"]) } var streamQueries = streamMap?.components(separatedBy: ",") ?? [String]() if let formats = adaptiveFormats { streamQueries += formats.components(separatedBy: ",") } var streamURLs = [VideoQuality: URL]() if let liveStream = httpLiveStream, let url = URL(string: liveStream) { streamURLs[.liveStreaming] = url } for streamQuery in streamQueries { let stream = dictionary(fromResponse: streamQuery) var signature: String? if let scrambledSignature = stream["s"] { if playerScript == nil { throw YouTubeError.signatureError } signature = playerScript?.unscrambleSignature(scrambledSignature) if signature == nil { continue } } if let urlString = stream["url"], let itag = stream["itag"], let url = URL(string: urlString) { if expirationDate == nil { expirationDate = expiration(from: url) } guard let quality = VideoQuality.qualityFromString(itag) else { continue } if let signature = signature { let escapedSignature = signature.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) var components = URLComponents(url: url, resolvingAgainstBaseURL: false) components?.queryItems?.append(URLQueryItem(name: "signature", value: escapedSignature)) if let url = components?.url { streamURLs[quality] = url } } else { streamURLs[quality] = url } } } if streamURLs.isEmpty { throw YouTubeError.noStreamAvailable(reason: nil) } self.streamURLs = streamURLs title = info["title"] if let duration = info["length_seconds"] { self.duration = Int(duration) ?? 0 } if let thumbnail = info["thumbnail_url"] ?? info["iurl"] { thumbnailSmall = URL(string: thumbnail) } if let thumbnail = info["iurlsd"] ?? info["iurlhq"] ?? info["iurlmq"] { thumbnailMedium = URL(string: thumbnail) } if let thumbnail = info["iurlmaxres"] { thumbnailLarge = URL(string: thumbnail) } } } func expiration(from url: URL) -> Date? { let components = URLComponents(url: url, resolvingAgainstBaseURL: false) for query in components?.queryItems ?? [] { if query.name == "expire" { if let stringTime = query.value, let time = Double(stringTime) { return Date(timeIntervalSince1970: time) } break } } return nil }
mit
cd705ddb027fefff52fea4fe53be531c
33.78626
127
0.56287
4.801897
false
false
false
false
mattrajca/swift-corelibs-foundation
DarwinCompatibilityTests/DarwinShims.swift
4
2275
// 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // These shims are used solely by the DarwinCompatibilityTests Xcode project to // allow the TestFoundation tests to compile and run against Darwin's native // Foundation. // It contains wrappers for methods (some experimental) added in // swift-corelibs-foundation which do not exist in Foundation, and other small // differences. import Foundation public typealias unichar = UInt16 extension unichar : ExpressibleByUnicodeScalarLiteral { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } extension NSURL { func checkResourceIsReachable() throws -> Bool { var error: NSError? if checkResourceIsReachableAndReturnError(&error) { return true } else { if let e = error { throw e } } return false } } extension Thread { class var mainThread: Thread { return Thread.main } } extension Scanner { public func scanString(_ searchString: String) -> String? { var result: NSString? = nil if scanString(string, into: &result), let str = result { return str as String } return nil } } extension JSONSerialization { class func writeJSONObject(_ obj: Any, toStream stream: OutputStream, options opt: WritingOptions) throws -> Int { var error: NSError? let ret = writeJSONObject(obj, to: stream, options: opt, error: &error) guard ret != 0 else { throw error! } return ret } } extension NSIndexSet { func _bridgeToSwift() -> NSIndexSet { return self } } extension CharacterSet { func _bridgeToSwift() -> CharacterSet { return self } } extension NSCharacterSet { func _bridgeToSwift() -> CharacterSet { return self as CharacterSet } }
apache-2.0
cf0acd5c3e006fb912a52f675c21f6ed
25.149425
118
0.65978
4.769392
false
false
false
false
JohnnyHao/ForeignChat
ForeignChat/TabVCs/UserCenter/RegisterViewController.swift
1
3053
// // RegisterViewController.swift // ForeignChat // // Created by Tonny Hao on 2/21/15. // Copyright (c) 2015 Tonny Hao. All rights reserved. // import UIKit class RegisterViewController: UITableViewController { @IBOutlet var nameField: UITextField! @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboard")) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.nameField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { self.view.endEditing(true) } @IBAction func registerButtonPressed(sender: UIButton) { let name = nameField.text let email = emailField.text let password = passwordField.text.lowercaseString if countElements(name) == 0 { ProgressHUD.showError("Name must be set.") return } if countElements(password) == 0 { ProgressHUD.showError("Password must be set.") return } if countElements(email) == 0 { ProgressHUD.showError("Email must be set.") return } ProgressHUD.show("Please wait...", interaction: false) // var user = PFUser() // user.username = name // // user.password = password // user.email = email // user[PF_USER_EMAILCOPY] = email // user[PF_USER_FULLNAME] = name // user[PF_USER_FULLNAME_LOWER] = name.lowercaseString // user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in // if error == nil { // PushNotication.parsePushUserAssign() // ProgressHUD.showSuccess("Succeeded.") // self.dismissViewControllerAnimated(true, completion: nil) // } else { // if let userInfo = error.userInfo { // ProgressHUD.showError(userInfo["error"] as String) // } // } // } var user = FCUser() user.username = name.lowercaseString user.fullName = name user.password = password user.email = email user.gender = NSNumber(char: 1) user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in if error == nil { PushNotication.parsePushUserAssign() ProgressHUD.showSuccess("Succeeded.") self.dismissViewControllerAnimated(true, completion: nil) } else { if let userInfo = error.userInfo { ProgressHUD.showError(userInfo["error"] as String) } } } } }
apache-2.0
64d9a972cdcb496b77bd01d4eb9baa7c
30.802083
103
0.576155
4.972313
false
false
false
false
seraphjiang/JHUIKit
JHUIKit/Classes/JHBannerMessage.swift
1
2279
// // JHBannerMessage.swift // Pods // // Created by Huan Jiang on 5/7/16. // // import UIKit /// A banner message public class JHBannerMessage: NSObject { /** show message box in current active viewcontroller - parameter message: message to be shown */ public static func show(message: String) -> Void { if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } let alertView = UIView(frame: CGRectMake(0, -80, RuntimeConstants().ScreenWidth, 80)) alertView.backgroundColor = UIColor.darkGrayColor() //Create a label to display the message and add it to the alertView let width = alertView.bounds.width let theMessage = UILabel(frame: CGRectMake(20, 0, width - 40, CGRectGetHeight(alertView.bounds))); theMessage.numberOfLines = 0 theMessage.lineBreakMode = .ByWordWrapping; theMessage.text = message theMessage.textColor = UIColor.whiteColor() alertView.addSubview(theMessage) topController.view.addSubview(alertView) //Create the ending frame or where you want it to end up on screen, in this case 0 y origin var newFrm = alertView.frame; newFrm.origin.y = 0; //Animate it in UIView.animateWithDuration( 1, delay:0, options:[], animations: { alertView.frame.origin.y = 0 }, completion: { (finished: Bool) in UIView.animateWithDuration( 0.5, delay:2, options:[], animations: { alertView.frame.origin.y = -80 }, completion: { (f:Bool) in alertView.removeFromSuperview() }) }) } } }
mit
04aabfb80cd4cdbc40589c43004f903d
33.545455
110
0.515577
5.755051
false
false
false
false
ucotta/BrilliantTemplate
Sources/BrilliantTemplate/FileHelper.swift
1
1432
// // Created by Ubaldo Cotta on 12/11/16. // import Foundation #if os(Linux) // realpath is not working in linux func loadfile(file:String, in path:String) -> String { func containsTraversalCharacters(data:String) -> Bool { let dangerCharacters = ["%2e", "%2f", "%5c", "%25", "%c0%af", "%c1%9c", ":", ">", "<", "./", ".\\", "..", "\\\\", "//", "/.", "\\.", "|"] return (dangerCharacters.filter { data.contains($0) }.flatMap { $0 }).count > 0 } var result = "cannot open file \(file)" let tmp = path + "/" + file do { if !containsTraversalCharacters(data:tmp) { result = try String(contentsOfFile: tmp, encoding: String.Encoding.utf8) } } catch { } return result } #else func loadfile(file:String, in path:String) -> String { func rp(path: String) -> String? { let p = realpath(path, nil) if p == nil { return nil } defer { free(p) } return String(validatingUTF8: p!) } let tmp = path + "/" + file var result = "cannot open file \(file)" do { if let file = rp(path: tmp) { if file.hasPrefix(path) { result = try String(contentsOfFile: file, encoding: String.Encoding.utf8) } else { print("Trying to acces file: \(file) outside path \(path)") } } } catch {} return result } #endif
apache-2.0
38059160d33dc86d3bc053e7b3092a1c
24.122807
145
0.52514
3.719481
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Tool/Sources/ToolKit/General/Extensions/Locale+Conveniences.swift
1
527
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation extension Locale { public static let US = Locale(identifier: "en_US") public static let Canada = Locale(identifier: "en_CA") public static let GreatBritain = Locale(identifier: "en_GB") public static let France = Locale(identifier: "fr_FR") public static let Japan = Locale(identifier: "ja_JP") public static let Lithuania = Locale(identifier: "lt_LT") public static let Posix = Locale(identifier: "en_US_POSIX") }
lgpl-3.0
b53938d945f5a6057d6da2be10997226
39.461538
64
0.711027
3.811594
false
false
false
false
ashfurrow/eidolon
Kiosk/Bid Fulfillment/PlaceBidNetworkModel.swift
2
2111
import Foundation import RxSwift import Moya import SwiftyJSON let OutbidDomain = "Outbid" protocol PlaceBidNetworkModelType { var bidDetails: BidDetails { get } func bid(_ provider: AuthorizedNetworking) -> Observable<String> } class PlaceBidNetworkModel: NSObject, PlaceBidNetworkModelType { let bidDetails: BidDetails init(bidDetails: BidDetails) { self.bidDetails = bidDetails super.init() } func bid(_ provider: AuthorizedNetworking) -> Observable<String> { let saleArtwork = bidDetails.saleArtwork.value assert(saleArtwork.hasValue, "Sale artwork cannot nil at bidding stage.") let cents = (bidDetails.bidAmountCents.value?.currencyValue) ?? 0 return bidOnSaleArtwork(saleArtwork!, bidAmountCents: String(cents), provider: provider) } fileprivate func bidOnSaleArtwork(_ saleArtwork: SaleArtwork, bidAmountCents: String, provider: AuthorizedNetworking) -> Observable<String> { let bidEndpoint = ArtsyAuthenticatedAPI.placeABid(auctionID: saleArtwork.auctionID!, artworkID: saleArtwork.artwork.id, maxBidCents: bidAmountCents) let request = provider .request(bidEndpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapTo(object: BidderPosition.self) return request .map { position in return position.id }.catchError { e -> Observable<String> in // We've received an error. We're going to check to see if it's type is "param_error", which indicates we were outbid. guard let error = e as? MoyaError else { throw e } guard case .statusCode(let response) = error else { throw e } let json = try JSON(data: response.data) if let type = json["type"].string , type == "param_error" { throw NSError(domain: OutbidDomain, code: 0, userInfo: [NSUnderlyingErrorKey: error as NSError]) } else { throw error } } .logError() } }
mit
70b58a766954f75a10a159ac9e0b9e80
32.507937
156
0.636665
4.967059
false
false
false
false
361425281/swift-snia
Swift-Sina/Classs/Main/Controller/DQTabBarController.swift
2
2572
// // DQTabBarController.swift // Swift - sina // // Created by 熊德庆 on 15/10/26. // Copyright © 2015年 熊德庆. All rights reserved. // import UIKit class DQTabBarController: UITabBarController { override func viewDidLoad() { // let newTabBar = DQTabBar() // newTabBar.composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside) // // setValue(newTabBar, forKey: "tabBar") super.viewDidLoad() tabBar.tintColor = UIColor.orangeColor() let HomeVC = DQHomeTabBarController() self.addChildViewController(HomeVC, title: "首页", imagename: "tabbar_home") let MessageVC = DQMessageTableViewController() self.addChildViewController(MessageVC, title: "信息", imagename: "tabbar_message_center") let add = UIViewController() self.addChildViewController(add, title: "", imagename: "f") let DiscoveVC = DQDiscoverTabBarController() self.addChildViewController(DiscoveVC, title: "发现", imagename: "tabbar_discover") let MeVC = DQMeTableViewController() MeVC.title = "我" self.addChildViewController(MeVC, title: "我", imagename: "tabbar_profile") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let width = tabBar.bounds.width / CGFloat(5) composeButton.frame = CGRectMake(width*2, 0, width, tabBar.bounds.height) tabBar.addSubview(composeButton) } private func addChildViewController(Controller:UIViewController,title:String,imagename:String) { Controller.title = title Controller.tabBarItem.image = UIImage(named: imagename) addChildViewController(UINavigationController(rootViewController: Controller)) } //懒加载 lazy var composeButton:UIButton = { let btn=UIButton() btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) btn.addTarget(self, action: "composeButton", forControlEvents: UIControlEvents.TouchUpInside) return btn }() }
apache-2.0
0e1221b9c1eb60414f79e5767a5892e0
38.609375
128
0.671006
4.617486
false
false
false
false
tensorflow/examples
lite/examples/bert_qa/ios/BertQACore/Constants.swift
1
2510
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit enum InterpreterOptions { // Default thread count is 2, unless maximum thread count is 1. static let threadCount = ( defaultValue: 2, minimumValue: 1, maximumValue: Int(ProcessInfo.processInfo.activeProcessorCount), id: "threadCount" ) } enum MobileBERT { static let maxAnsLen = 32 static let maxQueryLen = 64 static let maxSeqLen = 384 static let predictAnsNum = 5 static let outputOffset = 1 // Need to shift 1 for outputs ([CLS]) static let doLowerCase = true static let inputDimension = [1, MobileBERT.maxSeqLen] static let outputDimension = [1, MobileBERT.maxSeqLen] static let dataset = File(name: "contents_from_squad_dict_format", ext: "json") static let vocabulary = File(name: "vocab", ext: "txt") static let model = File(name: "mobilebert_float_20191023", ext: "tflite") } struct File { let name: String let ext: String let description: String init(name: String, ext: String) { self.name = name self.ext = ext self.description = "\(name).\(ext)" } } enum CustomUI { static let textHighlightColor = UIColor(red: 1.0, green: 0.7, blue: 0.0, alpha: 0.3) static let runButtonOpacity = 0.8 static let statusTextViewCornerRadius = CGFloat(7) static let suggestedQuestionCornerRadius = CGFloat(10) static let keyboardAnimationDuration = 0.23 static let stackSpacing = CGFloat(5) static let padding = CGFloat(5) static let contentViewPadding = CGFloat(7) static let controlViewPadding = CGFloat(10) static let textSidePadding = CGFloat(4) static let textPadding = CGFloat(3) static let statusFontSize = CGFloat(14) } enum StatusMessage { static let askRun = "Tap ▶︎ button to get the answer." static let warnEmptyQuery = "⚠️Got empty question.\nPlease enter non-empty question." static let inferenceFailError = "❗️Failed to inference the answer." }
apache-2.0
3818b6cabaa3cbe37c4ebffa54bbeeee
29.839506
87
0.724179
3.872868
false
false
false
false
coach-plus/ios
CoachPlus/helperclasses/MembershipManager.swift
1
5994
// // TeamManager.swift // CoachPlus // // Created by Breit, Maurice on 31.03.17. // Copyright © 2017 Mathandoro GbR. All rights reserved. // import Foundation import SwiftyUserDefaults import SwiftyJSON import RxSwift import PromiseKit class MembershipManager { enum MembershipError: Error { case notFound } static let shared = MembershipManager() var selectedMembership:Membership? var selectedMembershipSubject: BehaviorSubject<Membership?> var memberships:[Membership] = [] var membershipsSubject: BehaviorSubject<[Membership]> init() { self.membershipsSubject = BehaviorSubject<[Membership]>(value: []) self.selectedMembershipSubject = BehaviorSubject<Membership?>(value: nil) self.setMemberships(memberships: self.getStoredMemberships()) self.setSelectedMembership(membership: self.getPreviouslySelectedMembership()) } func setMemberships(memberships: [Membership]) { self.memberships = memberships self.storeMemberships(memberships: memberships) self.membershipsSubject.onNext(self.memberships) if (self.selectedMembership != nil) { let membershipIndex = self.memberships.firstIndex(where: { membership in return membership.id == self.selectedMembership!.id }) if let i = membershipIndex, i >= 0, i <= self.memberships.count { self.setSelectedMembership(membership: self.memberships[i]) } } } func setSelectedMembership(membership: Membership?) { self.selectedMembership = membership self.storeSelectedMembership(membership: membership) self.selectedMembershipSubject.onNext(self.selectedMembership) } func getRandomMembership() -> Promise<Membership?> { return Promise<Membership?> { p in self.loadMemberships().done({ memberships in self.storeMemberships(memberships: memberships) if (memberships.count > 0) { p.fulfill(self.memberships[0]) return } else { p.fulfill(nil) return } }).catch({ err in p.fulfill(nil) return }) } } func getMembershipForTeam(teamId: String) -> Promise<Membership?> { return Promise<Membership?> { p in let localMembership = self.getMembershipFromLocalMemberships(teamId: teamId) if (localMembership != nil) { p.fulfill(localMembership!) return } else { self.loadMemberships().done({ memberships in let membership = self.getMembershipFromLocalMemberships(teamId: teamId) if (membership != nil) { p.fulfill(membership!) return } else { p.reject(MembershipError.notFound) return } }).catch({ err in p.reject(MembershipError.notFound) return }) } } } func loadMemberships() -> Promise<[Membership]> { return Promise<[Membership]> { p in DataHandler.def.getMyMemberships().done({ memberships in self.setMemberships(memberships: memberships) p.fulfill(memberships) }).catch({ err in p.reject(err) }) } } public func getMembershipFromLocalMemberships(teamId: String) -> Membership? { let membershipIndex = self.memberships.firstIndex(where: { membership in return membership.team?.id == teamId }) if (membershipIndex != nil && membershipIndex! >= 0 && membershipIndex! < memberships.count) { return memberships[membershipIndex!] } return nil } func storeSelectedMembership(membership:Membership?) { if let m = membership { Defaults[\.selectedMembershipId] = m.id } else { Defaults[\.selectedMembershipId] = "" } } func getPreviouslySelectedMembership() -> Membership? { let membershipId = Defaults[\.selectedMembershipId] guard membershipId != "" else { return nil } let memberships = self.memberships if (memberships.count == 0) { return nil } if (memberships.count == 1) { selectedMembership = memberships[0] selectedMembership?.user = Authentication.getUser() return memberships[0] } let matchingMemberships = memberships.filter({ membership in return (membership.id == membershipId) }) if (matchingMemberships.count > 0) { selectedMembership = matchingMemberships[0] selectedMembership?.user = Authentication.getUser() return matchingMemberships[0] } selectedMembership = nil return nil } func storeMemberships(memberships: [Membership]) { self.memberships = memberships Defaults[\.membershipJSON] = memberships.toString() } private func getStoredMemberships() -> [Membership] { self.memberships = Defaults[\.membershipJSON].toArray(Membership.self) return self.memberships } func clearMemberships() { Defaults[\.membershipJSON] = "" Defaults[\.selectedMembershipId] = "" } } extension DefaultsKeys { var membershipJSON: DefaultsKey<String> { .init("teams", defaultValue: "") } var selectedMembershipId: DefaultsKey<String> { .init("selectedMembershipId", defaultValue: "") } }
mit
925e8671184a94c0de64db928dcd3ff5
31.394595
102
0.574003
5.473059
false
false
false
false
boland25/swift-hn
HackerNewsRSSFeeder/Features/RSSFeed/Posts/RSSPostVC.swift
1
2619
// // RSSPostVC.swift // HackerNewsRSSFeeder // // Created by boland on 8/9/14. // Copyright (c) 2014 Prolific Interactive. All rights reserved. // import UIKit class RSSPostVC: UIViewController { var detailItem: RSSItem = RSSItem() { didSet { // TODO: add anything in here that would need to happen when data is set. NOTE: can't load anything view related because the view does not yet exist, ask me how i realized that one? } } @IBOutlet weak var linkURL: UILabel!; @IBOutlet weak var commentView: UIWebView!; override func viewDidLoad() { super.viewDidLoad() self.configureView() } func configureView() { self.layoutDetails() } func layoutDetails() { self.title = self.detailItem.title println("\(self.linkURL) detail item \(self.detailItem)") self.linkURL.text = self.detailItem.link self.setCommentsWithLink(self.detailItem.comments!) } func setCommentsWithLink(linkURL:String)->Void { Data.shared().getComments(linkURL, success: { (htmlString) -> Void in //HTML turned into string self.loadHTML(htmlString) }, failure: {(error:Error )->Void in self.showError(error) }) } func loadHTML(htmlString:String)->Void { self.commentView.loadHTMLString(htmlString, baseURL: nil); } func resizeHTMLViewToFit()->Void { var contentSize = self.commentView.scrollView.contentSize; var viewSize = self.view.bounds.size; var rw = viewSize.width / viewSize.height self.commentView.scrollView.minimumZoomScale = rw self.commentView.scrollView.maximumZoomScale = rw*4 self.commentView.scrollView.zoomScale = rw; } // MARK: - UIWebViewDelegate func webViewDidFinishLoad(webView:UIWebView)->Void { //TODO: css style could be applied here in a future release //NOTE: wasn't sure how to deal with the comments section as it doesn't fit without re-sizing it, this is a temp solution self.resizeHTMLViewToFit(); // self.hideActivityIndicator(); } // MARK: - Error Handling //TODO: consolidate the error methods into an extension or base class func showError(error : Error!) { var alertView = UIAlertView() alertView.title = "Error" alertView.message = "\(error.message). There was a problem connecting with Hacker News. Please try again." alertView.addButtonWithTitle("Okay") alertView.show() } }
mit
4af5e24aa1f8d3709c0f8d2e3dba6157
30.554217
194
0.636884
4.627208
false
false
false
false
vanyaland/Tagger
Tagger/Sources/PresentationLayer/ViewControllers/Discover/CountPicker/CountPickerViewController.swift
1
6022
/** * Copyright (c) 2016 Ivan Magda * * 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 // MARK: Typealiases typealias CountPickerDoneBlock = (_ selectedIndex: Int, _ selectedValue: Int) -> Swift.Void typealias CountPickerCancelBlock = () -> Swift.Void // MARK: - CountPickerViewController: UIViewController @IBDesignable final class CountPickerViewController: UIViewController { // MARK: IBOutlets @IBOutlet var containerView: UIView! @IBOutlet var titleLabel: UILabel! @IBOutlet var pickerView: UIPickerView! @IBOutlet var selectButton: UIButton! @IBOutlet var cancelButton: UIButton! // MARK: Instance Variables var initialSelection = 0 var numberOfRows = 20 private var selectedRowIdx = 0 private var selectedValue: Int { get { return selectedRowIdx + 1 } } private var doneBlock: CountPickerDoneBlock? private var cancelBlock: CountPickerCancelBlock? private static let nibName = "CountPickerViewController" // MARK: - UIViewController lifecycle override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: - Init convenience init() { self.init(nibName: CountPickerViewController.nibName, bundle: nil) } } // MARK: - CountPickerViewController (Actions) - extension CountPickerViewController { @objc private func cancelButtonDidPressed(_ button: UIButton) { dismissFromParentViewController() cancelBlock?() } @objc private func selectButtonDidPressed(_ button: UIButton) { dismissFromParentViewController() doneBlock?(selectedRowIdx, selectedValue) } } // MARK: - CountPickerViewController (Private Helpers) - extension CountPickerViewController { private func setup() { containerView.layer.masksToBounds = true containerView.layer.cornerRadius = 8.0 cancelButton.addTarget(self, action: #selector(cancelButtonDidPressed(_:)), for: .touchUpInside) selectButton.addTarget(self, action: #selector(selectButtonDidPressed(_:)), for: .touchUpInside) pickerView.dataSource = self pickerView.delegate = self pickerView.selectRow(initialSelection, inComponent: 0, animated: false) } } // MARK: - CountPickerViewController (Embed) - extension CountPickerViewController { @discardableResult class func showPicker(title: String, rows: Int, initialSelection: Int, doneHandler: @escaping CountPickerDoneBlock, cancelHandler: CountPickerCancelBlock?) -> Bool { guard let rootViewController = UIUtils.rootViewController() else { return false } let picker = CountPickerViewController() picker.numberOfRows = rows picker.initialSelection = initialSelection picker.doneBlock = doneHandler picker.cancelBlock = cancelHandler picker.presentInParentViewController(rootViewController) picker.titleLabel.text = title return true } func dismissFromParentViewController() { willMove(toParent: nil) UIView.animate(withDuration: 0.3, animations: { self.containerView.frame.origin.y += self.view.bounds.height self.view.alpha = 0.0 }, completion: { finished in guard finished == true else { return } self.view.removeFromSuperview() self.removeFromParent() }) } func presentInParentViewController(_ parentViewController: UIViewController) { view.frame = parentViewController.view.bounds parentViewController.addChild(self) parentViewController.view.addSubview(view) view.alpha = 0.0 containerView.frame.origin.y += containerView.bounds.height UIView.animate(withDuration: 0.3, animations: { self.view.alpha = 1.0 self.containerView.frame.origin.y = 0 }, completion: nil) } } // MARK: - CountPickerViewController: UIPickerViewDataSource - extension CountPickerViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return numberOfRows } } // MARK: - CountPickerViewController: UIPickerViewDelegate - extension CountPickerViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return "\(row + 1)" } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedRowIdx = row } }
mit
e5b0e39e049506341b2efb25c3a0f0c6
31.203209
111
0.668549
5.333924
false
false
false
false
RetroRebirth/Micronaut
platformer/platformer/Player.swift
1
11398
// // Player.swift // Micronaut // // Created by Christopher Williams on 2/16/16. // Copyright © 2016 Christopher Williams. All rights reserved. // // Handles the game logic in association with the player. import Foundation import SpriteKit class Player: AnimatedSprite { static private let shrinkScale:CGFloat = 0.5 static var stunCounter:CGFloat = 0.0 static var velocityX:CGFloat = 0.0 static var velocityY:CGFloat = 0.0 static var jumpCounter:CGFloat = 0.0 static var dying:Bool = false override class func initialize(node: SKNode) { super.initialize(node) // Allow player to run node.physicsBody?.friction = 0.0 node.physicsBody?.restitution = 0.0 node.physicsBody?.affectedByGravity = !Controller.debug animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) } override class func loadSprites() { super.loadSprites() // Resting loadSprite(Constants.Sprite_PlayerResting, frames: 8) // Walking loadSprite(Constants.Sprite_PlayerWalking, frames: 8) // Jumping loadSprite(Constants.Sprite_PlayerJumping, frames: 8) // Death loadSprite("spacemanDead", frames: 1) } class func update() { // Keep the player running (unless they hit something) if abs(Player.velocityX) > 0.0 { node!.physicsBody?.velocity.dx = Player.velocityX } if abs(Player.velocityY) > 0.0 { node!.physicsBody?.velocity.dy = Player.velocityY } // If the player fell, reset the world if node!.position.y < 0.0 { Player.die() } // If the player is stunned, decrement the stun counter if Player.stunCounter > 0.0 { Player.stunCounter -= Utility.dt // Stun timer is done, change player sprite back to normal if Player.stunCounter <= 0.0 { animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) } // Keep player still // Player.clearVelocity() } // Check to see if the player is recently contacting the ground if Player.jumpCounter > 0.0 { Player.jumpCounter -= Utility.dt } // var groundContactCount = 0 for body in node!.physicsBody!.allContactedBodies() { if (body.categoryBitMask & Constants.CollisionCategory_Ground != 0) { // Reset the jump counter if the player has recently touched the ground Player.jumpCounter = 0.5 // If the player isn't shrinking or growing then we don't care what happens now if !Player.isShrinkingOrGrowing() { break } // Measure the ground's position in relation to the player // http://stackoverflow.com/questions/21853175/finding-absolute-position-of-child-sknode let absoluteY = body.node!.position.y + body.node!.parent!.position.y if absoluteY > node!.position.y { // If the player is squished between a floor and ceiling, force shrink Player.setShrink(true) break // // If the player is touching two grounds at the same time while growing, have them shrink // groundContactCount += 1 // // TODO why does allContactedBodies return duplicates? // if groundContactCount == 3 { // Player.setShrink(true) // break // } } } } } class func didFinishUpdate() { } class func jump() { if Player.isStunned() { // Do nothing, the player is stunned return } // Only jump when the player is standing on the ground // if let dy = node!.physicsBody?.velocity.dy { if Player.onGround() { // Nullify the jump counter (until we touch ground again) Player.jumpCounter = 0.0 // Change player sprite image to jumping animateOnce(Constants.Sprite_PlayerJumping, timePerFrame: 0.1) // Play jumping sound effect Sound.play("jump.wav", loop: false) // Enact an impulse on the player if isBig() { node!.physicsBody?.applyImpulse(CGVectorMake(0, Constants.PlayerJumpForceBig)) } else { node!.physicsBody?.applyImpulse(CGVectorMake(0, Constants.PlayerJumpForceSmall)) } } } class func setVelocityX(velocityX: CGFloat, force: Bool) { if Player.isStunned() && !force { // Do nothing, the player is stunned return } Player.velocityX = velocityX node!.physicsBody?.velocity.dx = velocityX // Change player sprite animation if velocityX == 0.0 { animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) } else { // Flip image depending on which way the player is moving if (velocityX > 0.0 && node!.xScale < 0.0) || (velocityX < 0.0 && node!.xScale > 0.0) { node!.xScale = -1.0 * node!.xScale } animateContinuously(Constants.Sprite_PlayerWalking, timePerFrame: 0.05) } } class func setVelocityY(velocityY: CGFloat, force: Bool) { if Player.isStunned() && !force { // Do nothing, the player is stunned return } Player.velocityY = velocityY node!.physicsBody?.velocity.dy = velocityY } class func clearVelocity() { Player.velocityX = 0.0 Player.velocityY = 0.0 animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) node!.physicsBody?.velocity.dx = 0.0 node!.physicsBody?.velocity.dy = 0.0 } class func isStunned() -> Bool { return Player.stunCounter > 0.0 } class func reset() { Player.setPos(Constants.LevelSpawnPoints[World.Level]) animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) node!.xScale = 1.0 node!.yScale = 1.0 node!.alpha = 1.0 node!.physicsBody?.affectedByGravity = !Controller.debug node!.physicsBody?.pinned = false node!.physicsBody?.dynamic = true } class func setPos(pos: CGPoint) { // Place the player back at start with no velocity node!.position = pos node!.physicsBody?.velocity = CGVectorMake(0.0, 0.0) // Change player sprite to default animateContinuously(Constants.Sprite_PlayerResting, timePerFrame: 0.1) } class func getPos() -> CGPoint { return node!.position } class func hurtBy(enemyBody: SKPhysicsBody) { if Player.isStunned() { // Do nothing, the player is stunned return } // Option 1: Player dies and goes back to start Player.die() // Option 2: Knock the player back, no death // Player.setVelocityX(0.0, force: true) // // let playerBody = node!.physicsBody! // // // TODO Change player sprite to hurt // animateOnce(Constants.Sprite_PlayerJumping, timePerFrame: 0.1) // // Play hurt sound effect // Sound.play("hurt.wav", loop: false) // // // Knock-back player // let hurtImpulse = Constants.PlayerHurtForce * Utility.normal(Utility.CGPointToCGVector((playerBody.node?.position)! - (enemyBody.node?.position)!)) // playerBody.applyImpulse(hurtImpulse) // // Apply hit stun // Player.stunCounter = Constants.PlayerHurtStunTime } class func setShrink(shouldShrink:Bool) { if Player.isStunned() { // Do nothing, the player is stunned return } let duration = 0.1 let directionX = node!.xScale / abs(node!.xScale) if shouldShrink { node!.runAction(SKAction.scaleXTo(directionX * Player.shrinkScale, duration: duration)) node!.runAction(SKAction.scaleYTo(0.5, duration: duration)) } else { node!.runAction(SKAction.scaleXTo(directionX * 1.0, duration: duration)) node!.runAction(SKAction.scaleYTo(1.0, duration: duration)) } } class func isBig() -> Bool { return node!.yScale >= 1.0 } class func isSmall() -> Bool { return node!.yScale <= Player.shrinkScale } class func isShrinkingOrGrowing() -> Bool { return node!.yScale < 1.0 && node!.yScale > Player.shrinkScale } class func die() { if Player.isStunned() || Controller.debug { // Do nothing, the player is stunned return } setShrink(false) let duration = 1.0 // Animations to group together let image = SKAction.animateWithTextures(sprites["spacemanDead"]!, timePerFrame: duration) let fade = SKAction.fadeOutWithDuration(duration) // Final animation let group = SKAction.group([image, fade]) // Hold player still for better animation Player.stunCounter = CGFloat(duration + 0.2) node!.physicsBody?.affectedByGravity = false node!.physicsBody?.pinned = true node!.physicsBody?.dynamic = false Player.clearVelocity() // Audio feedback Sound.play("hurt.wav", loop: false) // Visual feedback node!.runAction(group, completion: { () -> Void in // Move player back to start of level World.ShouldReset = true Player.dying = false }) Player.dying = true } class func warp() { if Player.isStunned() { // Do nothing, the player is stunned return } setShrink(false) let duration = 0.5 // Animations to group together let fade = SKAction.fadeOutWithDuration(duration) // Final animation let group = SKAction.group([fade]) // Hold player still for better animation Player.setVelocityX(0.0, force: true) Player.stunCounter = CGFloat(duration + 0.2) node!.physicsBody?.affectedByGravity = false // Warp goal animation let goal = World.getSpriteByName("goal-\(World.Level)") let shrink = SKAction.scaleTo(0.8, duration: 0.2) let grow = SKAction.scaleTo(1.2, duration: 0.5) let groupStar = SKAction.sequence([shrink, grow]) goal.runAction(groupStar, completion: { () -> Void in goal.xScale = 1.0 goal.yScale = 1.0 }) // Audio feedback Sound.play("warp.wav", loop: false) // Visual feedback node!.runAction(group, completion: { () -> Void in // Move player to next level World.nextLevel() }) } class func onGround() -> Bool { return Player.jumpCounter > 0.0 } }
mit
ed7326036fce44aa026d204d815a8665
33.856269
157
0.569624
4.546071
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/WaveViewController.swift
1
4130
// // WaveViewController.swift // SwiftDemoKit // // Created by runo on 17/3/20. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit class WaveViewController: UIViewController { let waveView = WaveView(frame: CGRect.init(x: 0.0, y: 200, width: kScreenWidth, height: 31)) override func viewDidLoad() { super.viewDidLoad() waveView.waveSpeed = 10 waveView.angularSpeed = 1.5 view.addSubview(waveView) waveView.startWave() //画三角函数 let path = CGMutablePath() let layerr = CAShapeLayer() path.move(to: CGPoint.init(x: 0, y: 300)) for i in stride(from: 0, to: kScreenWidth, by: 1) { print( "\(sin(CGFloat(i)))" ) let arg = i/kScreenWidth * (2*CGFloat.pi) let y = 300+(sin(arg) * 100) path.addLine(to: CGPoint.init(x: i, y: y)) } path.addLine(to: CGPoint.init(x: kScreenWidth, y: 300)) path.addLine(to: CGPoint.init(x: kScreenWidth, y: 301)) path.addLine(to: CGPoint.init(x: 0, y: 301)) path.addLine(to: CGPoint.init(x: 0, y: 300)) path.closeSubpath() layerr.path = path layerr.strokeColor = UIColor.black.cgColor layerr.fillColor = UIColor.black.cgColor view.layer.addSublayer(layerr) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if waveView.isWaveing { waveView.stopWave() }else{ waveView.startWave() } } } class WaveView: UIView { var waveSpeed: CGFloat = 4.8 var angularSpeed: CGFloat = 2.0 var waveColor: UIColor = .blue var isWaveing:Bool = false private var waveDisplayLink: CADisplayLink? private var offsetX: CGFloat = 0.0 private var waveShapeLayer: CAShapeLayer? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func stopWave() { UIView.animate(withDuration: 1, animations: { self.alpha = 0 }) { (finished) in self.waveDisplayLink?.invalidate() self.waveDisplayLink = nil self.waveShapeLayer?.removeFromSuperlayer() self.waveShapeLayer = nil self.isWaveing = false self.alpha = 1 } } func startWave() { if waveShapeLayer != nil { return } waveShapeLayer = CAShapeLayer() waveShapeLayer?.fillColor = waveColor.cgColor layer.addSublayer(waveShapeLayer!) /*CADisplayLink:一个和屏幕刷新率相同的定时器,需要以特定的模式注册到runloop中,每次屏幕刷新时,会调用绑定的target上的selector这个方法。 duration:每帧之间的时间 pause:暂停,设置true为暂停,false为继续 结束时,需要调用invalidate方法,并且从runloop中删除之前绑定的target跟selector。 不能被继承 */ waveDisplayLink = CADisplayLink(target: self, selector: #selector(keyFrameWave)) waveDisplayLink?.add(to: .main, forMode: .commonModes) self.isWaveing = true } func keyFrameWave() { offsetX -= waveSpeed let width = frame.size.width let height = frame.size.height //创建path let path = CGMutablePath() path.move(to: CGPoint.init(x: 0, y: height/2)) var y: CGFloat = 0.0 for x in stride(from: 0, to: width, by: 1) { y = height * sin(0.01*(angularSpeed * x + offsetX)) path.addLine(to: CGPoint.init(x: x, y: y)) } path.addLine(to: CGPoint.init(x: width, y: height)) path.addLine(to: CGPoint(x: 0, y: height)) path.closeSubpath() waveShapeLayer?.path = path } }
apache-2.0
984683a075da06aacd113704ab921829
28.689394
96
0.569788
4.031893
false
false
false
false
silence0201/Swift-Study
SimpleProject/RuntimeDemo/RuntimeDemo/Person.swift
1
1817
// // Person.swift // RuntimeDemo // // Created by 杨晴贺 on 2017/3/5. // Copyright © 2017年 Silence. All rights reserved. // import UIKit class Person: NSObject { var name: String? var age: Int = 0 // 基本数据类型在oc没有可选,如果定义成可选运行时同样获取不到,因此使用KVC会崩溃 var title: String? private var no:String? // 使用私有标识符也不能获取到 // 获取当前类的所有属性数组 // static func propertyList() -> [String]{ // var count: UInt32 = 0 // // var result:[String] = [] // // 获取类的属性列表 // let list = class_copyPropertyList(self, &count) // // print("属性的数量: \(count)") // // for i in 0..<Int(count){ // let pty = list?[i] // // 获取属性的名称 // let cName = property_getName(pty!) // 对应c语言字符串 // // // 转化成oc字符串 // let name = String(utf8String: cName!) // result.append(name ?? "") // } static func propertyList() -> [String]{ var count: UInt32 = 0 var result:[String] = [] // 获取类的属性列表 let list = class_copyPropertyList(self, &count) print("属性的数量: \(count)") for i in 0..<Int(count){ // 使用guard语法判断每一项是否有值,只要有一项为nil就不在执行后续的代码 guard let pty = list?[i],let cName = property_getName(pty),let name = String(utf8String: cName) else { continue } result.append(name) } free(list) return result } }
mit
5f07b650d3246aa7d6e1be97023d551e
24.666667
118
0.48961
3.615023
false
false
false
false
danielsanfr/hackatruck-apps-project
HACKATRUCK Apps/AppTableViewCell.swift
1
1049
// // AppTableViewCell.swift // HACKATRUCK Apps // // Created by Student on 3/7/17. // Copyright © 2017 Daniel San. All rights reserved. // import UIKit class AppTableViewCell: UITableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var likes: UILabel! @IBOutlet weak var company: UILabel! private var app = App() override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func onOpenInfo(_ sender: Any) { let url = URL(string: app.relevantLink)! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } func bind(_ app: App) { self.app = app name.text = app.name company.text = app.company likes.text = "\(app.likes) Likes" } }
unlicense
89213bcff926b6bfaf26c5422085ca19
22.818182
65
0.625
4.142292
false
false
false
false
UW-AppDEV/AUXWave
AUXWave/RequestsViewController.swift
1
3387
// // RequestsViewController.swift // AUXWave // // Created by Nico Cvitak on 2015-03-14. // Copyright (c) 2015 UW-AppDEV. All rights reserved. // import UIKit class RequestsViewController: UIViewController, FBLoginViewDelegate { @IBOutlet private var facebookLoginView: FBLoginView? @IBOutlet private var facebookProfilePictureView: FBProfilePictureView? @IBOutlet private var djNameLabel: UILabel? @IBOutlet private var serviceStateView: UIView? @IBOutlet private var serviceStateImageView: UIImageView? @IBOutlet private var serviceStateSwitch: UISwitch? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Add circle mask to djImageView if let facebookProfilePictureView = self.facebookProfilePictureView { facebookProfilePictureView.layer.cornerRadius = facebookProfilePictureView.frame.size.width / 2.0 facebookProfilePictureView.layer.masksToBounds = true } facebookLoginView?.delegate = self djNameLabel?.text = UIDevice.currentDevice().name if let serviceStateView = self.serviceStateView { serviceStateView.layer.cornerRadius = 3.0 serviceStateView.layer.masksToBounds = true } serviceStateSwitch?.on = DJService.localService().isActive } 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. } */ func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!) { let userState = UserState.localUserState() userState.displayName = user.name userState.facebookID = user.objectID self.djNameLabel?.text = userState.displayName self.facebookProfilePictureView?.profileID = userState.facebookID } func loginViewShowingLoggedOutUser(loginView: FBLoginView!) { let userState = UserState.localUserState() userState.displayName = UIDevice.currentDevice().name userState.facebookID = nil self.djNameLabel?.text = userState.displayName self.facebookProfilePictureView?.profileID = userState.facebookID } @IBAction func serviceStateChange(switchState: UISwitch) { if switchState.on { serviceStateImageView?.image = kAUXWaveServiceOnImage let userState = UserState.localUserState() let displayName = userState.displayName var discoveryInfo: [NSObject : AnyObject] = [:] discoveryInfo["facebookID"] = userState.facebookID DJService.localService().start(displayName!, discoveryInfo: discoveryInfo) } else { serviceStateImageView?.image = kAUXWaveServiceOffImage DJService.localService().stop() } } }
gpl-2.0
0d6501888e0ae8634ea2fa82209c900d
33.561224
109
0.664895
5.36767
false
false
false
false
devmynd/drip
Drip/Registry/Registry.swift
1
1236
/** Registry encapsulating a component's storage. Classes conforming to `ComponentType` should declare and instantiate a registry, i.e. `let registry = Registry()` */ public class Registry { private var modules = [Key: Any]() private var parents = [Key: Any]() private var generators = [Key: Any]() public init() {} } // MARK: Parents extension Registry { func get<C: ComponentType>() throws -> C { guard let parent = parents[Key(C.self)] as? C else { throw Error.ComponentNotFound(type: C.self) } return parent } func set<C: ComponentType>(value: C?) { parents[Key(C.self)] = value } } // MARK: Modules extension Registry { func get<M: ModuleType>(key: KeyConvertible) throws -> M { guard let module = modules[key.key()] as? M else { throw Error.ModuleNotFound(type: M.self) } return module } func set<M: ModuleType>(key: KeyConvertible, value: M?) { modules[key.key()] = value } } // MARK: Generators extension Registry { func get<C: ComponentType, T>(key: KeyConvertible) -> (C -> T)? { return generators[key.key()] as? C -> T } func set<C: ComponentType, T>(key: KeyConvertible, value: C -> T) { generators[key.key()] = value } }
mit
6b94812ea7975a25493526e01f441073
21.907407
84
0.63835
3.56196
false
false
false
false
ello/ello-ios
Specs/Controllers/Home/HomeViewControllerSpec.swift
1
1255
//// /// HomeViewControllerSpec.swift // @testable import Ello import Quick import Nimble class HomeViewControllerSpec: QuickSpec { override func spec() { describe("HomeViewController") { var subject: HomeViewController! beforeEach { subject = HomeViewController(usage: .loggedOut) showController(subject) } it("starts out with editorials visible") { expect(subject.visibleViewController) == subject.editorialsViewController } it("shows following view controller") { subject.showFollowingViewController() expect(subject.visibleViewController) == subject.followingViewController } it("shows editorials view controller") { subject.showFollowingViewController() subject.showEditorialsViewController() expect(subject.visibleViewController) == subject.editorialsViewController } it("shows discover view controller") { subject.showDiscoverViewController() expect(subject.visibleViewController) == subject.discoverViewController } } } }
mit
20a76361955d259df377d598e069338a
29.609756
89
0.604781
6.338384
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Exporters/Persistence/PersistenceSpanExporterDecorator.swift
1
2011
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk // a persistence exporter decorator for `SpanData`. // specialization of `PersistenceExporterDecorator` for `SpanExporter`. public class PersistenceSpanExporterDecorator: SpanExporter { struct SpanDecoratedExporter: DecoratedExporter { typealias SignalType = SpanData private let spanExporter: SpanExporter init(spanExporter: SpanExporter) { self.spanExporter = spanExporter } func export(values: [SpanData]) -> DataExportStatus { _ = spanExporter.export(spans: values) return DataExportStatus(needsRetry: false) } } private let spanExporter: SpanExporter private let persistenceExporter: PersistenceExporterDecorator<SpanDecoratedExporter> public init(spanExporter: SpanExporter, storageURL: URL, exportCondition: @escaping () -> Bool = { true }, performancePreset: PersistencePerformancePreset = .default) throws { self.spanExporter = spanExporter self.persistenceExporter = PersistenceExporterDecorator<SpanDecoratedExporter>( decoratedExporter: SpanDecoratedExporter(spanExporter: spanExporter), storageURL: storageURL, exportCondition: exportCondition, performancePreset: performancePreset) } public func export(spans: [SpanData]) -> SpanExporterResultCode { do { try persistenceExporter.export(values: spans) return .success } catch { return .failure } } public func flush() -> SpanExporterResultCode { persistenceExporter.flush() return spanExporter.flush() } public func shutdown() { persistenceExporter.flush() spanExporter.shutdown() } }
apache-2.0
35e1684c5d81a78a9da0b82cda9f8afa
30.421875
88
0.637991
5.812139
false
false
false
false
22377832/swiftdemo
CustomDatePicker/CustomDatePicker/ViewController.swift
1
2677
// // ViewController.swift // CustomDatePicker // // Created by adults on 2017/4/19. // Copyright © 2017年 adults. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var dateView: UIView! @IBOutlet weak var month: UIPickerView! @IBOutlet weak var day: UIPickerView! @IBOutlet weak var time: UIPickerView! let monthData = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",] let dayData = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"] let timeData = ["早上", "下午", "晚上"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == month{ return monthData.count } else if pickerView == day{ return dayData.count } else { return timeData.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView == month{ return monthData[row] } else if pickerView == day{ return dayData[row] } else { return timeData[row] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c7ee034d5497069ac45faf57e6a8c3ac
23.2
111
0.37979
5.522822
false
false
false
false
Kawoou/KWDrawerController
DrawerController/Transition/DrawerFloatTransition.swift
1
3645
/* The MIT License (MIT) Copyright (c) 2017 Kawoou (Jungwon An) 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 open class DrawerFloatTransition: DrawerTransition { // MARK: - Property open var floatFactor: Float // MARK: - Public open override func initTransition(content: DrawerContent) { super.initTransition(content: content) content.isBringToFront = false } open override func startTransition(content: DrawerContent, side: DrawerSide) { super.startTransition(content: content, side: side) } open override func endTransition(content: DrawerContent, side: DrawerSide) { super.endTransition(content: content, side: side) } open override func transition(content: DrawerContent, side: DrawerSide, percentage: CGFloat, viewRect: CGRect) { switch content.drawerSide { case .left: content.contentView.transform = .identity content.contentView.frame = CGRect( x: content.drawerOffset, y: viewRect.minY, width: CGFloat(content.drawerWidth), height: content.contentView.frame.height ) case .right: content.contentView.transform = .identity content.contentView.frame = CGRect( x: content.drawerOffset, y: viewRect.minY, width: CGFloat(content.drawerWidth), height: content.contentView.frame.height ) case .none: #if swift(>=4.2) let scale = CGFloat(1.0 - Float(abs(percentage)) * floatFactor) #else let scale = CGFloat(1.0 - Float(fabs(percentage)) * floatFactor) #endif content.contentView.transform = CGAffineTransform( scaleX: scale, y: scale ) switch side { case .right: content.contentView.frame.origin = CGPoint( x: viewRect.width * percentage * scale, y: (viewRect.height - content.contentView.frame.size.height) * 0.5 ) default: content.contentView.frame.origin = CGPoint( x: viewRect.width * percentage, y: (viewRect.height - content.contentView.frame.size.height) * 0.5 ) } } } // MARK: - Lifecycle public init(floatFactor: Float = 0.2875) { self.floatFactor = floatFactor super.init() } }
mit
08729e6c9326a2bbe7f8e4c27b7e163a
33.714286
116
0.619204
4.847074
false
false
false
false
kzaher/RxSwift
RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
5
2853
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift extension UICollectionView: HasDataSource { public typealias DataSource = UICollectionViewDataSource } private let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() private final class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod(message: dataSourceNotSet) } } /// For more information take a look at `DelegateProxyType`. open class RxCollectionViewDataSourceProxy : DelegateProxy<UICollectionView, UICollectionViewDataSource> , DelegateProxyType , UICollectionViewDataSource { /// Typed parent object. public weak private(set) var collectionView: UICollectionView? /// - parameter collectionView: Parent object for delegate proxy. public init(collectionView: ParentObject) { self.collectionView = collectionView super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourceProxy.self) } // Register known implementations public static func registerKnownImplementations() { self.register { RxCollectionViewDataSourceProxy(collectionView: $0) } } private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet // MARK: delegate /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) } /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) } /// For more information take a look at `DelegateProxyType`. open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
mit
ec8b0ea018083febf51001a130114be4
36.526316
134
0.764025
6.351893
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Points/MOptionWhistlesVsZombiesPoints.swift
1
1156
import Foundation class MOptionWhistlesVsZombiesPoints:MGameUpdate<MOptionWhistlesVsZombies> { private var items:[MOptionWhistlesVsZombiesPointsItem] override init() { items = [] super.init() } override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { for item:MOptionWhistlesVsZombiesPointsItem in items { item.update( elapsedTime:elapsedTime, scene:scene) } } //MARK: public func addPoints(zombie:MOptionWhistlesVsZombiesZombieItem) { let item:MOptionWhistlesVsZombiesPointsItem = MOptionWhistlesVsZombiesPointsItem( zombie:zombie) items.append(item) } func removePoints(points:MOptionWhistlesVsZombiesPointsItem) { var items:[MOptionWhistlesVsZombiesPointsItem] = [] for item:MOptionWhistlesVsZombiesPointsItem in self.items { if item !== points { items.append(item) } } self.items = items } }
mit
447d5f6766184c75ef21a08d6a086f36
23.083333
89
0.596886
5.478673
false
false
false
false
Steveaxelrod007/UtilitiesInSwift
Example/UtilitiesInSwift/ViewController.swift
1
3251
// // ViewController.swift // UtilitiesInSwift // // Created by steveaxelrod007 on 03/06/2017. // Copyright (c) 2017 steveaxelrod007. All rights reserved. // import UIKit import UtilitiesInSwift class ViewController: UIViewController { var cc = CancelableClosure() // axe maintain the var var autoComplete:AutoFillTextField? @IBOutlet weak var textF: UITextField! @IBAction func textFieldChanged() { } func tests() { var num = "123,456.78" print("Origial number --> \(num) \(NumberToWords.convert(amount: num))") num = "0" print("Origial number --> \(num) \(NumberToWords.convert(amount: num))") num = "1" print("Origial number --> \(num) \(NumberToWords.convert(amount: num))") num = "2" print("Origial number --> \(num) \(NumberToWords.convert(amount: num))") num = "1.23" print("Origial number --> \(num) \(NumberToWords.convert(amount: num))") let start = Date().timeIntervalSince1970 Queues.delayThenRunMainQueue(delay: 2) { print("delayed in queue --> \(Date().timeIntervalSince1970 - start)") } print("Available device space --> \(FileSystem.availableDeviceSpace())") // print("Phone is in use --> \(Phone.onPhone())") cc.cancelled = true let newCc = CancelableClosure() newCc.closure = { //[weak self] in print("closure called") } cc = newCc cc.runAfterDelayOf(delayTime: 1.5) let color = UIColor.init(red: 10, green: 20, blue: 30) print("Int value of color --> \(UIColor.hexFromColor(color: color))") print("UIColor from Int --> \(UIColor.colorWithHex(hex: UIColor.hexFromColor(color: color)))") for intVal in [10000, 50000, 100000, 1000000, 10000000, (5280 * 1000) - 1, (5280 * 1000), 999999,999990,999900] { print(intVal.distance()) print(intVal.fullNotation()) print(intVal.kmNotation()) print("------------") } } override func viewDidLoad() { super.viewDidLoad() let listOfNames = [ AutoFillTextFieldData(name: "abc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "frefreabc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "rregergabc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "agregrtegbc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "etrhtrhtrgerghabc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "ztrhtrgregrrhthabc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "abtrhwdwqdtrhthabc", imageUrl: "http://www.axelrod.net/poi.jpg"), AutoFillTextFieldData(name: "iabc", imageUrl: "http://www.axelrod.net/safetynet1.PNG"), AutoFillTextFieldData(name: "babtrhwdwqdtrhthabc", imageUrl: "http://www.axelrod.net/poi.jpg"), ] autoComplete = AutoFillTextField(triggers: "@+*", textF: textF, view: view, list: listOfNames, backColor: UIColor.clear) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tests() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
1390a63591d23cfb1b42b36c7032b6a8
27.517544
121
0.650261
3.507012
false
false
false
false
FabrizioBrancati/SwiftyBot
Sources/Messenger/Response/Button.swift
1
2411
// // Button.swift // SwiftyBot // // The MIT License (MIT) // // Copyright (c) 2016 - 2019 Fabrizio Brancati. // // 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 /// Button helper. public struct Button: Codable, Equatable { /// Button type. public private(set) var type: ButtonType /// Button title. public private(set) var title: String /// Button payload, postback type only. public private(set) var payload: String? /// Button URL, webURL type only. public private(set) var url: String? /// Creates a Button for Messenger structured message element. /// /// - Parameters: /// - title: Button type. /// - url: Button URL. public init(title: String, url: String) { /// Set Button type. self.type = .webURL /// Set Button title. self.title = title /// Is a webURL type, so set its url. self.url = url } /// Creates a Button for Messenger structured message element. /// /// - Parameters: /// - title: Button type. /// - payload: Button payload. public init(title: String, payload: String) { /// Set Button type. self.type = .postback /// Set Button title. self.title = title /// Is a postback type, so set its payload. self.payload = payload } }
mit
a181d30b0da6bc6cb8ff7e8c37b37396
34.985075
82
0.661136
4.267257
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Conversation/ZMConversation+Services.swift
1
2149
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation extension ZMConversation { public class func existingConversation(in moc: NSManagedObjectContext, service: ServiceUser, team: Team?) -> ZMConversation? { guard let team = team else { return nil } guard let serviceID = service.serviceIdentifier else { return nil } let sameTeam = predicateForConversations(in: team) let groupConversation = NSPredicate(format: "%K == %d", ZMConversationConversationTypeKey, ZMConversationType.group.rawValue) let selfIsActiveMember = NSPredicate(format: "ANY %K.user == %@", ZMConversationParticipantRolesKey, ZMUser.selfUser(in: moc)) let onlyOneOtherParticipant = NSPredicate(format: "%K.@count == 2", ZMConversationParticipantRolesKey) let hasParticipantWithServiceIdentifier = NSPredicate(format: "ANY %K.user.%K == %@", ZMConversationParticipantRolesKey, #keyPath(ZMUser.serviceIdentifier), serviceID) let noUserDefinedName = NSPredicate(format: "%K == nil", #keyPath(ZMConversation.userDefinedName)) let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [sameTeam, groupConversation, selfIsActiveMember, onlyOneOtherParticipant, hasParticipantWithServiceIdentifier, noUserDefinedName]) let fetchRequest = sortedFetchRequest(with: predicate) fetchRequest.fetchLimit = 1 let result = moc.fetchOrAssert(request: fetchRequest) return result.first as? ZMConversation } }
gpl-3.0
b16cf4601b809b3b155a26165756f3a1
52.725
206
0.746394
4.73348
false
false
false
false
lorentey/swift
test/Sema/type_join.swift
3
6173
// RUN: %target-typecheck-verify-swift -parse-stdlib import Swift class C {} class D : C {} protocol L {} protocol M : L {} protocol N : L {} protocol P : M {} protocol Q : M {} protocol R : L {} protocol Y {} protocol FakeEquatable {} protocol FakeHashable : FakeEquatable {} protocol FakeExpressibleByIntegerLiteral {} protocol FakeNumeric : FakeEquatable, FakeExpressibleByIntegerLiteral {} protocol FakeSignedNumeric : FakeNumeric {} protocol FakeComparable : FakeEquatable {} protocol FakeStrideable : FakeComparable {} protocol FakeCustomStringConvertible {} protocol FakeBinaryInteger : FakeHashable, FakeNumeric, FakeCustomStringConvertible, FakeStrideable {} protocol FakeLosslessStringConvertible {} protocol FakeFixedWidthInteger : FakeBinaryInteger, FakeLosslessStringConvertible {} protocol FakeUnsignedInteger : FakeBinaryInteger {} protocol FakeSignedInteger : FakeBinaryInteger, FakeSignedNumeric {} protocol FakeFloatingPoint : FakeSignedNumeric, FakeStrideable, FakeHashable {} protocol FakeExpressibleByFloatLiteral {} protocol FakeBinaryFloatingPoint : FakeFloatingPoint, FakeExpressibleByFloatLiteral {} func expectEqualType<T>(_: T.Type, _: T.Type) {} func commonSupertype<T>(_: T, _: T) -> T {} // expected-note 2 {{generic parameters are always considered '@escaping'}} expectEqualType(Builtin.type_join(Int.self, Int.self), Int.self) expectEqualType(Builtin.type_join_meta(D.self, C.self), C.self) expectEqualType(Builtin.type_join(Int?.self, Int?.self), Int?.self) expectEqualType(Builtin.type_join(Int.self, Int?.self), Int?.self) expectEqualType(Builtin.type_join(Int?.self, Int.self), Int?.self) expectEqualType(Builtin.type_join(Int.self, Int??.self), Int??.self) expectEqualType(Builtin.type_join(Int??.self, Int.self), Int??.self) expectEqualType(Builtin.type_join(Int?.self, Int??.self), Int??.self) expectEqualType(Builtin.type_join(Int??.self, Int?.self), Int??.self) expectEqualType(Builtin.type_join(D?.self, D?.self), D?.self) expectEqualType(Builtin.type_join(C?.self, D?.self), C?.self) expectEqualType(Builtin.type_join(D?.self, C?.self), C?.self) expectEqualType(Builtin.type_join(D.self, D?.self), D?.self) expectEqualType(Builtin.type_join(D?.self, D.self), D?.self) expectEqualType(Builtin.type_join(C.self, D?.self), C?.self) expectEqualType(Builtin.type_join(D?.self, C.self), C?.self) expectEqualType(Builtin.type_join(D.self, C?.self), C?.self) expectEqualType(Builtin.type_join(C?.self, D.self), C?.self) expectEqualType(Builtin.type_join(Any?.self, D.self), Any?.self) expectEqualType(Builtin.type_join(D.self, Any?.self), Any?.self) expectEqualType(Builtin.type_join(Any.self, D?.self), Any?.self) expectEqualType(Builtin.type_join(D?.self, Any.self), Any?.self) expectEqualType(Builtin.type_join(Any?.self, Any.self), Any?.self) expectEqualType(Builtin.type_join(Any.self, Any?.self), Any?.self) expectEqualType(Builtin.type_join(Builtin.Int1.self, Builtin.Int1.self), Builtin.Int1.self) expectEqualType(Builtin.type_join(Builtin.Int32.self, Builtin.Int1.self), Any.self) expectEqualType(Builtin.type_join(Builtin.Int1.self, Builtin.Int32.self), Any.self) expectEqualType(Builtin.type_join(L.self, L.self), L.self) expectEqualType(Builtin.type_join(L.self, M.self), L.self) expectEqualType(Builtin.type_join(L.self, P.self), L.self) expectEqualType(Builtin.type_join(L.self, Y.self), Any.self) expectEqualType(Builtin.type_join(N.self, P.self), L.self) expectEqualType(Builtin.type_join(Q.self, P.self), M.self) expectEqualType(Builtin.type_join((N & P).self, (Q & R).self), M.self) expectEqualType(Builtin.type_join((Q & P).self, (Y & R).self), L.self) expectEqualType(Builtin.type_join(FakeEquatable.self, FakeEquatable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeHashable.self, FakeEquatable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeEquatable.self, FakeHashable.self), FakeEquatable.self) expectEqualType(Builtin.type_join(FakeNumeric.self, FakeHashable.self), FakeEquatable.self) expectEqualType(Builtin.type_join((FakeHashable & FakeStrideable).self, (FakeHashable & FakeNumeric).self), FakeHashable.self) expectEqualType(Builtin.type_join((FakeNumeric & FakeStrideable).self, (FakeHashable & FakeNumeric).self), FakeNumeric.self) expectEqualType(Builtin.type_join(FakeBinaryInteger.self, FakeFloatingPoint.self), (FakeHashable & FakeNumeric & FakeStrideable).self) expectEqualType(Builtin.type_join(FakeFloatingPoint.self, FakeBinaryInteger.self), (FakeHashable & FakeNumeric & FakeStrideable).self) func joinFunctions( _ escaping: @escaping () -> (), _ nonescaping: () -> () ) { _ = commonSupertype(escaping, escaping) _ = commonSupertype(nonescaping, escaping) // expected-error@-1 {{converting non-escaping parameter 'nonescaping' to generic parameter 'T' may allow it to escape}} _ = commonSupertype(escaping, nonescaping) // expected-error@-1 {{converting non-escaping parameter 'nonescaping' to generic parameter 'T' may allow it to escape}} let x: Int = 1 // FIXME: We emit these diagnostics here because we refuse to allow // Any to be inferred for the generic type. That's pretty // arbitrary. _ = commonSupertype(escaping, x) // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type '() -> ()'}} _ = commonSupertype(x, escaping) // expected-error@-1 {{cannot convert value of type '() -> ()' to expected argument type 'Int'}} let a: Any = 1 _ = commonSupertype(nonescaping, a) // expected-error@-1 {{converting non-escaping value to 'Any' may allow it to escape}} _ = commonSupertype(a, nonescaping) // expected-error@-1 {{converting non-escaping value to 'Any' may allow it to escape}} _ = commonSupertype(escaping, a) _ = commonSupertype(a, escaping) expectEqualType(Builtin.type_join(((C) -> C).self, ((C) -> D).self), ((C) -> C).self) } func rdar37241221(_ a: C?, _ b: D?) { let c: C? = C() let array_c_opt = [c] let inferred = [a!, b] expectEqualType(type(of: array_c_opt).self, type(of: inferred).self) }
apache-2.0
18154db5ef40f4e82d83fea93e70f843
49.598361
122
0.731249
3.568208
false
false
false
false
alblue/swift
test/stdlib/BridgeStorage.swift
1
5217
//===--- BridgeStorage.swift.gyb ------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Bridged types are notionally single-word beasts that either store // an objc class or a native Swift class. We'd like to be able to // distinguish these cases efficiently. // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Swift //===--- Code mimics the stdlib without using spare pointer bits ----------===// import SwiftShims protocol BridgeStorage { associatedtype Native : AnyObject associatedtype ObjC : AnyObject init(native: Native, isFlagged: Bool) init(native: Native) init(objC: ObjC) mutating func isUniquelyReferencedNative() -> Bool mutating func isUniquelyReferencedUnflaggedNative() -> Bool var isNative: Bool {get} var isObjC: Bool {get} var nativeInstance: Native {get} var unflaggedNativeInstance: Native {get} var objCInstance: ObjC {get} } extension _BridgeStorage : BridgeStorage {} //===----------------------------------------------------------------------===// //===--- Testing code -----------------------------------------------------===// //===----------------------------------------------------------------------===// import StdlibUnittest var allTests = TestSuite("DiscriminatedBridgeObject") class C { deinit { print("bye C!") } } import Foundation func isOSAtLeast(_ major: Int, _ minor: Int, patch: Int = 0) -> Bool { // isOperatingSystemAtLeastVersion() is unavailable on some OS versions. if #available(iOS 8.0, OSX 10.10, *) { let procInfo: AnyObject = ProcessInfo.processInfo return procInfo.isOperatingSystemAtLeast( OperatingSystemVersion(majorVersion: major, minorVersion: minor, patchVersion: patch)) } return false } func expectTagged(_ s: NSString, _ expected: Bool) -> NSString { #if arch(x86_64) let mask: UInt = 0x8000000000000001 #elseif arch(arm64) let mask: UInt = 0x8000000000000000 #else let mask: UInt = 0 #endif var osSupportsTaggedStrings: Bool #if os(iOS) // NSTaggedPointerString is enabled starting in iOS 9.0. osSupportsTaggedStrings = isOSAtLeast(9,0) #elseif os(tvOS) || os(watchOS) // NSTaggedPointerString is supported in all versions of TVOS and watchOS. osSupportsTaggedStrings = true #elseif os(OSX) // NSTaggedPointerString is enabled starting in OS X 10.10. osSupportsTaggedStrings = isOSAtLeast(10,10) #endif let taggedStringsSupported = osSupportsTaggedStrings && mask != 0 let tagged = unsafeBitCast(s, to: UInt.self) & mask != 0 if taggedStringsSupported && expected == tagged { // okay } else if !taggedStringsSupported && !tagged { // okay } else { let un = !tagged ? "un" : "" fatalError("Unexpectedly \(un)tagged pointer for string \"\(s)\"") } return s } var taggedNSString : NSString { return expectTagged(NSString(format: "foo"), true) } var unTaggedNSString : NSString { return expectTagged("fûtbōl" as NSString, false) } allTests.test("_BridgeStorage") { typealias B = _BridgeStorage<C, NSString> let oy: NSString = "oy" expectTrue(B(objC: oy).objCInstance == oy) for flag in [false, true] { do { var b = B(native: C(), isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.isUniquelyReferencedNative()) if !flag { expectTrue(b.isUniquelyReferencedUnflaggedNative()) } } do { let c = C() var b = B(native: c, isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectFalse(b.isUniquelyReferencedNative()) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.nativeInstance === c) if !flag { expectTrue(b.unflaggedNativeInstance === c) expectFalse(b.isUniquelyReferencedUnflaggedNative()) } } } var b = B(native: C(), isFlagged: false) expectTrue(b.isUniquelyReferencedNative()) // Add a reference and verify that it's still native but no longer unique var c = b expectFalse(b.isUniquelyReferencedNative()) _fixLifetime(c) // make sure c is not killed early let n = C() var bb = B(native: n) expectTrue(bb.nativeInstance === n) expectTrue(bb.isNative) expectTrue(bb.isUnflaggedNative) expectFalse(bb.isObjC) var d = B(objC: taggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) d = B(objC: unTaggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) } runAllTests()
apache-2.0
f233a44522dec486328c76b07685bcb5
27.653846
80
0.639693
4.342215
false
false
false
false
likojack/wedrive_event_management
weDrive/ContactListViewController.swift
2
3055
// // ContactListViewController.swift // weDrive // // Created by kejielee on 27/07/2015. // Copyright (c) 2015 michelle. All rights reserved. // import UIKit class ContactListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var people = ["George", "Ben", "Cindy"] var name : String = "" var note : String = "" var from : String = "" var to : String = "" var selectedCell : [Int] = [] var selectedPeople : [String] = [] override func viewDidLoad() { super.viewDidLoad() self.ContactListTableView.dataSource = self self.ContactListTableView.delegate = self let backButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelTapped:") navigationItem.leftBarButtonItem = backButton let rightButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneTapped:") navigationItem.rightBarButtonItem = rightButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var ContactListTableView: UITableView! func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.people.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() cell.textLabel?.text = people[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedPeople.append(people[indexPath.row]) } @IBAction func cancelTapped(sender: AnyObject) { self.performSegueWithIdentifier("contactCancelSegue", sender: self) } @IBAction func doneTapped(sender: AnyObject) { self.performSegueWithIdentifier("peopleAddedSegue", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "peopleAddedSegue" { var eventCreateViewController = segue.destinationViewController as! CreateEventViewController eventCreateViewController.people = self.selectedPeople eventCreateViewController.name = self.name eventCreateViewController.note = self.note eventCreateViewController.from = self.from eventCreateViewController.to = self.to } if segue.identifier == "contactCancelSegue" { var eventCreateViewController = segue.destinationViewController as! CreateEventViewController eventCreateViewController.people = self.selectedPeople eventCreateViewController.name = self.name eventCreateViewController.note = self.note eventCreateViewController.from = self.from eventCreateViewController.to = self.to } } }
apache-2.0
1dd871a3b90c14f44eb4e693074ab955
37.1875
131
0.684124
5.340909
false
false
false
false
benlangmuir/swift
test/stdlib/ImplicitlyUnwrappedOptional.swift
34
1876
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test var x : Int! = .none if x != nil { print("x is non-empty!") } else { print("an empty optional is logically false") } // CHECK: an empty optional is logically false x = .some(0) if x != nil { print("a non-empty optional is logically true") } else { print("x is empty!") } // CHECK: a non-empty optional is logically true class C {} var c : C! = C() if c === nil { print("x is nil!") } else { print("a non-empty class optional should not equal nil") } // CHECK: a non-empty class optional should not equal nil c = nil if c === nil { print("an empty class optional should equal nil") } else { print("x is not nil!") } // CHECK: an empty class optional should equal nil import StdlibUnittest import Swift var ImplicitlyUnwrappedOptionalTests = TestSuite("ImplicitlyUnwrappedOptional") ImplicitlyUnwrappedOptionalTests.test("flatMap") { // FIXME(19798684): can't call map or flatMap on ImplicitlyUnwrappedOptional // let half: Int32 -> Int16! = // { if $0 % 2 == 0 { return Int16($0 / 2) } else { return .none } } // expectEqual(2 as Int16, half(4)) // expectNil(half(3)) // expectNil((.none as Int!).flatMap(half)) // expectEqual(2 as Int16, (4 as Int!).flatMap(half)) // expectNil((3 as Int!).flatMap(half)) } infix operator *^* : ComparisonPrecedence func *^*(lhs: Int?, rhs: Int?) -> Bool { return true } func *^*(lhs: Int, rhs: Int) -> Bool { return true } ImplicitlyUnwrappedOptionalTests.test("preferOptional") { let i: Int! = nil let j: Int = 1 if i != j {} // we should choose != for Optionals rather than forcing i if i == j {} // we should choose == for Optionals rather than forcing i // FIXME: https://bugs.swift.org/browse/SR-6988 // if i *^* j {} // we should choose *^* for Optionals rather than forcing i } runAllTests()
apache-2.0
cf68ffe5fda46aa204bf73790d743a00
24.351351
79
0.655117
3.467652
false
true
false
false
GuiBayma/PasswordVault
PasswordVault/Scenes/Authentication/New Password/NewPasswordView.swift
1
2295
// // NewPasswordView.swift // PasswordVault // // Created by Guilherme Bayma on 8/7/17. // Copyright © 2017 Bayma. All rights reserved. // import UIKit import SnapKit class NewPasswordView: UIView { // MARK: - Components let label = UILabel() let labeledTextField = LabeledTextField() let button = DoneButton() // MARK: - Initialization required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white self.addSubview(label) self.addSubview(labeledTextField) self.addSubview(button) setConstraints() } // MARK: - Constraints internal func setConstraints() { // Label label.snp.makeConstraints { (maker) in maker.top.equalTo(self).offset(80) maker.left.equalTo(self).offset(20) maker.right.equalTo(self).offset(-20) } label.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightRegular) label.numberOfLines = 3 label.text = "Escolha uma senha que será requisitada sempre que voltar ao aplicativo." label.textAlignment = .justified // Labeled Text Field labeledTextField.snp.makeConstraints { (maker) in maker.top.equalTo(label.snp.bottom).offset(15) maker.trailing.equalTo(label.snp.trailing) maker.leading.equalTo(label.snp.leading) maker.height.equalTo(60) } labeledTextField.label.text = "Senha" labeledTextField.textField.returnKeyType = .done labeledTextField.textField.isSecureTextEntry = true // Button button.snp.makeConstraints { (maker) in maker.top.equalTo(labeledTextField.snp.bottom).offset(10) maker.trailing.equalTo(labeledTextField.snp.trailing) } button.addTarget(self, action: #selector(self.registerButtonTouched(_:)), for: .touchUpInside) } // MARK: - Button action var buttonAction: (() -> Void)? internal func registerButtonTouched(_ sender: UIButton) { buttonAction?() } }
mit
f98dbe0b6502d11765478370c6607e88
28.397436
102
0.610554
4.576846
false
false
false
false
CosynPa/TZStackView
TZStackView/TZStackViewDistribution.swift
1
1940
// // TZStackViewDistribution.swift // TZStackView // // Created by Tom van Zummeren on 10/06/15. // Copyright © 2015 Tom van Zummeren. All rights reserved. // import Foundation /* Distribution—the layout along the stacking axis. All UIStackViewDistribution enum values fit first and last arranged subviews tightly to the container, and except for UIStackViewDistributionFillEqually, fit all items to intrinsicContentSize when possible. */ @objc public enum TZStackViewDistribution : Int { /* When items do not fit (overflow) or fill (underflow) the space available adjustments occur according to compressionResistance or hugging priorities of items, or when that is ambiguous, according to arrangement order. */ case Fill = 0 /* Items are all the same size. When space allows, this will be the size of the item with the largest intrinsicContentSize (along the axis of the stack). Overflow or underflow adjustments are distributed equally among the items. */ case FillEqually = 1 /* Overflow or underflow adjustments are distributed among the items proportional to their intrinsicContentSizes. */ case FillProportionally = 2 /* Additional underflow spacing is divided equally in the spaces between the items. Overflow squeezing is controlled by compressionResistance priorities followed by arrangement order. */ case EqualSpacing = 3 /* Equal center-to-center spacing of the items is maintained as much as possible while still maintaining a minimum edge-to-edge spacing within the allowed area. Additional underflow spacing is divided equally in the spacing. Overflow squeezing is distributed first according to compressionResistance priorities of items, then according to subview order while maintaining the configured (edge-to-edge) spacing as a minimum. */ case EqualCentering = 4 }
mit
cdd743c9bfded59cd166592268c13fc3
36.980392
103
0.743418
5.137931
false
false
false
false
sochalewski/TinySwift
TinySwift/UIScreen.swift
1
3676
// // UIScreen.swift // TinySwift // // Created by Piotr Sochalewski on 26.09.2016. // Copyright © 2016 Piotr Sochalewski. All rights reserved. // import UIKit #if !os(watchOS) /// The display diagonal screen size representation. public enum ScreenSize: Int, Equatable, Comparable { /// An unknown screen size. case unknown /// The 3.5" screen size. case inch3p5 /// The 4.0" screen size. case inch4 /// The 4.7" screen size. case inch4p7 /// The 5.4" screen size. case inch5p4 /// The 5.5" screen size. case inch5p5 /// The 5.8" screen size. case inch5p8 /// The 6.1" screen size. case inch6p1 /// The 6.5" screen size. case inch6p5 /// The 6.7" screen size. case inch6p7 /// The 7.9" screen size. case inch7p9 /// The 8.3" screen size. case inch8p3 /// The 9.7" screen size. case inch9p7 /// The 10.2" screen size. case inch10p2 /// The 10.5" screen size. case inch10p5 /// The 10.9" screen size. case inch10p9 /// The 11.0" screen size. case inch11 /// The 12.9" screen size. case inch12p9 } public func <(lhs: ScreenSize, rhs: ScreenSize) -> Bool { return lhs.rawValue < rhs.rawValue } #if swift(>=4.2) extension ScreenSize: CaseIterable {} #endif public extension UIScreen { #if os(iOS) /// Returns the display diagonal screen size. var size: ScreenSize { let height = max(bounds.width, bounds.height) switch height { case 240, 480: return .inch3p5 case 568: return .inch4 case 667: return scale == 3.0 ? .inch5p5 : .inch4p7 case 736: return .inch5p5 case 812: switch UIDevice.current.device { case .phone(.iPhone12Mini): return .inch5p4 default: return .inch5p8 } case 844, 852: return .inch6p1 case 896: switch UIDevice.current.device { case .phone(.iPhoneXSMax), .phone(.iPhone11ProMax): return .inch6p5 default: return .inch6p1 } case 926, 932: return .inch6p7 case 1024: switch UIDevice.current.device { case .pad(.iPadMini), .pad(.iPadMini2), .pad(.iPadMini3), .pad(.iPadMini4), .pad(.iPadMini5): return .inch7p9 case .pad(.iPadPro2(.inch10p5)): return .inch10p5 default: return .inch9p7 } case 1080: return .inch10p2 case 1112: return .inch10p5 case 1133: return .inch8p3 case 1180: return .inch10p9 case 1194: return .inch11 case 1366: return .inch12p9 default: return .unknown } } /// A Boolean value that determines whether the display diagonal screen size equals 3.5" for iPhones (iPhone 4s and older) or 7.9" for iPads (iPad mini). var isSmallScreen: Bool { return [ScreenSize.inch3p5, ScreenSize.inch7p9].contains(size) } #endif #if os(tvOS) /// A Boolean value that determines whether the display screen resolution is equal or lower than 720p. var isLowResolution: Bool { return min(bounds.width, bounds.height) <= 720.0 } #endif } #endif
mit
1ce2137e49f6bd30c27051561c3cdb02
29.882353
161
0.525714
3.998912
false
false
false
false
JGiola/swift
test/attr/attr_originally_definedin_backward_compatibility.swift
5
3808
// REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios // UNSUPPORTED: DARWIN_SIMULATOR=ios // rdar://problem/64298096 // XFAIL: OS=ios && CPU=arm64 // rdar://problem/65399527 // XFAIL: OS=ios && CPU=armv7s // // RUN: %empty-directory(%t) // // ----------------------------------------------------------------------------- // --- Prepare SDK (.swiftmodule). // RUN: %empty-directory(%t/SDK) // // --- Build original high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighlevelOriginal.swift -Xlinker -install_name -Xlinker @rpath/HighLevel.framework/HighLevel -enable-library-evolution // --- Build an executable using the original high level framework // RUN: %target-build-swift -emit-executable %s -g -o %t/HighlevelRunner -F %t/SDK/Frameworks/ -framework HighLevel \ // RUN: %target-rpath(@executable_path/SDK/Frameworks) // --- Run the executable // RUN: %target-codesign %t/SDK/Frameworks/HighLevel.framework/HighLevel // RUN: %target-codesign %t/HighlevelRunner // RUN: %target-run %t/HighlevelRunner %t/SDK/Frameworks/HighLevel.framework/HighLevel | %FileCheck %s -check-prefix=BEFORE_MOVE // --- Build low level framework. // RUN: mkdir -p %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/LowLevel.framework/LowLevel) -module-name LowLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/LowLevel.swift -Xlinker -install_name -Xlinker @rpath/LowLevel.framework/LowLevel -enable-library-evolution \ // RUN: -Xfrontend -define-availability -Xfrontend "_iOS13Aligned:macOS 10.10, iOS 8.0" // --- Build high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevel.swift -F %t/SDK/Frameworks -Xlinker -reexport_framework -Xlinker LowLevel -enable-library-evolution // --- Run the executable // RUN: %target-codesign %t/SDK/Frameworks/HighLevel.framework/HighLevel // RUN: %target-codesign %t/SDK/Frameworks/LowLevel.framework/LowLevel // RUN: %target-codesign %t/HighlevelRunner // RUN: %target-run %t/HighlevelRunner %t/SDK/Frameworks/HighLevel.framework/HighLevel %t/SDK/Frameworks/LowLevel.framework/LowLevel | %FileCheck %s -check-prefix=AFTER_MOVE import HighLevel printMessage() printMessageMoved() // BEFORE_MOVE: Hello from HighLevel // BEFORE_MOVE: Hello from HighLevel // AFTER_MOVE: Hello from LowLevel // AFTER_MOVE: Hello from LowLevel let e = Entity() print(e.location()) // BEFORE_MOVE: Entity from HighLevel // AFTER_MOVE: Entity from LowLevel print(CandyBox(Candy()).ItemKind) // BEFORE_MOVE: candy // AFTER_MOVE: candy print(CandyBox(Candy()).shape()) // BEFORE_MOVE: square // AFTER_MOVE: round print(LanguageKind.Cpp.rawValue) // BEFORE_MOVE: -1 // AFTER_MOVE: 1 print("\(Vehicle().currentSpeed)") // BEFORE_MOVE: -40 // AFTER_MOVE: 40 class Bicycle: Vehicle {} let bicycle = Bicycle() bicycle.currentSpeed = 15.0 print("\(bicycle.currentSpeed)") // BEFORE_MOVE: 15.0 // AFTER_MOVE: 15.0 funcMacro() // BEFORE_MOVE: Macro from HighLevel // AFTER_MOVE: Macro from LowLevel
apache-2.0
909b0073e951c59af9900735308ca0bb
40.846154
173
0.728466
3.552239
false
false
false
false
MakeAWishFoundation/SwiftyMocky
Sources/CLI/Core/InteractiveOptions/ProjectOption.swift
1
2387
import Foundation import Chalk import PathKit public struct ProjectPathOption: RawRepresentable, SelectableOption { public typealias RawValue = String private static var projects: [Path] = [] public var rawValue: String public var title: String { if rawValue == ProjectPathOption.projects.first?.string { let formatted = ck.underline.on("\(Path(rawValue).lastComponentWithoutExtension)") return "\(formatted)" } return Path(rawValue).lastComponentWithoutExtension } public init?(rawValue: RawValue) { guard !ProjectPathOption.projects.isEmpty else { return nil } guard !rawValue.isEmpty else { self.rawValue = ProjectPathOption.projects.first!.string return } let matching = ProjectPathOption.projects.filter { $0.lastComponent.hasPrefix(rawValue) } guard !matching.isEmpty else { Message.warning("No project with that name!") return nil } guard matching.count == 1 else { Message.warning("Project name ambigious! Found:") Message.indent() matching.forEach { path in Message.infoPoint("\(path)") } Message.unindent() return nil } self.rawValue = matching[0].string } init(_ rawValue: RawValue) { self.rawValue = rawValue } static func select(project name: Path, at root: Path) throws -> Path { var paths = name.string.isEmpty ? root.glob("*.xcodeproj") : [name.xcproj(with: root)] paths = paths.map { $0.dropSlash() } guard !paths.isEmpty else { throw MockyError.projectNotFound } guard paths.count > 1 else { return paths[0] } ProjectPathOption.projects = paths Message.warning("Several projects found! Choose xcodeproj file.") let options = paths.map { ProjectPathOption($0.string) } let selected = Path(select(from: options).rawValue) Message.empty() Message.subheader("Selected: \(selected.lastComponent)\n") return selected } } private extension Path { func xcproj(with root: Path) -> Path { return (root + self).dropSlash() } func dropSlash() -> Path { return string.hasSuffix("/") ? Path(String(string.dropLast())) : self } }
mit
99f83c90dd856c4ee5afe610e63523be
30.826667
97
0.61416
4.708087
false
false
false
false
nguyentruongky/FirebaseChat
FirebaseChat/ChatInputContainerView.swift
1
3532
// // ChatInputswift // FirebaseChat // // Created by Ky Nguyen on 11/12/16. // Copyright © 2016 Ky Nguyen. All rights reserved. // import UIKit class ChatInputContainerView : UIView, UITextFieldDelegate { weak var chatLogController : ChatLogController? { didSet { sendButton.addTarget(chatLogController!, action: #selector(ChatLogController.handleSend), for: .touchUpInside) uploadImageView.addGestureRecognizer(UITapGestureRecognizer(target: chatLogController, action: #selector(ChatLogController.handleUploadTap))) } } let sendButton: UIButton = { let sendButton = UIButton(type: .system) sendButton.translatesAutoresizingMaskIntoConstraints = false sendButton.setTitle("Send", for: .normal) return sendButton }() let uploadImageView : UIImageView = { let uploadImageView = UIImageView() uploadImageView.image = UIImage(named: "camera") uploadImageView.contentMode = .scaleAspectFit uploadImageView.translatesAutoresizingMaskIntoConstraints = false return uploadImageView }() lazy var inputTextField : UITextField = { let tf = UITextField() tf.delegate = self tf.placeholder = "Your message goes here" tf.translatesAutoresizingMaskIntoConstraints = false tf.autocorrectionType = .no return tf }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white addSubview(uploadImageView) uploadImageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true uploadImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true uploadImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true uploadImageView.heightAnchor.constraint(equalTo: uploadImageView.widthAnchor).isActive = true uploadImageView.isUserInteractionEnabled = true addSubview(sendButton) sendButton.rightAnchor.constraint(equalTo: rightAnchor, constant: 8).isActive = true sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true sendButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true addSubview(self.inputTextField) inputTextField.leftAnchor.constraint(equalTo: uploadImageView.rightAnchor, constant: 18).isActive = true inputTextField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true inputTextField.heightAnchor.constraint(equalToConstant: 44).isActive = true inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true let separator = UIView() separator.backgroundColor = UIColor.lightGray separator.translatesAutoresizingMaskIntoConstraints = false addSubview(separator) separator.topAnchor.constraint(equalTo: topAnchor).isActive = true separator.leftAnchor.constraint(equalTo: leftAnchor).isActive = true separator.rightAnchor.constraint(equalTo: rightAnchor).isActive = true separator.heightAnchor.constraint(equalToConstant: 0.5).isActive = true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { chatLogController?.handleSend() return true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
fe611fd98ebfd43f8cbb8f2d4c65c47b
36.967742
153
0.692438
5.640575
false
false
false
false
zhuxietong/Eelay
Sources/Eelay/eelay/EeLay.swift
1
21115
// // EeLay.swift // EeLay // // Created by zhuxietong on 2016/12/16. // Copyright © 2016年 zhuxietong. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit fileprivate struct SoNode<DataType>{ static func count(list:[Any]) -> Int { var count = 0 for one in list { if let _ = one as? DataType { count += 1 } } return count } } fileprivate class SoPaw { public static func strings<T:Sequence>(list:T) ->[String] { var str_values = [String]() for t in list { str_values.append("\(t)") } return str_values } } prefix operator .> prefix operator .< public prefix func .><T>(value:T) -> [String:T] { return [">":value] } public prefix func .<<T>(value:T) -> [String:T] { return ["<":value] } infix operator .+ public func .+<T>(value:T,p:Double) -> Any { if var one = value as? [String:NumberValue] { one["p"] = p.doubleValue return one } if var one = value as? [String:String]{ one["p"] = "\(p)" return one } if let num = value as? NumberValue { return ["=":num.doubleValue,"p":p] } if value is String { return ["=":value,"p":"\(p)"] } return value } public typealias ee = easy enum EasyTarget{ case view case safeArea case none } open class easy { static var priority:Float = 800 public class lay{ var value:NSLayoutConstraint.Attribute var target:EasyTarget = .view public func constrainTarget(view:UIView?) -> Any? { switch self.target { case .safeArea: if #available(iOS 11.0, *) { return view?.safeAreaLayoutGuide } else { return view // Fallback on earlier versions } case .none: return nil default: return view } } init(v:NSLayoutConstraint.Attribute){ self.value = v } } public class map{ var values:[lay] = [lay]() init(v:NSLayoutConstraint.Attribute,p:Float=easy.priority){ self.values.append(lay(v: v)) } public var T:easy.map{ self.values.append(lay(v: .top)) return self } public var B:easy.map{ self.values.append(lay(v: .bottom)) return self } public var L:easy.map{ self.values.append(lay(v: .left)) return self } public var R:easy.map{ self.values.append(lay(v: .right)) return self } public var X:easy.map{ self.values.append(lay(v: .centerX)) return self } public var Y:easy.map{ self.values.append(lay(v: .centerY)) return self } public var safe:easy.map{ for one in values { one.target = .safeArea } return self } public var view:easy.map{ for one in values { one.target = .view } return self } public var none:easy.map{ for one in values { one.target = .none } return self } public var width:easy.map{ self.values.append(lay(v: .width)) return self } public var height:easy.map{ self.values.append(lay(v: .height)) return self } } public static var T:easy.map{ return map(v: NSLayoutConstraint.Attribute.top) } public static var B:easy.map{ return map(v: NSLayoutConstraint.Attribute.bottom) } public static var L:easy.map{ return map(v: NSLayoutConstraint.Attribute.left) } public static var R:easy.map{ return map(v: NSLayoutConstraint.Attribute.right) } public static var X:easy.map{ return map(v: NSLayoutConstraint.Attribute.centerX) } public static var Y:easy.map{ return map(v: NSLayoutConstraint.Attribute.centerY) } public static var width:easy.map{ return map(v: NSLayoutConstraint.Attribute.width) } public static var height:easy.map{ return map(v: NSLayoutConstraint.Attribute.height) } public static var none:easy.map{ return map(v: NSLayoutConstraint.Attribute.notAnAttribute) } } // // //public struct TP { // //} // //public extension TP //{ // typealias lays = [[Any]] //} // // // // //extension String //{ // var cg_float:CGFloat{ // get{ // let str = NSString(string: self) // return CGFloat(str.floatValue) // } // } //} // public extension TP { typealias lays = [[Any]] } extension String { var cg_float:CGFloat{ get{ let str = NSString(string: self) return CGFloat(str.floatValue) } } } public extension UIView{ var eelay:TP.lays { set(newValue){ let format = UIView.eeformat(lays: newValue) _ = UIView.eelay(lays: format, at: self) } get{ return TP.lays() } } @discardableResult func setEeLays(lays:TP.lays) ->([[NSLayoutConstraint]],[NSLayoutConstraint]) { let format = UIView.eeformat(lays: lays) // print(format) return UIView.eelay(lays: format, at: self) } @discardableResult func append(_ rules:Any...)->[NSLayoutConstraint] { if let superV = self.superview { let new_rules = [self] + rules let lays = [ new_rules ] let format = UIView.eeformat(lays: lays) // print(format) return UIView.eelay(lays: format, at: superV).1 } return [NSLayoutConstraint]() } static func eeformat(lays:TP.lays) -> TP.lays { var new_lays = [[Any]]() for one_lay in lays { var new_one = [Any]() for lay in one_lay { //视图------------------------------------------- if let view = lay as? UIView //first view { new_one.append(view) } //宽度------------------------------------------- if let width = lay as? NumberValue { new_one.append(width.doubleValue.+Double(easy.priority)) } //高度------------------------------------------- if let height = lay as? String //height { let ps = height.+Double(easy.priority) new_one.append(ps) } //宽度或高度------------------------------------------- if let dict = lay as? [String:Any] //height { new_one.append(dict) } //约束------------------------------------------- if let list = lay as? [Any] //height { var new_list = [Any]() for constain in list { if let values = constain as? [Any] { var new_values = [Any]() for one_value in values { if let value = one_value as? [String:Any] { new_values.append(value) } else{ new_values.append(one_value.+Double(easy.priority)) } } new_list.append(new_values) } else if constain is UIView{ new_list.append(constain) } else if constain is easy.map{ new_list.append(constain) } else if constain is [String:Any]{ let list = [constain] new_list.append(list) } else { new_list.append([constain.+Double(easy.priority)]) } } new_one.append(new_list) } } new_lays.append(new_one) } return new_lays } @discardableResult class func eelay<T:UIView>(lays:TP.lays,at:T)->([[NSLayoutConstraint]],[NSLayoutConstraint]) { var constrains = [[NSLayoutConstraint]]() if lays.count > 0 { for oneLays in lays{ if let one_view = oneLays[0] as? UIView { one_view.translatesAutoresizingMaskIntoConstraints = false if one_view !== at { if let o = one_view.superview { if o !== at { at.addSubview(one_view) } } else { at.addSubview(one_view) } } } } for oneLays in lays{ var one_constains = [NSLayoutConstraint]() var t_view:UIView = at var item_lays = oneLays if let t_view_1 = item_lays[0] as? UIView { t_view = t_view_1 item_lays.remove(at: 0) // at.addSubview(t_view) } for one in item_lays { //宽度或高度----------------------------------- if let dict = one as? [String:Any] { //----------------------------高度 if let height = dict as? [String:String] { var relatedBy:NSLayoutConstraint.Relation = .equal var value = "0" if height.keys.contains(">") { relatedBy = .greaterThanOrEqual value = height[">"]! } if height.keys.contains("<") { relatedBy = .lessThanOrEqual value = height["<"]! } if height.keys.contains("=") { relatedBy = .equal value = height["="]! } var priority = easy.priority if height.keys.contains("p") { priority = Float(height["p"]!)! } let c = NSLayoutConstraint(item: t_view, attribute: .height, relatedBy: relatedBy, toItem: nil, attribute: .height, multiplier: 1, constant: value.cg_float) c.priority = UILayoutPriority(rawValue: priority) one_constains.append(c) t_view.superview?.addConstraint(c) continue } else{ //----------------------------宽度 let width = dict var relatedBy:NSLayoutConstraint.Relation = .equal var value = "0" if width.keys.contains(">") { relatedBy = .greaterThanOrEqual let _value = width[">"]! value = "\(_value)" } if width.keys.contains("<") { relatedBy = .lessThanOrEqual let _value = width["<"]! value = "\(_value)" } if width.keys.contains("=") { relatedBy = .equal let _value = width["="]! value = "\(_value)" } var priority = easy.priority if width.keys.contains("p") { let _priority = width["p"]! priority = Float("\(_priority)")! } let c = NSLayoutConstraint(item: t_view, attribute: NSLayoutConstraint.Attribute.width, relatedBy: relatedBy, toItem: nil, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1, constant: value.cg_float) c.priority = UILayoutPriority(rawValue:priority) one_constains.append(c) t_view.superview?.addConstraint(c) continue } } if let alay = one as? [Any] { var relate_v = t_view.superview var one_lay:[Any] = Array<Any>(alay) if let v = alay[0] as? UIView { relate_v = v one_lay.remove(at: 0) } let co_count = SoNode<easy.map>.count(list: one_lay) var to_atr = easy.none var this_atr = easy.none if co_count == 1 { to_atr = one_lay[0] as! easy.map this_atr = one_lay[0] as! easy.map } if co_count == 2 { to_atr = one_lay[0] as! easy.map this_atr = one_lay[1] as! easy.map } //取值 var _values = [[String:Any]]() if let v = one_lay.last as? [[String:Any]] { for one_v in v{ _values.append(one_v) } } if to_atr.values.count >= this_atr.values.count { for (i,lay0) in this_atr.values.enumerated() { if lay0.value != NSLayoutConstraint.Attribute.notAnAttribute { let lay1 = to_atr.values[i] var _v = ["p":easy.priority,"=":"0"] as [String : Any] if _values.count > i{ _v = _values[i] } else if _values.count > 0 { _v = _values[0] } else{} var relatedBy:NSLayoutConstraint.Relation = .equal var value = "0" if _v.keys.contains(">") { relatedBy = .greaterThanOrEqual let _value = _v[">"]! value = "\(_value)" } if _v.keys.contains("<") { relatedBy = .lessThanOrEqual let _value = _v["<"]! value = "\(_value)" } if _v.keys.contains("=") { relatedBy = .equal let _value = _v["="]! value = "\(_value)" } var priority = easy.priority if _v.keys.contains("p") { let _priority = _v["p"]! priority = Float("\(_priority)")! } let item = lay0.constrainTarget(view: t_view) let toItem = lay1.constrainTarget(view: relate_v) switch lay0.value { case .width,.height: var multiplier = value.cg_float if multiplier == 0{ multiplier = 1 } let x = NSLayoutConstraint(item: item!, attribute: lay0.value, relatedBy: relatedBy, toItem: toItem, attribute: lay1.value, multiplier: multiplier, constant: 0) x.priority = UILayoutPriority(rawValue:priority) one_constains.append(x) t_view.superview!.addConstraint(x) default: let x = NSLayoutConstraint(item: item!, attribute: lay0.value, relatedBy: relatedBy, toItem: toItem, attribute: lay1.value, multiplier: 1, constant: value.cg_float) x.priority = UILayoutPriority(rawValue:priority) one_constains.append(x) t_view.superview!.addConstraint(x) } } } } } } constrains.append(one_constains) } } var cons = [NSLayoutConstraint]() for cs in constrains { for one_c in cs { cons.append(one_c) } } return (constrains,cons) } } #endif
mit
71e40d759742c458998cac6c4426e9eb
30.722892
239
0.340106
5.883799
false
false
false
false
edjiang/forward-swift-workshop
SwiftNotesIOS/Pods/Stormpath/Stormpath/Networking/Logger.swift
1
2089
// // Logger.swift // Stormpath // // Created by Adis on 27/11/15. // Copyright © 2015 Stormpath. All rights reserved. // import Foundation // Simple logging class flavored for this SDK enum LogLevel { case None case Error case Debug case Verbose } final class Logger { static var logLevel: LogLevel { if _isDebugAssertConfiguration() { return .Debug } else { return .None } } class func log(string: String) { switch logLevel { case .None: break case .Debug, .Verbose, .Error: print("[STORMPATH] \(string)") } } class func logRequest(request: NSURLRequest) { if logLevel == .Debug || logLevel == .Verbose { print("[STORMPATH] \(request.HTTPMethod!) \(request.URL!.absoluteString)") if logLevel == .Verbose { print("\(request.allHTTPHeaderFields!)") if let bodyData = request.HTTPBody, bodyString = String.init(data: bodyData, encoding: NSUTF8StringEncoding) { print("\(bodyString)") } } } } class func logResponse(response: NSHTTPURLResponse, data: NSData?) { if logLevel == .Debug || logLevel == .Verbose { print("[STORMPATH] \(response.statusCode) \(response.URL!.absoluteString)") if logLevel == .Verbose { print("\(response.allHeaderFields)") if let data = data { print(String(data: data, encoding: NSUTF8StringEncoding)!) } } } } class func logError(error: NSError) { switch logLevel { case .None: break case .Debug, .Verbose, .Error: print("[STORMPATH][ERROR] \(error.code) \(error.localizedDescription)") print(error.userInfo) } } }
apache-2.0
92aa56c31f419f70a2d8ca84eb5f8d1b
24.156627
126
0.496169
5.080292
false
false
false
false
jmcalister1/iOS-Calculator
ClassCalculator/CalculatorCPU.swift
1
2782
// // CalculatorCPU.swift // ClassCalculator // // Created by Joshua McAlister on 1/24/17. // Copyright © 2017 Harding University. All rights reserved. // import Foundation func divide(op1:Double, op2:Double) -> Double { return op1 / op2 } func multiply(op1:Double, op2:Double) -> Double { return op1 * op2 } func subtract(op1:Double, op2:Double) -> Double { return op1 - op2 } func add(op1:Double, op2:Double) -> Double { return op1 + op2 } class CalculatorCPU { private var accumulator:Double = 0.0 var description:String { get { var result:String = " " if pending != nil { result = String(format: "%f", pending!.firstOperand) } return result } } struct PendingBinaryOperation { var binaryFunction: (Double,Double) -> Double var firstOperand: Double } private var pending: PendingBinaryOperation? private var isPartialResult: Bool { get { return pending != nil } } func setOperand(operand:Double) { accumulator = operand } func performOperation(symbol:String) { switch symbol { case "C": accumulator = 0.0 case "±": accumulator *= -1.0 case "%": accumulator /= 100.0 case "÷": performEquals() pending = PendingBinaryOperation(binaryFunction:divide, firstOperand: accumulator) case "×": performEquals() pending = PendingBinaryOperation(binaryFunction:multiply, firstOperand: accumulator) case "-": performEquals() pending = PendingBinaryOperation(binaryFunction:subtract, firstOperand: accumulator) case "+": performEquals() pending = PendingBinaryOperation(binaryFunction:add, firstOperand: accumulator) case "=": performEquals() case "sin": performEquals() accumulator = sin(accumulator) case "cos": performEquals() accumulator = cos(accumulator) case "tan": performEquals() accumulator = tan(accumulator) case "√": performEquals() accumulator = sqrt(accumulator) case "x²": performEquals() accumulator = pow(accumulator, 2) case "π": accumulator = M_PI default: break } } private func performEquals() { if pending != nil { accumulator = pending!.binaryFunction(pending!.firstOperand, accumulator) pending = nil } } var result:Double { get { return accumulator } } }
mit
544c45549c7985d731c4f187dc676fca
24.218182
96
0.556597
4.662185
false
false
false
false
Alamofire/Alamofire
Tests/TLSEvaluationTests.swift
2
20900
// // TLSEvaluationTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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(Linux) || os(Windows)) import Alamofire import Foundation import XCTest private enum TestCertificates { static let rootCA = TestCertificates.certificate(filename: "expired.badssl.com-root-ca") static let intermediateCA1 = TestCertificates.certificate(filename: "expired.badssl.com-intermediate-ca-1") static let intermediateCA2 = TestCertificates.certificate(filename: "expired.badssl.com-intermediate-ca-2") static let leaf = TestCertificates.certificate(filename: "expired.badssl.com-leaf") static func certificate(filename: String) -> SecCertificate { let filePath = Bundle.test.path(forResource: filename, ofType: "cer")! let data = try! Data(contentsOf: URL(fileURLWithPath: filePath)) let certificate = SecCertificateCreateWithData(nil, data as CFData)! return certificate } } // MARK: - final class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase { private let expiredURLString = "https://expired.badssl.com/" private let expiredHost = "expired.badssl.com" private let revokedURLString = "https://revoked.badssl.com" private let revokedHost = "revoked.badssl.com" private var configuration: URLSessionConfiguration! // MARK: Setup and Teardown override func setUp() { super.setUp() configuration = URLSessionConfiguration.ephemeral configuration.urlCache = nil configuration.urlCredentialStorage = nil } // MARK: Default Behavior Tests func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() { // Given let expectation = self.expectation(description: "\(expiredURLString)") let manager = Session(configuration: configuration) var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error) if let error = error?.underlyingError as? URLError { XCTAssertEqual(error.code, .serverCertificateUntrusted) } else { XCTFail("error should be a URLError or NSError from CFNetwork") } } func disabled_testRevokedCertificateRequestBehaviorWithNoServerTrustPolicy() { // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This // test is left for debugging purposes only. Should not be committed into the test suite while enabled. // Given let expectation = self.expectation(description: "\(revokedURLString)") let manager = Session(configuration: configuration) var error: Error? // When manager.request(revokedURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) { // Apple appears to have started revocation tests as part of default evaluation in 10.1 XCTAssertNotNil(error) } else { XCTAssertNil(error) } } // MARK: Server Trust Policy - Perform Default Tests func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() { // Given let evaluators = [expiredHost: DefaultTrustEvaluator(validateHost: true)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { XCTAssertTrue(reason.isHostValidationFailed, "should be .hostValidationFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } func disabled_testRevokedCertificateRequestBehaviorWithDefaultServerTrustPolicy() { // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This // test is left for debugging purposes only. Should not be committed into the test suite while enabled. // Given let defaultPolicy = DefaultTrustEvaluator() let evaluators = [revokedHost: defaultPolicy] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(revokedURLString)") var error: Error? // When manager.request(revokedURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) { // Apple appears to have started revocation tests as part of default evaluation in 10.1 XCTAssertNotNil(error) } else { XCTAssertNil(error) } } // MARK: Server Trust Policy - Perform Revoked Tests func testThatExpiredCertificateRequestFailsWithRevokedServerTrustPolicy() { // Given let policy = RevocationTrustEvaluator() let evaluators = [expiredHost: policy] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } // watchOS doesn't perform revocation checking at all. #if !os(watchOS) func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() { // Given let policy = RevocationTrustEvaluator() let evaluators = [revokedHost: policy] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(revokedURLString)") var error: AFError? // When manager.request(revokedURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { // Test seems flaky and can result in either of these failures, perhaps due to the OS actually checking? XCTAssertTrue(reason.isDefaultEvaluationFailed || reason.isRevocationCheckFailed, "should be .defaultEvaluationFailed or .revocationCheckFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } #endif // MARK: Server Trust Policy - Certificate Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf] let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf, TestCertificates.intermediateCA1, TestCertificates.intermediateCA2, TestCertificates.rootCA] let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainOrHostValidation() { // Given let certificates = [TestCertificates.leaf] let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, validateHost: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainOrHostValidation() { // Given let certificates = [TestCertificates.intermediateCA2] let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, validateHost: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.rootCA] let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } } // MARK: Server Trust Policy - Public Key Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() { // Given let keys = [TestCertificates.leaf].af.publicKeys let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: AFError? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(error, "error should not be nil") XCTAssertEqual(error?.isServerTrustEvaluationError, true) if case let .serverTrustEvaluationFailed(reason)? = error { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") } else { XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") } } else { XCTFail("error should be .serverTrustEvaluationFailed") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainOrHostValidation() { // Given let keys = [TestCertificates.leaf].af.publicKeys let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainOrHostValidation() { // Given let keys = [TestCertificates.intermediateCA2].af.publicKeys let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() { // Given let keys = [TestCertificates.rootCA].af.publicKeys let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } } // MARK: Server Trust Policy - Disabling Evaluation Tests func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() { // Given let evaluators = [expiredHost: DisabledTrustEvaluator()] let manager = Session(configuration: configuration, serverTrustManager: ServerTrustManager(evaluators: evaluators)) let expectation = self.expectation(description: "\(expiredURLString)") var error: Error? // When manager.request(expiredURLString) .response { resp in error = resp.error expectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(error, "error should be nil") } } #endif
mit
432c5d49884de8c379a3d3958c93f1ac
36.522442
154
0.644402
5.673181
false
true
false
false
googleapis/google-auth-library-swift
Sources/Examples/Spotify/main.swift
1
1777
// Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import OAuth2 let CREDENTIALS = "spotify.json" let TOKEN = "spotify.json" func main() throws { let arguments = CommandLine.arguments if arguments.count == 1 { print("Usage: \(arguments[0]) [options]") return } guard let tokenProvider = BrowserTokenProvider(credentials:CREDENTIALS, token:TOKEN) else { print("Unable to create token provider.") return } let spotify = SpotifySession(tokenProvider:tokenProvider) if arguments[1] == "login" { try tokenProvider.signIn(scopes:["playlist-read-private", "playlist-modify-public", "playlist-modify-private", "user-library-read", "user-library-modify", "user-read-private", "user-read-email"]) try tokenProvider.saveToken(TOKEN) } if arguments[1] == "me" { try spotify.getUser() } if arguments[1] == "tracks" { try spotify.getTracks() } } do { try main() } catch (let error) { print("ERROR: \(error)") }
apache-2.0
2f928e7602ae755e2b5f19e28482723a
28.131148
93
0.612268
4.409429
false
false
false
false
rvanmelle/QuickSettings
Settings.playground/Contents.swift
1
1831
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport import QuickSettings enum Test : String { case Lady case Tramp } enum Speed : String { case Fast case Faster case Fastest } let speedOptions = EnumSettingsOptions<Speed>(defaultValue:.Fastest) let whoOptions = EnumSettingsOptions<Test>(defaultValue:.Lady) let settings = [ Setting.Group(title:"General", children:[ Setting.Toggle(label:"Foo", id:"general.foo", default:true), Setting.Toggle(label:"Bar", id:"general.bar", default:false), Setting.Select(label:"Bar2", id:"general.bar2", options:whoOptions), Setting.Text(label:"Baz", id:"general.baz", default:"Saskatoon"), ]), Setting.Select(label:"How fast?", id:"speed", options:speedOptions), Setting.Group(title:"Extra", children:[ Setting.Toggle(label:"Foo", id:"extra.foo", default:false), Setting.Toggle(label:"Bar", id:"extra.bar", default:true), Setting.Text(label:"Baz", id:"extra.baz", default:"TomTom"), ]) ] class TheDelegate : SettingsViewControllerDelegate { func settingsViewController(vc: SettingsViewController, didUpdateSetting id: String) { print("Update: \(id)") } } var theDelegate = TheDelegate() var defaults = UserDefaults.standard defaults.set("Whhooppeee", forKey: "general.baz") defaults.set("nice", forKey: "extra.baz") defaults.set(true, forKey: "extra.foo") defaults.synchronize() var testit = defaults.value(forKey: "general.baz") var ctrl = SettingsViewController(settings:settings, delegate:theDelegate) let nav = UINavigationController(rootViewController: ctrl) nav.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480) ctrl.title = "Settings Example" ctrl.view.frame = nav.view.frame PlaygroundPage.current.liveView = nav.view
mit
022d6aeb72fd886c0bf79fc31fbea33b
30.033898
90
0.706718
3.759754
false
true
false
false
silence0201/Swift-Study
SwiftLearn/MySwfit15_protocol.playground/Contents.swift
1
8554
//: Playground - noun: a place where people can play import UIKit //=====================================================// //协议就像一个接口. //协议 内可以写属性和方法, //但是方法是不能有大括号及实现, //具体做事的是由实现了协议的具体的类或结构来实现的. //协议也是一种类型, 但是不能用协议去初始化 例: var pet:Pet = Pet() //error //protocol Pet { //宠物 protocol Pet: class { //: class 说明协议只能被类尊守, 结构体不能实现了. //协议只规定了实现有一个属性name, 具体它是计算型属性 还是 存储型属性 协议并不关心. *** var name: String {get set} //属性必须用大括号指定属性是只读, 可写, 或者可读可写 var birthPlace: String{get} //属性是不能有默认值 func playWith() func fed(food: String) //参数是不能有默认值的 //mutating只对结构体有用, 表明结构体尊守协议时这个函数是可以改变自己的. //mutating func changeName(newName: String) func changeName(newName: String) } //定义实现了协议Pet的结构体Dog //struct Dog: Pet{ class Dog: Pet{ /* private var myDoggyName: String //隐藏属性代表了name var name: String{ get{ return myDoggyName } set{ myDoggyName = newValue } } */ var name : String = "Puppy" //存储型属性, 在协议实现中属性可以有默认值. //let birthPlace: String = "Beijing" //因为birthPlace是只读的, 可以直接使用let声明. var birthPlace: String = "Beijing" func playWith() { print("Wong!") } //协议的实现函数中参数就可以有默认值了. func fed(food: String = "Bone"){ if food == "Bone"{ print("Happy") } else{ print("I want a bone") } } //mutating func changeName(newName: String) { func changeName(newName: String) { self.name = newName; } } var myDog : Dog = Dog() myDog.birthPlace = "ChaoYang" myDog.birthPlace = "HaiDian" //虽然协议规定了birthPlace是只读的, 但是myDog是Dog类型的, 所以不受约束. var pet: Pet = myDog //这说明Pet协议也是一种类型 //由于pet是协议Pet类型的, 且birthPlace是只读的属性, 所以不能被整改的. //pet.birthPlace = "ChangPing" //error: birthPlace is a get-only property pet.birthPlace myDog.birthPlace = "BeiJing" pet.birthPlace //由于pet和myDog指向了同一片内存区域, 所以myDog修改了只读属性, pet也被迫更改了. //====协议和构造函数==============================// protocol Pet2{ var name: String{get set} //规定所有实现者<必须>有一个name参数的构造函数. init(name: String) func playWith() func fed() } class Animal{ var type: String = "mammal" } //在Swift中当父类 要在 协议前面. //Dog类的子类同时也尊守Pet2协议 class Dog2: Animal, Pet2{ var name:String = "Puppy" //required标示子类<必须>重写的构造函数. //因为Dog2的子类也同时遵守Pet2协议, 那么就必须加上required关键字, 让Dog2的子类必须实现init(name)函数. required init(name:String){ self.name = name } func playWith() { print("Wong") } func fed(){ print("I love bones") } } class Bird: Animal{ var name:String = "Little Little Bird" init(name:String){ self.name = name } } //鹦鹉 class Parrot: Bird, Pet2{ //init(name)构造函数即是Bird父类所需要的, 同时也是协议Pet2协议所必须实现的. //required是针对协议的, override是针对父类Bird的. required override init(name:String){ super.init(name: name + " " + name) } func playWith() { print("Hello") } func fed(){ print("Thank you!") } } /////////////////////////////////////////////////////////////// //完整的示例 /////////////////////////////////////////////////////////////// protocol Pet5{ var name: String {get set} } protocol Flyable5{ var flySpeed: Double {get} var flyHeight: Double {get} } class Animal5{ } class Dog5: Animal5, Pet5{ var name = "Puppy" } class Cat5: Animal5, Pet5{ var name = "Kitten" } class Bird5: Animal5, Flyable5{ var flySpeed: Double var flyHeight: Double init(flySpeed: Double, flyHeight: Double){ self.flySpeed = flySpeed self.flyHeight = flyHeight } } class Parrot5: Bird5, Pet5{ var name: String init(name: String, flySpeed: Double, flyHeight: Double){ self.name = name + " " + name super.init(flySpeed: flySpeed, flyHeight: flyHeight) } } class Sparrow5: Bird5{ var color = UIColor.gray } class Vehicle5{ } class Plane5: Vehicle5, Flyable5{ var model: String var flySpeed: Double var flyHeight: Double init(model: String, flySpeed: Double, flyHeight: Double){ self.model = model self.flySpeed = flySpeed self.flyHeight = flyHeight } } var dog = Dog5() var cat = Cat5() var parrot = Parrot5(name: "hi", flySpeed: 10.0, flyHeight: 100.0) let pets: [Pet5] = [dog, cat, parrot] for pet in pets{ print(pet.name) } var sparrow = Sparrow5(flySpeed: 15.0, flyHeight: 80.0) var plane = Plane5(model: "Boeing 747", flySpeed: 200.0, flyHeight: 10_000.0) let flyers: [Flyable5] = [parrot, sparrow, plane] for flyer in flyers{ print("Fly speed: " , flyer.flySpeed , "Fly Height: " , flyer.flyHeight) } /*** * typealias 类型别名 */ typealias Lenght = Double extension Double{ var km: Lenght{ return self * 1000.0} var m: Lenght{ return self} var cm: Lenght{ return self/100} var ft: Lenght{ return self/3.28084} } let runningDistance: Lenght = 3.54.km runningDistance typealias AudioSample = UInt64 protocol WeightCalculable{ //associatedtype 和 typealias 语义是一样的 associatedtype WeightType //给协议关联一个类型 var weight: WeightType{ get } } class IPhone7: WeightCalculable{ typealias WeightType = Double //声明协议关联的类型为Double var weight: WeightType{ return 0.114 } } class Ship: WeightCalculable{ typealias WeightType = Int //声明协议关联的类型为Int let weight: WeightType init(weight: Int){ self.weight = weight } } extension Int{ typealias Weight = Int //给Int起一个别名 var t: Weight{ return 1_000*self} //当使用t属性时, 返回Weight别名类型 } let titanic = Ship(weight: 46_328.t) //结构类型实现了协议Equatable后, 必须在结构体外紧跟着 协议的实现, 中间不能有其他语句 struct Record : Equatable, Comparable, CustomStringConvertible{ var wins: Int //赢数 var losses: Int //失败数 var description: String{ //计算型属性 return "WINS: " + String(wins) + ", LOSSES: " + String(losses) } var boolValue: Bool{ return wins > losses //胜数大于败数, 则为赢了true. } } func ==(left: Record, right: Record) -> Bool{ return left.wins == right.wins && left.losses == right.losses } func <(left: Record, right: Record) -> Bool{ if(left.wins != right.wins){ return left.wins < right.wins } return left.losses > right.losses } let recordA = Record(wins: 10, losses: 5) let recordB = Record(wins: 10, losses: 5) //当Record结构体实现了Equatable协议并实现了==操作, 会自动追加了!=操作 recordA != recordB recordA > recordB recordA >= recordB var team1Record = Record(wins: 10, losses: 3) var team2Record = Record(wins: 8, losses: 5) var team3Record = Record(wins: 8, losses: 8) var records = [team1Record, team2Record, team3Record] //系统运行sort()函数时, 是期望其元素是可比较的, 即实现Comparable协议 //当Record结构体没有实现协议Comparable时, 此时sort()是会报错的 records.sort() print(recordA) //调用了CustomStringConvertible协议 if recordA.boolValue{ //这是因为Record类型实现了BooleanType协议, 才可将Record做为一个bool类型使用 print("Great!") } extension Int{ public var boolValue: Bool{ //public是将系统内部功能对外公开 return self != 0 //将Int不等于0时, 表示为true, 等于0时, 返回false } } var wins = 0 if !wins.boolValue{ print("You never win!") }
mit
a34771a19c3198d6759762a3b7dbfa83
20.409639
77
0.622397
3.062473
false
false
false
false
exyte/Macaw
Source/model/draw/ColorMatrix.swift
1
2248
// // ColorMatrix.swift // Macaw // // Created by Yuri Strot on 6/20/18. // Copyright © 2018 Exyte. All rights reserved. // import Foundation open class ColorMatrix { public static let identity = ColorMatrix( values: [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]) public static let luminanceToAlpha = ColorMatrix( values: [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0.2125, 0.7154, 0.0721, 0, 0]) public let values: [Double] public init(values: [Double]) { if values.count != 20 { fatalError("ColorMatrix: wrong matrix count") } self.values = values } public convenience init(color: Color) { self.init(values: [0, 0, 0, 0, Double(color.r()) / 255.0, 0, 0, 0, 0, Double(color.g()) / 255.0, 0, 0, 0, 0, Double(color.b()) / 255.0, 0, 0, 0, Double(color.a()) / 255.0, 0]) } public convenience init(saturate: Double) { let s = max(min(saturate, 1), 0) self.init(values: [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, 0, 0, 0, 1, 0]) } public convenience init(hueRotate: Double) { let c = cos(hueRotate) let s = sin(hueRotate) let m1 = [0.213, 0.715, 0.072, 0.213, 0.715, 0.072, 0.213, 0.715, 0.072] let m2 = [0.787, -0.715, -0.072, -0.213, 0.285, -0.072, -0.213, -0.715, 0.928] let m3 = [-0.213, -0.715, 0.928, 0.143, 0.140, -0.283, -0.787, 0.715, 0.072] let a = { (i: Int) -> Double in m1[i] + c * m2[i] + s * m3[i] } self.init(values: [a(0), a(1), a(2), 0, 0, a(3), a(4), a(5), 0, 0, a(6), a(7), a(8), 0, 0, 0, 0, 0, 1, 0]) } }
mit
7ca7f999844f826cbabf42f201ae0953
31.565217
89
0.40721
2.980106
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/BackupPage/BackupViewController.swift
1
13964
// // BackupViewController.swift // GogoroMap // // Created by 陳 冠禎 on 02/11/2017. // Copyright © 2017 陳 冠禎. All rights reserved. // import UIKit import CloudKit import GoogleMobileAds import Crashlytics extension BackupViewController: ADSupportable { func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("Google Ad error: \(error)") } func adViewDidReceiveAd(_ bannerView: GADBannerView) { didReceiveAd(bannerView) } } final class BackupViewController: UITableViewController { var bannerView = GADBannerView(adSize: GADAdSizeFromCGSize(CGSize(width: UIScreen.main.bounds.width, height: 50))) weak var stations: StationDataSource? let adUnitID: String = Keys.standard.backupAdUnitID private let backupHeadView = SupplementaryCell(title: "資料備份", subtitle: "建立一份備份資料,當機器損壞或遺失時,可以從iCloud回復舊有資料") private let restoreHeadView = SupplementaryCell(title: "資料還原", subtitle: "從iCloud中選擇您要還原的備份資料的時間點以還原舊有資料") private let backupfooterView = SupplementaryCell(title: "目前沒有登入的iCloud帳號", subtitle: "最後更新日: \(UserDefaults.standard.string(forKey: Keys.standard.nowDateKey) ?? "")", titleTextAlignment: .center) private let backupCell = BackupTableViewCell(type: .none, title: "立即備份", titleColor: .gray) private let deleteCell = BackupTableViewCell(type: .none, title: "刪除全部的備份資料", titleColor: .red) private let noDataCell = BackupTableViewCell(type: .none, title: "暫無資料", titleColor: .lightGray) private lazy var backupElement = BackupElement(titleView: backupHeadView, cells: [backupCell], footView: backupfooterView, type: .backup) private lazy var restoreElement = BackupElement(titleView: restoreHeadView, cells: [noDataCell], footView: SupplementaryCell(), type: .delete) private lazy var elements: [BackupElement] = [backupElement, restoreElement] var cloudAccountStatus = CKAccountStatus.noAccount { didSet { DispatchQueue.main.async(execute: checkAccountStatus) } } private func checkAccountStatus() { backupCell.isUserInteractionEnabled = cloudAccountStatus == .available deleteCell.isUserInteractionEnabled = cloudAccountStatus == .available backupCell.titleLabel.textColor = cloudAccountStatus == .available ? .grassGreen : .gray deleteCell.titleLabel.textColor = cloudAccountStatus == .available ? .red : .gray switch cloudAccountStatus { case .available: CKContainer.default().fetchUserID { self.backupfooterView.titleLabel.text = $0 } default: backupfooterView.titleLabel.text = "目前沒有登入的iCloud帳號" backupfooterView.subtitleLabel.text = "無法取得最後更新日" elements[1].cells = [noDataCell] } backupfooterView.subtitleLabel.text = cloudAccountStatus.description tableView.reloadData() } var records: [CKRecord]? { didSet { records?.sort { $0.creationDate > $1.creationDate } let dataSize = records?.reduce(0) { $0 + (($1.value(forKey: "batteryStationPointAnnotation") as? Data)?.count ?? 0) } DispatchQueue.main.async { let subtitleText: String? if let records = self.records, let date = records.first?.creationDate?.string(dateformat: "yyyy.MM.dd hh:mm:ss") { self.elements[1].cells = records .compactMap { (($0.value(forKey: "batteryStationPointAnnotation") as? Data), $0.creationDate?.string(dateformat: "yyyy.MM.dd HH:mm:ss")) } .enumerated() .compactMap { (index, element) in guard let data = element.0, let batteryRecords = try? JSONDecoder().decode([BatteryStationRecord].self, from: data) else { return nil } let size = BackupTableViewCell.byteCountFormatter.string(fromByteCount: Int64(data.count)) return BackupTableViewCell(title: "\(index + 1). 上傳時間: \(element.1 ?? "")", subtitle: "檔案容量: \(size), 打卡次數:\(batteryRecords.reduce(0) { $0 + $1.checkinCount })" , stationRecords: batteryRecords) } + [self.deleteCell] subtitleText = "最新備份時間:\(date)" } else { self.elements[1].cells = [self.noDataCell] subtitleText = nil } if let dataSize = dataSize { self.elements[1].footView?.titleLabel.text = "iCloud 已使用儲存容量:" + BackupTableViewCell.byteCountFormatter.string(fromByteCount: Int64(dataSize)) } self.backupfooterView.subtitleLabel.text = subtitleText self.tableView.reloadData() } } } override func loadView() { super.loadView() checkTheCloudAccountStatus() navigationController?.navigationBar.tintColor = .white } override func viewDidLoad() { super.viewDidLoad() Answers.log(view: "backup page") setupObserve() setupAd(with: view) tableView.delegate = self tableView.dataSource = self tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) tableView.allowsSelection = true tableView.allowsMultipleSelection = false navigationItem.title = "資料更新中..." CKContainer.default().fetchData { (records, error) in self.records = records self.navigationItem.title = error == nil ? "備份與還原" : "發生錯誤,請稍後嘗試" self.backupCell.isUserInteractionEnabled = error == nil DispatchQueue.main.async(execute: self.tableView.reloadData) } } deinit { NotificationCenter.default.removeObserver(self) } } //MARK: - UITableView extension BackupViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return elements[section].cells?.count ?? 0 } override func numberOfSections(in tableView: UITableView) -> Int { return elements.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return elements[indexPath.section].cells?[indexPath.row] ?? BackupTableViewCell(type: .none) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } guard cloudAccountStatus == .available else { return } let cell = elements[indexPath.section].cells?[indexPath.row] switch (cell?.cellType, elements[indexPath.section].type) { case (.none?, .backup): cell?.isUserInteractionEnabled = false cell?.titleLabel.text = "資料備份中..." guard let stations = stations?.batteryStationPointAnnotations, let data = try? JSONEncoder().encode(stations.compactMap(BatteryStationRecord.init)) else { return } CKContainer.default().save(data: data) { (newRecord, error) in cell?.isUserInteractionEnabled = true cell?.titleLabel.text = "立即備份" guard let newRecord = newRecord else { return } switch self.records { case .none: self.records = [newRecord] case let records?: self.records = records + [newRecord] } } case (.none?, .delete): let alertController = UIAlertController(title: "要刪除所有備份資料?", message: "所有備份資料將從iPhone及iCloud刪除,無法復原。", preferredStyle: .actionSheet) [ UIAlertAction(title: "刪除", style: .destructive, handler : { _ in self.elements[indexPath.section].cells?.forEach { guard $0.cellType == .backupButton else { return } $0.titleLabel.text = "備份資料刪除中..." $0.subtitleLabel.text = nil } self.records?.forEach { CKContainer.default().privateCloudDatabase.delete(withRecordID: $0.recordID) { (recordID, error) in guard error == nil, let recordID = recordID, let index = self.records?.map({ $0.recordID }).firstIndex(of: recordID) else { return } self.records?.remove(at: index) } }}), UIAlertAction(title: "取消", style: .cancel, handler: nil), ].forEach(alertController.addAction) self.present(alertController, animated: true) case (.backupButton?, _): let alertController = UIAlertController(title: "要使用此資料?", message: "當前地圖資訊將被備份資料取代", preferredStyle: .actionSheet) [ UIAlertAction(title: "使用", style: .destructive, handler : { _ in DataManager.shared.fetchStations{ (result) in NetworkActivityIndicatorManager.shared.networkOperationStarted() self.navigationItem.title = "資料覆蓋中..." guard case .success(let stations) = result, let stationRecords = self.elements[1].cells?[indexPath.row].stationRecords else { return } stationRecords.forEach { for station in stations where $0.id == station.coordinate { (station.checkinDay, station.checkinCounter) = ($0.checkinDay, $0.checkinCount) return } } NetworkActivityIndicatorManager.shared.networkOperationFinished() self.navigationItem.title = "備份與還原" self.stations?.batteryStationPointAnnotations = stations } }), UIAlertAction(title: "取消", style: .cancel, handler: nil), ].forEach(alertController.addAction) present(alertController, animated: true) default: break } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return elements[indexPath.section].cells?[indexPath.row].cellType == .some(.backupButton) } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .destructive, title: "刪除") { (action, indexPath) in let alertController = UIAlertController(title: "要刪除資料?", message: "此筆資料將從iPhone及iCloud刪除,無法復原。", preferredStyle: .actionSheet) [ UIAlertAction(title: "刪除", style: .destructive, handler : { _ in guard let record = self.records?[indexPath.row] else { return } self.elements[indexPath.section].cells?[indexPath.row].titleLabel.text = "資料刪除中..." self.elements[indexPath.section].cells?[indexPath.row].subtitleLabel.text = nil CKContainer.default().privateCloudDatabase.delete(withRecordID: record.recordID) { (recordID, error) in guard error == nil, let recordID = recordID, let index = self.records?.map({ $0.recordID }).firstIndex(of: recordID) else { return } self.records?.remove(at: index) } }), UIAlertAction(title: "取消", style: .cancel, handler: nil), ].forEach(alertController.addAction) self.present(alertController, animated: true) } return [delete] } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return elements[section].titleView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 100 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return elements[section].footView } } extension BackupViewController { private func setupObserve() { NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(checkTheCloudAccountStatus), name: .CKAccountChanged, object: nil) } @objc private func checkTheCloudAccountStatus() { CKContainer.default().accountStatus { (status, _) in self.cloudAccountStatus = status } } }
mit
638892d0c08a41a95a742cd7751af923
46.049123
199
0.595794
4.809541
false
false
false
false
czechboy0/Buildasaur
BuildaKit/BuildTemplate.swift
2
5063
// // BuildTemplate.swift // Buildasaur // // Created by Honza Dvorsky on 09/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils import XcodeServerSDK private let kKeyId = "id" private let kKeyProjectName = "project_name" private let kKeyName = "name" private let kKeyScheme = "scheme" private let kKeySchedule = "schedule" private let kKeyCleaningPolicy = "cleaning_policy" private let kKeyTriggers = "triggers" private let kKeyTestingDevices = "testing_devices" private let kKeyDeviceFilter = "device_filter" private let kKeyPlatformType = "platform_type" private let kKeyShouldAnalyze = "should_analyze" private let kKeyShouldTest = "should_test" private let kKeyShouldArchive = "should_archive" public struct BuildTemplate: JSONSerializable { public let id: RefType public var projectName: String? public var name: String public var scheme: String public var schedule: BotSchedule public var cleaningPolicy: BotConfiguration.CleaningPolicy public var triggers: [RefType] public var shouldAnalyze: Bool public var shouldTest: Bool public var shouldArchive: Bool public var testingDeviceIds: [String] public var deviceFilter: DeviceFilter.FilterType public var platformType: DevicePlatform.PlatformType? func validate() -> Bool { if self.id.isEmpty { return false } //TODO: add all the other required values! this will be called on saving from the UI to make sure we have all the required fields. return true } public init(projectName: String? = nil) { self.id = Ref.new() self.projectName = projectName self.name = "" self.scheme = "" self.schedule = BotSchedule.manualBotSchedule() self.cleaningPolicy = BotConfiguration.CleaningPolicy.Never self.triggers = [] self.shouldAnalyze = true self.shouldTest = true self.shouldArchive = false self.testingDeviceIds = [] self.deviceFilter = .AllAvailableDevicesAndSimulators self.platformType = nil } public init(json: NSDictionary) throws { self.id = json.optionalStringForKey(kKeyId) ?? Ref.new() self.projectName = json.optionalStringForKey(kKeyProjectName) self.name = try json.stringForKey(kKeyName) self.scheme = try json.stringForKey(kKeyScheme) if let scheduleDict = json.optionalDictionaryForKey(kKeySchedule) { self.schedule = try BotSchedule(json: scheduleDict) } else { self.schedule = BotSchedule.manualBotSchedule() } if let cleaningPolicy = json.optionalIntForKey(kKeyCleaningPolicy), let policy = BotConfiguration.CleaningPolicy(rawValue: cleaningPolicy) { self.cleaningPolicy = policy } else { self.cleaningPolicy = BotConfiguration.CleaningPolicy.Never } if let array = (json.optionalArrayForKey(kKeyTriggers) as? [RefType]) { self.triggers = array } else { self.triggers = [] } self.shouldAnalyze = try json.boolForKey(kKeyShouldAnalyze) self.shouldTest = try json.boolForKey(kKeyShouldTest) self.shouldArchive = try json.boolForKey(kKeyShouldArchive) self.testingDeviceIds = json.optionalArrayForKey(kKeyTestingDevices) as? [String] ?? [] if let deviceFilterInt = json.optionalIntForKey(kKeyDeviceFilter), let deviceFilter = DeviceFilter.FilterType(rawValue: deviceFilterInt) { self.deviceFilter = deviceFilter } else { self.deviceFilter = .AllAvailableDevicesAndSimulators } if let platformTypeString = json.optionalStringForKey(kKeyPlatformType), let platformType = DevicePlatform.PlatformType(rawValue: platformTypeString) { self.platformType = platformType } else { self.platformType = nil } if !self.validate() { throw Error.withInfo("Invalid input into Build Template") } } public func jsonify() -> NSDictionary { let dict = NSMutableDictionary() dict[kKeyId] = self.id dict[kKeyTriggers] = self.triggers dict[kKeyDeviceFilter] = self.deviceFilter.rawValue dict[kKeyTestingDevices] = self.testingDeviceIds ?? [] dict[kKeyCleaningPolicy] = self.cleaningPolicy.rawValue dict[kKeyName] = self.name dict[kKeyScheme] = self.scheme dict[kKeyShouldAnalyze] = self.shouldAnalyze dict[kKeyShouldTest] = self.shouldTest dict[kKeyShouldArchive] = self.shouldArchive dict[kKeySchedule] = self.schedule.dictionarify() dict.optionallyAddValueForKey(self.projectName, key: kKeyProjectName) dict.optionallyAddValueForKey(self.platformType?.rawValue, key: kKeyPlatformType) return dict } }
mit
5e8d9bcfd8478e5014bd2829cbbc7e4c
35.688406
138
0.664231
4.674977
false
true
false
false
P0ed/SWLABR
SWLABR/GamepadKit/HIDController.swift
1
3374
import Foundation import GameController import Combine final class HIDController { private var current: GCController? = GCController.controllers().first { didSet { if let some = current { setupController(some) } } } private var observers: [Any] = [] @IO private var controls = Controls() let eventsController = EventsController() init() { observers = [ NotificationCenter.default.publisher(for: .GCControllerDidBecomeCurrent).sink { [weak self] in self?.current = $0.object as? GCController }, NotificationCenter.default.publisher(for: .GCControllerDidStopBeingCurrent).sink { [weak self] _ in self?.current = nil } ] } private func setupController(_ controller: GCController) { guard let gamepad = controller.extendedGamepad else { return } _controls.value = Controls() gamepad.leftThumbstick.valueChangedHandler = { [_controls, eventsController] _, x, y in _controls.value.leftStick = Controls.Thumbstick(x: x, y: y) eventsController.handleLeftThumbstick(Controls.Thumbstick(x: x, y: y)) } gamepad.rightThumbstick.valueChangedHandler = { [_controls, eventsController] _, x, y in _controls.value.rightStick = Controls.Thumbstick(x: x, y: y) eventsController.handleRightThumbstick(Controls.Thumbstick(x: x, y: y)) } gamepad.leftTrigger.valueChangedHandler = { [_controls, eventsController] _, value, _ in _controls.value.leftTrigger = value eventsController.handleLeftTrigger(value) } gamepad.rightTrigger.valueChangedHandler = { [_controls, eventsController] _, value, _ in _controls.value.rightTrigger = value eventsController.handleRightTrigger(value) } let mapControl: (GCControllerButtonInput, Controls.Buttons) -> Void = { [_controls, eventsController] button, control in button.valueChangedHandler = { _, _, pressed in _controls.modify { if pressed { $0.buttons.insert(control) } else { $0.buttons.remove(control) } } eventsController.handleButton(control, isPressed: pressed) } } mapControl(gamepad.buttonA, .cross) mapControl(gamepad.buttonB, .circle) mapControl(gamepad.dpad.up, .up) mapControl(gamepad.dpad.down, .down) mapControl(gamepad.dpad.left, .left) mapControl(gamepad.dpad.right, .right) mapControl(gamepad.leftShoulder, .shiftLeft) mapControl(gamepad.rightShoulder, .shiftRight) mapControl(gamepad.buttonX, .square) mapControl(gamepad.buttonY, .triangle) mapControl(gamepad.buttonMenu, .scan) } } struct Controls { var leftStick = Thumbstick.zero var rightStick = Thumbstick.zero var leftTrigger = 0 as Float var rightTrigger = 0 as Float var buttons = [] as Buttons struct Buttons: OptionSet, Hashable { var rawValue: Int16 = 0 static let up = Buttons(rawValue: 1 << 0) static let down = Buttons(rawValue: 1 << 1) static let left = Buttons(rawValue: 1 << 2) static let right = Buttons(rawValue: 1 << 3) static let shiftLeft = Buttons(rawValue: 1 << 4) static let shiftRight = Buttons(rawValue: 1 << 5) static let cross = Buttons(rawValue: 1 << 6) static let circle = Buttons(rawValue: 1 << 7) static let square = Buttons(rawValue: 1 << 8) static let triangle = Buttons(rawValue: 1 << 9) static let scan = Buttons(rawValue: 1 << 10) static let dPad = Buttons([.up, .down, .left, .right]) } struct Thumbstick { var x: Float var y: Float static let zero = Thumbstick(x: 0, y: 0) } }
mit
ce905fd467fd41cb9ffc640d5fbd4ce5
33.428571
122
0.719028
3.411527
false
false
false
false
gouyz/GYZBaking
baking/Pods/SKPhotoBrowser/SKPhotoBrowser/SKAnimator.swift
4
7084
// // SKAnimator.swift // SKPhotoBrowser // // Created by keishi suzuki on 2016/08/09. // Copyright © 2016 suzuki_keishi. All rights reserved. // import UIKit @objc public protocol SKPhotoBrowserAnimatorDelegate { func willPresent(_ browser: SKPhotoBrowser) func willDismiss(_ browser: SKPhotoBrowser) } class SKAnimator: NSObject, SKPhotoBrowserAnimatorDelegate { var resizableImageView: UIImageView? var senderOriginImage: UIImage! var senderViewOriginalFrame: CGRect = .zero var senderViewForAnimation: UIView? var finalImageViewFrame: CGRect = .zero var bounceAnimation: Bool = false var animationDuration: TimeInterval { if SKPhotoBrowserOptions.bounceAnimation { return 0.5 } return 0.35 } var animationDamping: CGFloat { if SKPhotoBrowserOptions.bounceAnimation { return 0.8 } return 1 } func willPresent(_ browser: SKPhotoBrowser) { guard let appWindow = UIApplication.shared.delegate?.window else { return } guard let window = appWindow else { return } guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.initialPageIndex) ?? senderViewForAnimation else { presentAnimation(browser) return } let photo = browser.photoAtIndex(browser.currentPageIndex) let imageFromView = (senderOriginImage ?? browser.getImageFromView(sender)).rotateImageByOrientation() let imageRatio = imageFromView.size.width / imageFromView.size.height senderViewOriginalFrame = calcOriginFrame(sender) finalImageViewFrame = calcFinalFrame(imageRatio) resizableImageView = UIImageView(image: imageFromView) resizableImageView!.frame = senderViewOriginalFrame resizableImageView!.clipsToBounds = true resizableImageView!.contentMode = photo.contentMode if sender.layer.cornerRadius != 0 { let duration = (animationDuration * Double(animationDamping)) resizableImageView!.layer.masksToBounds = true resizableImageView!.addCornerRadiusAnimation(sender.layer.cornerRadius, to: 0, duration: duration) } window.addSubview(resizableImageView!) presentAnimation(browser) } func willDismiss(_ browser: SKPhotoBrowser) { guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.currentPageIndex), let image = browser.photoAtIndex(browser.currentPageIndex).underlyingImage, let scrollView = browser.pageDisplayedAtIndex(browser.currentPageIndex) else { senderViewForAnimation?.isHidden = false browser.dismissPhotoBrowser(animated: false) return } senderViewForAnimation = sender browser.view.isHidden = true browser.backgroundView.isHidden = false browser.backgroundView.alpha = 1 senderViewOriginalFrame = calcOriginFrame(sender) let photo = browser.photoAtIndex(browser.currentPageIndex) let contentOffset = scrollView.contentOffset let scrollFrame = scrollView.photoImageView.frame let offsetY = scrollView.center.y - (scrollView.bounds.height/2) let frame = CGRect( x: scrollFrame.origin.x - contentOffset.x, y: scrollFrame.origin.y + contentOffset.y + offsetY, width: scrollFrame.width, height: scrollFrame.height) // resizableImageView.image = scrollView.photo?.underlyingImage?.rotateImageByOrientation() resizableImageView!.image = image.rotateImageByOrientation() resizableImageView!.frame = frame resizableImageView!.alpha = 1.0 resizableImageView!.clipsToBounds = true resizableImageView!.contentMode = photo.contentMode if let view = senderViewForAnimation , view.layer.cornerRadius != 0 { let duration = (animationDuration * Double(animationDamping)) resizableImageView!.layer.masksToBounds = true resizableImageView!.addCornerRadiusAnimation(0, to: view.layer.cornerRadius, duration: duration) } dismissAnimation(browser) } } private extension SKAnimator { func calcOriginFrame(_ sender: UIView) -> CGRect { if let senderViewOriginalFrameTemp = sender.superview?.convert(sender.frame, to:nil) { return senderViewOriginalFrameTemp } else if let senderViewOriginalFrameTemp = sender.layer.superlayer?.convert(sender.frame, to: nil) { return senderViewOriginalFrameTemp } else { return .zero } } func calcFinalFrame(_ imageRatio: CGFloat) -> CGRect { if SKMesurement.screenRatio < imageRatio { let width = SKMesurement.screenWidth let height = width / imageRatio let yOffset = (SKMesurement.screenHeight - height) / 2 return CGRect(x: 0, y: yOffset, width: width, height: height) } else { let height = SKMesurement.screenHeight let width = height * imageRatio let xOffset = (SKMesurement.screenWidth - width) / 2 return CGRect(x: xOffset, y: 0, width: width, height: height) } } } private extension SKAnimator { func presentAnimation(_ browser: SKPhotoBrowser, completion: ((Void) -> Void)? = nil) { browser.view.isHidden = true browser.view.alpha = 0.0 UIView.animate( withDuration: animationDuration, delay: 0, usingSpringWithDamping:animationDamping, initialSpringVelocity:0, options:UIViewAnimationOptions(), animations: { browser.showButtons() browser.backgroundView.alpha = 1.0 self.resizableImageView?.frame = self.finalImageViewFrame }, completion: { (Bool) -> Void in browser.view.isHidden = false browser.view.alpha = 1.0 browser.backgroundView.isHidden = true self.resizableImageView?.alpha = 0.0 }) } func dismissAnimation(_ browser: SKPhotoBrowser, completion: ((Void) -> Void)? = nil) { UIView.animate( withDuration: animationDuration, delay:0, usingSpringWithDamping:animationDamping, initialSpringVelocity:0, options:UIViewAnimationOptions(), animations: { browser.backgroundView.alpha = 0.0 self.resizableImageView?.layer.frame = self.senderViewOriginalFrame }, completion: { (Bool) -> () in browser.dismissPhotoBrowser(animated: true) { self.resizableImageView?.removeFromSuperview() } }) } }
mit
b1cc640f5d9f1cd8b440bf1ed9a67fb2
36.877005
133
0.628406
5.325564
false
false
false
false
majinyu888/SwiftDemo
SwiftDemo/SwiftDemo/Sections/CATransform 3D/CATransform3DController.swift
1
4915
// // CATransform3DDemo.swift // SwiftDemo // // Created by hb on 2017/6/22. // Copyright © 2017年 com.bm.hb. All rights reserved. // /** ********************** 注意 ************************ 地址:http://www.cocoachina.com/swift/20170518/19305.html CATransform3D 是采用三维坐标系统, x 轴向下为正, y 向右为正, z 轴则是垂直于屏幕向外为正。 ********************** 注意 ************************ */ import UIKit class CATransform3DController: UIViewController { //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.addDice() let handle = #selector(viewTransform(sender:)) let pan = UIPanGestureRecognizer(target: self, action: handle) self.diceView.addGestureRecognizer(pan) } //MARK: - IB //MARK: - Private Propertys fileprivate var angle = CGPoint(x: 0, y: 0) fileprivate let diceView = UIView() //MARK: - Private Methods func addDice() { let viewFrame = UIScreen.main.bounds var diceTransform = CATransform3DIdentity diceView.frame = CGRect(x: 0, y: viewFrame.maxY / 2 - 50, width: viewFrame.width, height: 100) //1 let dice1 = UIImageView.init(image: UIImage(named: "dice1")) dice1.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DTranslate(diceTransform, 0, 0, 50) dice1.layer.transform = diceTransform //6 let dice6 = UIImageView.init(image: UIImage(named: "dice6")) dice6.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 0, -50) dice6.layer.transform = diceTransform //2 let dice2 = UIImageView.init(image: UIImage(named: "dice2")) dice2.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DRotate(CATransform3DIdentity, (CGFloat.pi / 2), 0, 1, 0) diceTransform = CATransform3DTranslate(diceTransform, 0, 0, 50) dice2.layer.transform = diceTransform //5 let dice5 = UIImageView.init(image: UIImage(named: "dice5")) dice5.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DRotate(CATransform3DIdentity, (-CGFloat.pi / 2), 0, 1, 0) diceTransform = CATransform3DTranslate(diceTransform, 0, 0, 50) dice5.layer.transform = diceTransform //3 let dice3 = UIImageView.init(image: UIImage(named: "dice3")) dice3.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DRotate(CATransform3DIdentity, (-CGFloat.pi / 2), 1, 0, 0) diceTransform = CATransform3DTranslate(diceTransform, 0, 0, 50) dice3.layer.transform = diceTransform //4 let dice4 = UIImageView.init(image: UIImage(named: "dice4")) dice4.frame = CGRect(x: viewFrame.maxX / 2 - 50, y: 0, width: 100, height: 100) diceTransform = CATransform3DRotate(CATransform3DIdentity, (CGFloat.pi / 2), 1, 0, 0) diceTransform = CATransform3DTranslate(diceTransform, 0, 0, 50) dice4.layer.transform = diceTransform diceView.addSubview(dice1) diceView.addSubview(dice2) diceView.addSubview(dice3) diceView.addSubview(dice4) diceView.addSubview(dice5) diceView.addSubview(dice6) view.addSubview(diceView) } @objc private func viewTransform(sender: UIPanGestureRecognizer) { let point = sender.translation(in: self.diceView) let angleX = self.angle.x + (point.x / 30) let angleY = self.angle.y - (point.y / 30) var transform = CATransform3DIdentity /** 在真实世界中, 当物体远离我们时, 由于视角的关系会看起来变小, 理论上来说, 比较远的边会比近的边要短, 但是实际上对系统来说他们是一样长的, 所以我们要做一些修正。 透过设置 CATransform3D 的 m34 为 -1.0 / d 来让影像有远近的 3D 效果, d 代表了想象中视角与屏幕的距离, 这个距离只需要大概估算, 不需要很精准的计算。 */ transform.m34 = -1 / 500 transform = CATransform3DRotate(transform, angleX, 0, 1, 0) transform = CATransform3DRotate(transform, angleY, 1, 0, 0) self.diceView.layer.sublayerTransform = transform if sender.state == .ended { self.angle.x = angleX self.angle.y = angleY } } }
mit
a7207ddf41786a7a7766b4038fad07a8
33.606061
102
0.595009
3.698785
false
false
false
false
tjw/swift
stdlib/public/core/Indices.swift
2
4126
//===----------------------------------------------------------------------===// // // 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 collection of indices for an arbitrary collection @_fixed_layout public struct DefaultIndices<Elements: Collection> { @usableFromInline internal var _elements: Elements @usableFromInline internal var _startIndex: Elements.Index @usableFromInline internal var _endIndex: Elements.Index @inlinable internal init( _elements: Elements, startIndex: Elements.Index, endIndex: Elements.Index ) { self._elements = _elements self._startIndex = startIndex self._endIndex = endIndex } } extension DefaultIndices: Collection { public typealias Index = Elements.Index public typealias Element = Elements.Index public typealias Indices = DefaultIndices<Elements> public typealias SubSequence = DefaultIndices<Elements> public typealias Iterator = IndexingIterator<DefaultIndices<Elements>> @inlinable public var startIndex: Index { return _startIndex } @inlinable public var endIndex: Index { return _endIndex } @inlinable public subscript(i: Index) -> Elements.Index { // FIXME: swift-3-indexing-model: range check. return i } @inlinable public subscript(bounds: Range<Index>) -> DefaultIndices<Elements> { // FIXME: swift-3-indexing-model: range check. return DefaultIndices( _elements: _elements, startIndex: bounds.lowerBound, endIndex: bounds.upperBound) } @inlinable public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(after: i) } @inlinable public func formIndex(after i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(after: &i) } @inlinable public var indices: Indices { return self } } extension DefaultIndices: BidirectionalCollection where Elements: BidirectionalCollection { @inlinable public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(before: i) } @inlinable public func formIndex(before i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(before: &i) } } extension DefaultIndices: RandomAccessCollection where Elements: RandomAccessCollection { } extension Collection where Indices == DefaultIndices<Self> { /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) @inlinable // FIXME(sil-serialize-all) public var indices: DefaultIndices<Self> { return DefaultIndices( _elements: self, startIndex: self.startIndex, endIndex: self.endIndex) } } @available(*, deprecated, renamed: "DefaultIndices") public typealias DefaultBidirectionalIndices<T> = DefaultIndices<T> where T : BidirectionalCollection @available(*, deprecated, renamed: "DefaultIndices") public typealias DefaultRandomAccessIndices<T> = DefaultIndices<T> where T : RandomAccessCollection
apache-2.0
6620acce64432dc2354c0da097b2ca52
29.791045
101
0.677169
4.479913
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/Contacts/ContactsController/View/CWContactHeaderView.swift
2
943
// // CWContactHeaderView.swift // CWWeChat // // Created by wei chen on 2017/4/3. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit class CWContactHeaderView: UITableViewHeaderFooterView { //title lazy var titleLabel:UILabel = { let titleLabel = UILabel() titleLabel.textColor = UIColor(hex: "#8E8E93") titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.numberOfLines = 0 return titleLabel }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.contentView.addSubview(titleLabel) p_addSnap() } func p_addSnap() { self.titleLabel.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsMake(0, 10, 0, 10)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
6587345840a944b412732f7069b88f88
23.736842
62
0.630851
4.272727
false
false
false
false
Vinelab/socialite-ios
Socialite.swift
1
14749
// // SLTSocial.swift // testSocialLogins // // Created by Ibrahim Kteish on 10/28/15. // Copyright © 2015 Ibrahim Kteish. All rights reserved. // import Foundation import FBSDKLoginKit import FBSDKShareKit //FB login App Events and Notifications struct SLTAppEventsAndNotifications { //Events static let SLTAppEventNameFBLoginButtonDidTap = "SLTAppEventNameFBLoginButtonDidTap" static let SLTAppEventNameFBLoginDidSuccess = "SLTAppEventNameFBLoginDidSuccess" static let SLTAppEventNameFBLoginDidCancel = "SLTAppEventNameFBLoginDidCancel" static let SLTAppEventNameFBLoginDidLogout = "SLTAppEventNameFBLoginDidLogout" static let SLTAppEventNameFBLoginDidFail = "SLTAppEventNameFBLoginDidFail" //Notifications static let SLTAppNotificationNameUserStateHasChangedNotification = "SLTAppNotificationNameUserStateHasChangedNotification" } //Social Internals Utilities private struct SLTInternals : SLTFacebookPermission { ///Facebook permissions static var facebookReadPermissions : [String] = { return ["public_profile"] }() //Providers name static let facebookProviderName = "facebook" static let twitterProviderName = "twitter" static let providerNameKey = "providerName" static let UserStateKey = "State" ///Attempts to find the first UIViewController in the view's responder chain. Returns nil if not found. static func viewControllerforView(view:UIView) -> UIViewController? { var responder :UIResponder? = view.nextResponder() repeat { if let unWrappedResponder = responder { if unWrappedResponder is UIViewController { return unWrappedResponder as? UIViewController } responder = unWrappedResponder.nextResponder() } } while (responder != nil ) return nil } }//End //SLTProvider's Delegate protocol SLTLoginDelegate { ///Indicates a successful login /// - Parameters: /// - credentials: an object contains the id and token for the requested social medium. func userDidLogin(credentials:SLTLoginCredentials) ///Logs the user out. func userDidLogout() ///Indicates that the user cancelled the Login. func userDidCancelLogin() ///Indicates that the login failed /// - Parameters: /// - error: The error object returned by the SDK func userLoginFailed(error:NSError) } protocol SLTFacebookPermission { static var facebookReadPermissions : [String] { get } } protocol SLTProviderName { var providerName : String { get } } struct SLTFacebookProvider { //Properties let facebookManager = FBSDKLoginManager() var delegate : SLTLoginDelegate? //Computed Properties var isUserLoggedIn : Bool { get { return FBSDKAccessToken.currentAccessToken() != nil } } //Facebook ///Logs the user in or authorizes additional permissions, the permissions exist in SLTSocialInternals Struct /// - Parameters: /// - button: a reference for the button/View that will trigger this method in order to get its ViewController /// - helper: an object that implements `SLTFacebookPermission` protocol func login(button:UIView, helper:SLTFacebookPermission = SLTInternals()) { if self.isUserLoggedIn { let currentToken = FBSDKAccessToken.currentAccessToken() userDidLogin(currentToken) return } self.logTapEventWithEventName(SLTAppEventsAndNotifications.SLTAppEventNameFBLoginButtonDidTap, parameters: nil) let handler : FBSDKLoginManagerRequestTokenHandler = { (result, error) -> Void in if error != nil { self.logTapEventWithEventName(SLTAppEventsAndNotifications.SLTAppEventNameFBLoginDidFail, parameters: nil) self.delegate?.userLoginFailed(error) } else if result.isCancelled { self.delegate?.userDidCancelLogin() self.logTapEventWithEventName(SLTAppEventsAndNotifications.SLTAppEventNameFBLoginDidCancel, parameters: nil) } else { self.userDidLogin(result.token) } } facebookManager.logInWithReadPermissions(helper.dynamicType.facebookReadPermissions, fromViewController: SLTInternals.viewControllerforView(button), handler: handler) } ///Logs the user out func logout() { facebookManager.logOut() self.delegate?.userDidLogout() logTapEventWithEventName(SLTAppEventsAndNotifications.SLTAppEventNameFBLoginDidLogout, parameters: nil) postNotification() } ///Login/Logout Notification func postNotification() { NSNotificationCenter.defaultCenter().postNotificationName(SLTAppEventsAndNotifications.SLTAppNotificationNameUserStateHasChangedNotification, object: [SLTInternals.providerNameKey : self.providerName,SLTInternals.UserStateKey: self.isUserLoggedIn] ) } /// Helper method it will be called after a successful login /// - Parameters: /// - token: the `FBSDKAccessToken` token from `FBSDKLoginManagerLoginResult` func userDidLogin(token: FBSDKAccessToken) { self.delegate?.userDidLogin(SLTFacebookLoginCredentials(userID: token.userID, userToken: token.tokenString)) self.logTapEventWithEventName(SLTAppEventsAndNotifications.SLTAppEventNameFBLoginDidSuccess, parameters: nil) postNotification() } /// Log an event with an eventName, a numeric value to be aggregated with other events of this name, ///and a set of key/value pairs in the parameters dictionary. Providing session lets the developer ///target a particular <FBSession>. If nil is provided, then `[FBSession activeSession]` will be used. /// - Parameters: /// - eventName: the name of the event /// - parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must ///be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of ///parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names ///are provided in `FBSDKAppEventParameterName*` constants. func logTapEventWithEventName(eventName:String, parameters:[NSObject:AnyObject]? ) { FBSDKAppEvents.logEvent(eventName,valueToSum: nil,parameters: parameters,accessToken: FBSDKAccessToken.currentAccessToken()) } } extension SLTFacebookProvider : SLTProviderName { var providerName : String { get { return SLTInternals.facebookProviderName } } } /// a struct that holds user login credentials class SLTLoginCredentials { var id : String init(userID:String) { self.id = userID } } class SLTFacebookLoginCredentials : SLTLoginCredentials { var token : String init(userID:String,userToken:String) { self.token = userToken super.init(userID: userID) } } class SLTTwitterLoginProfile : SLTLoginCredentials { var token : String var secret : String init(userID:String,userToken:String,secret : String) { self.token = userToken self.secret = secret super.init(userID: userID) } } //////////////SHARE////////////////// //Helpers let SLTShareErrorDomain = "SLTShareErrors" ///Share Error code enum SLTShareErrorCode: Int { case Unknown = 1 case AppDoesntExist = 2 case EmailNotAvailable = 3 } extension NSError { convenience init(code: SLTShareErrorCode, userInfo: [NSObject: AnyObject]? = nil) { self.init(domain: SLTShareErrorDomain, code: code.rawValue, userInfo: userInfo) } convenience init(userInfo: [NSObject: AnyObject]? = nil) { self.init(domain: SLTShareErrorDomain, code: SLTShareErrorCode.Unknown.rawValue, userInfo: userInfo) } } // This makes it easy to compare an `NSError.code` to an `shareErrorDomain`. func ==(lhs: Int, rhs: SLTShareErrorCode) -> Bool { return lhs == rhs.rawValue } func ==(lhs: SLTShareErrorCode, rhs: Int) -> Bool { return lhs.rawValue == rhs } extension String { ///Encodes a String with custom allowed set (URLQuery) func URLEncodedString() -> String? { let customAllowedSet = NSCharacterSet.URLQueryAllowedCharacterSet() let escapedString = self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) return escapedString } } ///Share provider Interface. protocol SLTShareProvider { var name : String { get } ///Init the provider with its delegate Object init(delegate : SLTShareProviderDelegate?) } ///Struct containing data returned after a successful share operation. struct SLTShareResult { var postId : String init(postID:String?) { self.postId = postID ?? "" } } ///Protocol definition for callbacks to be invoked when a share operation is triggered. protocol SLTShareProviderDelegate: class { ///Sent to the delegate when the share completes without error or cancellation. /// - Parameters: /// - sharer: The SLTShareProvider that completed. /// - results: An SLTShareResult Struct containing the PostID if existed func provider(provider: SLTShareProvider, didCompleteWithResults results: SLTShareResult) ///Sent to the delegate when the sharer encounters an error. /// - Parameters: /// - sharer: The SLTShareProvider that completed. /// - Error : The error object func provider(provider: SLTShareProvider, didFailWithError error: NSError) ///Sent to the delegate when the sharer is cancelled. /// - Parameters: /// - sharer: The SLTShareProvider that completed. func providerDidCancel(sharer: SLTShareProvider) } ///A class Implements `FBSDKSharingDelegate's` delegate /// Since we cannot use Struct to be the `FBSDKSharingDelegate` delegate. That's mean the facebookShareProvider will have this class as a property and it will forward its delegate to this class. **Note:** we cannot use this class without setting its 'facebookShareProvider' property class FBSDKSharingDelegateImpl:NSObject, FBSDKSharingDelegate { weak var delegate : SLTShareProviderDelegate? var facebookShareProvider : SLTFacebookShareProvider override init() { self.facebookShareProvider = SLTFacebookShareProvider() super.init() fatalError("you cannot init FBSDKSharingDelegateImpl without Facebook share provider use init:delegate instead") } init(facebookShareProvider:SLTFacebookShareProvider) { self.facebookShareProvider = facebookShareProvider super.init() } func sharer(sharer: FBSDKSharing, didCompleteWithResults results: [NSObject : AnyObject]) { delegate?.provider(facebookShareProvider, didCompleteWithResults: SLTShareResult(postID: results["postid"] as? String)) } func sharer(sharer: FBSDKSharing, didFailWithError error: NSError) { delegate?.provider(facebookShareProvider, didFailWithError: error) } func sharerDidCancel(sharer: FBSDKSharing) { delegate?.providerDidCancel(facebookShareProvider) } } /// Struct providing Facebook share operations. struct SLTFacebookShareProvider : SLTShareProvider { var sharingDelegateImpl : FBSDKSharingDelegateImpl! var name : String { return "SLTFacebookShareProvider" } weak var delegate : SLTShareProviderDelegate? { didSet { //Forward delegation self.sharingDelegateImpl.delegate = delegate } } init() { self.sharingDelegateImpl = FBSDKSharingDelegateImpl(facebookShareProvider: self) } init(delegate : SLTShareProviderDelegate?) { self.init() self.sharingDelegateImpl.delegate = delegate } ///Requests to share a content on the user's feed. /// - Parameters: /// - button:a reference for the button/View that will trigger this method in order to get its ViewController /// - title: The title to display for this link. /// - contentURL: URL for the content being shared. /// - description:The description of the link. If not specified, this field is automatically populated by information scraped from the contentURL, typically the title of the page. This value may be discarded for specially handled links (ex: iTunes URLs). /// - imageURL: The URL of a picture to attach to this content. func share(button:UIView,title:String,contentURL: NSURL?,description:String?,imageURL:NSURL?) { let content : FBSDKShareLinkContent = FBSDKShareLinkContent() content.contentTitle = title if let url = contentURL { content.contentURL = url } if let des = description { content.contentDescription = des } if let imgURL = imageURL { content.imageURL = imgURL } FBSDKShareDialog.showFromViewController(SLTInternals.viewControllerforView(button), withContent: content, delegate: sharingDelegateImpl) } ///Requests to share a content using Facebook Messenger. /// - Parameters: /// - title: The title to display for this link. /// - contentURL: URL for the content being shared. /// - description: The description of the link. If not specified, this field is automatically populated by information scraped from the contentURL, typically the title of the page. This value may be discarded for specially handled links (ex: iTunes URLs). /// - imageURL: The URL of a picture to attach to this content. func shareMessengerText(title:String,url: NSURL?,description:String?,imageURL:NSURL?) { let content : FBSDKShareLinkContent = FBSDKShareLinkContent() content.contentTitle = title if let url = url { content.contentURL = url } if let des = description { content.contentDescription = des } if let imgURL = imageURL { content.imageURL = imgURL } FBSDKMessageDialog.showWithContent(content, delegate: sharingDelegateImpl) } }
mit
e0ba5a91a3c20fc937fa352cc05ac086
33.538642
282
0.677109
4.924207
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Chat Items/Composable/Layout/LayoutProviderProtocol.swift
1
2309
// // The MIT License (MIT) // // Copyright (c) 2015-present Badoo Trading Limited. // // 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 protocol LayoutProviderProtocol { associatedtype Layout: LayoutModel func layout(for context: LayoutContext) throws -> Layout } // TODO: Remove #745 public struct AnyLayoutProvider<Layout: LayoutModel>: LayoutProviderProtocol { private let _layout: (LayoutContext) throws -> Layout public init<Base: LayoutProviderProtocol>(_ base: Base) where Base.Layout == Layout { self._layout = { try base.layout(for: $0) } } public func layout(for context: LayoutContext) throws -> Layout { try self._layout(context) } } public struct AnySizeContainer: SizeContainer { private var _size: () -> CGSize public init<Base: SizeContainer>(_ base: Base) { self._size = { base.size } } public var size: CGSize { self._size() } } extension AnySizeContainer: LayoutModel {} extension AnyLayoutProvider where Layout == AnySizeContainer { public init<Base: LayoutProviderProtocol>(_ base: Base) where Base.Layout: SizeContainer { self._layout = { .init(try base.layout(for: $0)) } } } public typealias AnySizeProvider = AnyLayoutProvider<AnySizeContainer>
mit
ad728998b943a216329c78a6f56696e5
36.241935
94
0.72932
4.332083
false
false
false
false
blinksh/blink
KB/Native/Views/KeyModifierPicker.swift
1
1955
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import SwiftUI struct KeyModifierPicker: View { @Binding var modifier: KeyModifier @State private var _updatedAt = Date() var body: some View { List { Section { _mod(.none, title: "Default") _mod(.bit8) _mod(.escape) _mod(.control) _mod(.shift) _mod(.meta) } } .listStyle(GroupedListStyle()) } private func _mod(_ value: KeyModifier, title: String? = nil) -> some View { HStack { Text(title ?? value.description) Spacer() Checkmark(checked: modifier == value) }.overlay(Button(action: { self.modifier = value self._updatedAt = Date() }, label: { EmptyView() })) } }
gpl-3.0
89155d66def6f81d259cd8c80d976443
30.031746
82
0.610742
4.373602
false
false
false
false
ninjaprox/NVActivityIndicatorView
Sources/Base/Animations/NVActivityIndicatorAnimationBallClipRotate.swift
2
2751
// // NVActivityIndicatorBallClipRotate.swift // NVActivityIndicatorView // // 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. // #if canImport(UIKit) import UIKit class NVActivityIndicatorAnimationBallClipRotate: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let duration: CFTimeInterval = 0.75 // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.6, 1] // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.values = [0, Double.pi, 2 * Double.pi] // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.timingFunction = CAMediaTimingFunction(name: .linear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } #endif
mit
0599c16b9f0cea75803fa21a17679c3f
38.869565
137
0.699019
4.801047
false
false
false
false
nathawes/swift
test/SILGen/initializers.swift
8
42896
// RUN: %target-swift-emit-silgen -disable-objc-attr-requires-foundation-module -enable-objc-interop %s -module-name failable_initializers | %FileCheck %s // High-level tests that silgen properly emits code for failable and thorwing // initializers. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = Canary() return nil } init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = T() return nil } init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes //// //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } init?(failBeforeFullInitialization: ()) { return nil } init?(failAfterFullInitialization: ()) { member = Canary() return nil } convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br bb2([[RESULT]] : $Optional<FailableBaseClass>) // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[RESULT]] // CHECK-NEXT: } convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: cond_br {{.*}}, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB:bb[0-9]+]]: // CHECK: destroy_value [[NEW_SELF]] // CHECK: br [[FAIL_EPILOG_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK: [[UNWRAPPED_NEW_SELF:%.*]] = unchecked_enum_data [[NEW_SELF]] : $Optional<FailableBaseClass>, #Optional.some!enumelt // CHECK: assign [[UNWRAPPED_NEW_SELF]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_EPILOG_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br [[EPILOG_BB]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC21failDuringDelegation2ACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: switch_enum [[NEW_SELF]] : $Optional<FailableBaseClass>, case #Optional.some!enumelt: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: unreachable // // CHECK: [[SUCC_BB]]([[RESULT:%.*]] : @owned $FailableBaseClass): // CHECK: assign [[RESULT]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] : $FailableBaseClass // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] // CHECK-NEXT: } convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: br bb1 // // CHECK: bb1: // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[RESULT]] // // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): init?(derivedFailDuringDelegation: ()) { // First initialize the lvalue for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // // Then assign canary to other member using a borrow. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[CANARY_VALUE:%.*]] = apply // CHECK: [[CANARY_GEP:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[CANARY_GEP]] : $*Canary // CHECK: assign [[CANARY_VALUE]] to [[WRITE]] self.otherMember = Canary() // Finally, begin the super init sequence. // CHECK: [[LOADED_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[LOADED_SELF]] // CHECK: [[OPT_NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: [[IS_NIL:%.*]] = select_enum [[OPT_NEW_SELF]] // CHECK: cond_br [[IS_NIL]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // And then return nil making sure that we do not insert any extra values anywhere. // CHECK: [[SUCC_BB]]: // CHECK: [[NEW_SELF:%.*]] = unchecked_enum_data [[OPT_NEW_SELF]] // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} required init(throwingCanary: Canary) throws {} init(canary: Canary) {} init(noFail: ()) {} init(fail: Int) throws {} init(noFail: Int) {} } class ThrowDerivedClass : ThrowBaseClass { var canary: Canary? required init(throwingCanary: Canary) throws { } required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } override init(fail: Int) throws {} override init(noFail: Int) {} // ---- Delegating to super // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_ACCESS:%.*]] = begin_access [modify] [dynamic] [[CANARY_ADDR]] // CHECK: assign [[OPT_CANARY]] to [[CANARY_ACCESS]] // CHECK: end_access [[CANARY_ACCESS]] // CHECK: end_borrow [[SELF]] // // Now we perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_BASE:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[BASE_INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[SELF_INIT_BASE:%.*]] = apply [[BASE_INIT_FN]]([[SELF_BASE]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[SELF_INIT_BASE]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // Finally the error BB. We do not touch self since self is still in the // box implying that destroying MARK_UNINIT will destroy it for us. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc' init(delegatingFailBeforeDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_ACCESS:%.*]] = begin_access [modify] [dynamic] [[CANARY_ADDR]] // CHECK: assign [[OPT_CANARY]] to [[CANARY_ACCESS]] // CHECK: end_access [[CANARY_ACCESS]] // CHECK: end_borrow [[SELF]] // // Now we begin argument emission where we perform the unwrap. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Now we emit the call to the initializer. Notice how we return self back to // its memory locatio nbefore any other work is done. // CHECK: [[NORMAL_BB]]( // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) // CHECK: [[BASE_SELF_INIT:%.*]] = apply [[INIT_FN]]({{%.*}}, [[BASE_SELF]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // // Handle the return value. // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // When the error is thrown, we need to: // 1. Store self back into the "conceptually" uninitialized box. // 2. destroy the box. // 3. Perform the rethrow. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc' init(delegatingFailDuringDelegationArgEmission : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassCACyKcfc : $@convention(method) // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> (@owned ThrowBaseClass, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]([[BASE_SELF_INIT:%.*]] : @owned $ThrowBaseClass): // CHECK: [[OUT_SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[OUT_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc' init(delegatingFailDuringDelegationCall : Int) throws { try super.init() } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer and then store the new self back into its memory slot. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF_CAST]] to [init] [[PROJ]] // // Finally perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]( // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc' init(delegatingFailAfterDelegation : Int) throws { super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // Create our box. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // // Perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB:bb[0-9]+]], error [[UNWRAP_ERROR_BB:bb[0-9]+]] // // Now we begin argument emission where we perform another unwrap. // CHECK: [[UNWRAP_NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_CAST:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN2:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN2]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB2:bb[0-9]+]], error [[UNWRAP_ERROR_BB2:bb[0-9]+]] // // Then since this example has a // CHECK: [[UNWRAP_NORMAL_BB2]]([[INT:%.*]] : $Int): // CHECK: [[INIT_FN2:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = apply [[INIT_FN2]]([[INT]], [[SELF_CAST]]) : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[UNWRAP_ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: br [[ERROR_JOIN:bb[0-9]+]]([[ERROR]] // // CHECK: [[UNWRAP_ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF_CASTED_BACK:%.*]] = unchecked_ref_cast [[SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF_CASTED_BACK]] to [init] [[PROJ]] // CHECK: br [[ERROR_JOIN]]([[ERROR]] // // CHECK: [[ERROR_JOIN]]([[ERROR_PHI:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR_PHI]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc' init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() } init(delegatingFailBeforeDelegation : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } // ---- Delegating to other self method. convenience init(chainingFailBeforeDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) } convenience init(chainingFailDuringDelegationArgEmission : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationCall : Int) throws { try self.init() } convenience init(chainingFailAfterDelegation : Int) throws { self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() } convenience init(chainingFailBeforeDelegation : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC39chainingFailDuringDelegationArgEmission0fghI4CallACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]( // CHECK: try_apply {{.*}}({{.*}}, [[SELF_META]]) : {{.*}}, normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC32chainingFailDuringDelegationCall0fg5AfterI0ACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: try_apply {{.*}}([[SELF_META]]) : {{.*}}, normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: function_ref @ // CHECK-NEXT: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]( // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC28chainingFailBeforeDelegation0fg6DuringI11ArgEmission0fgjI4CallACSi_S2itKcfC' convenience init(chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } @objc protocol P3 { init?(p3: Int64) } extension P3 { init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } } class InOutInitializer { // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s21failable_initializers16InOutInitializerC1xACSiz_tcfC : $@convention(method) (@inout Int, @thick InOutInitializer.Type) -> @owned InOutInitializer { // CHECK: bb0(%0 : $*Int, %1 : $@thick InOutInitializer.Type): init(x: inout Int) {} } // <rdar://problem/16331406> class SuperVariadic { init(ints: Int...) { } } class SubVariadic : SuperVariadic { } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11SubVariadicC4intsACSid_tcfc // CHECK: bb0(%0 : @owned $Array<Int>, %1 : @owned $SubVariadic): // CHECK: [[SELF_UPCAST:%.*]] = upcast {{.*}} : $SubVariadic to $SuperVariadic // CHECK: [[T0:%.*]] = begin_borrow %0 : $Array<Int> // CHECK: [[T1:%.*]] = copy_value [[T0]] : $Array<Int> // CHECK: [[SUPER_INIT:%.*]] = function_ref @$s21failable_initializers13SuperVariadicC4intsACSid_tcfc // CHECK: apply [[SUPER_INIT]]([[T1]], [[SELF_UPCAST]]) // CHECK-LABEL: } // end sil function public struct MemberInits<Value : Equatable> { private var box: MemberInitsHelper<Value>? fileprivate var value: String = "default" } class MemberInitsHelper<T> { } extension MemberInits { // CHECK-LABEL: sil [ossa] @$s21failable_initializers11MemberInitsVyACySayqd__GGSayACyqd__GGcADRszSQRd__lufC : $@convention(method) <Value><T where Value == Array<T>, T : Equatable> (@owned Array<MemberInits<T>>, @thin MemberInits<Array<T>>.Type) -> @owned MemberInits<Array<T>> { public init<T>(_ array: [MemberInits<T>]) where Value == [T] { box = nil // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers11MemberInitsV5value33_4497B2E9306011E5BAC13C07BEAC2557LLSSvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String // CHECK-NEXT: = apply [[INIT_FN]]<Array<T>>() : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String } } // rdar://problem/51302498 class Butt { init(foo: inout (Int, Int)) { } }
apache-2.0
47b0a0b87dc9fe7109008b482b00f9f3
36.103806
282
0.656812
3.612566
false
false
false
false
roambotics/swift
test/Syntax/tokens_nonbreaking_space.swift
3
1507
// RUN: cat %s | sed -f %S/Inputs/nbsp.sed > %t.tmp // RUN: cp -f %t.tmp %t // RUN: %swift-syntax-test -input-source-filename %t -dump-full-tokens 2>&1 | %FileCheck %t let a =Z3Z // nbsp(Z) let bZ= 3Z let cZ=Z3 // CHECK: 4:8: warning: non-breaking space (U+00A0) used instead of regular space // CHECK: 4:11: warning: non-breaking space (U+00A0) used instead of regular space // CHECK: 5:6: warning: non-breaking space (U+00A0) used instead of regular space // CHECK: 5:11: warning: non-breaking space (U+00A0) used instead of regular space // CHECK: 6:6: warning: non-breaking space (U+00A0) used instead of regular space // CHECK: 6:9: warning: non-breaking space (U+00A0) used instead of regular space // CHECK-LABEL: 4:7 // CHECK-NEXT:(Token equal // CHECK-NEXT: (text="=") // CHECK-NEXT: (trivia unexpectedText \302\240)) // CHECK-LABEL: 4:10 // CHECK-NEXT:(Token integer_literal // CHECK-NEXT: (text="3") // CHECK-NEXT: (trivia unexpectedText \302\240) // CHECK-NEXT: (trivia space 1)) // CHECK-LABEL: 5:5 // CHECK-NEXT:(Token identifier // CHECK-NEXT: (text="b") // CHECK-NEXT: (trivia unexpectedText \302\240)) // CHECK-LABEL: 5:10 // CHECK-NEXT:(Token integer_literal // CHECK-NEXT: (text="3") // CHECK-NEXT: (trivia unexpectedText \302\240) // CHECK-LABEL: 6:5 // CHECK-NEXT:(Token identifier // CHECK-NEXT: (text="c") // CHECK-NEXT: (trivia unexpectedText \302\240)) // CHECK-LABEL: 6:8 // CHECK-NEXT:(Token equal // CHECK-NEXT: (text="=") // CHECK-NEXT: (trivia unexpectedText \302\240))
apache-2.0
4e2c65583218419e127ec4638ee95824
33.25
91
0.677505
2.843396
false
false
false
false
gtranchedone/NFYU
NFYUTests/TestCitySearchViewController.swift
1
8072
// // TestCitySearchViewController.swift // NFYU // // Created by Gianluca Tranchedone on 04/11/2015. // Copyright © 2015 Gianluca Tranchedone. All rights reserved. // import XCTest import MapKit import CoreLocation import AddressBook @testable import NFYU class MockCitySearchViewControllerDelegate: CitySearchViewControllerDelegate { fileprivate(set) var didFinish = false fileprivate(set) var returnedCity: Location? func citySearchViewController(_ viewController: CitySearchViewController, didFinishWithLocation location: Location?) { didFinish = true returnedCity = location } } // NOTE: FakeSearchBar is needed just to verify that becomeFirstResponder is called // because -becomeFirstResponder returns false if the viewController isn't actually being presented class FakeSearchBar: UISearchBar { fileprivate(set) var didBecomeFirstResponder = false override func becomeFirstResponder() -> Bool { didBecomeFirstResponder = true return false } } class TestCitySearchViewController: XCTestCase { var viewController: CitySearchViewController? override func setUp() { super.setUp() let storyboard = UIStoryboard(name: "Main", bundle: nil) viewController = storyboard.instantiateViewController(withIdentifier: "CitySearchViewController") as? CitySearchViewController viewController?.delegate = MockCitySearchViewControllerDelegate() viewController?.geocoder = FakeGeocoder() viewController?.loadViewIfNeeded() } override func tearDown() { viewController = nil super.tearDown() } // MARK: Initial Setup func testViewControllerGetsCorrectlyInitializedViaStoryboard() { XCTAssertNotNil(viewController) } func testViewControllerTitleIsCorrectlySet() { XCTAssertEqual(NSLocalizedString("CITY_SEARCH_VIEW_TITLE", comment: ""), viewController?.title) } func testViewControllerIsSearchBarDelegate() { XCTAssertTrue(viewController?.searchBar.delegate === viewController) } func testViewControllerMakesSearchBarFirstResponderWhenTheViewHasAppeared() { let searchBar = FakeSearchBar() viewController!.searchBar = searchBar viewController?.viewWillAppear(false) // needs to be on this exact method for the view to animate as expected XCTAssertTrue(searchBar.didBecomeFirstResponder) } func testViewControllerHasGeocoderByDefault() { let otherViewController = CitySearchViewController() XCTAssertNotNil(otherViewController.geocoder) } func testViewControllerIsTableViewDataSourceAndDelegate() { XCTAssertTrue(viewController!.tableView.delegate === viewController) XCTAssertTrue(viewController!.tableView.delegate === viewController) } // MARK: Search Logic func testViewControllerGeocodesSearchInputsLongerThenOneCharacter() { // Asian countries have city names of 2+ characters, e.g. Tokyo viewController?.searchBar(viewController!.searchBar, textDidChange: "To") let geocoder = viewController?.geocoder as! FakeGeocoder XCTAssertEqual("To", geocoder.lastGeocodedString) } func testViewControllerDoesNotGeocodeSearchInputsOfOneCharacterOnly() { viewController?.searchBar(viewController!.searchBar, textDidChange: "T") let geocoder = viewController?.geocoder as! FakeGeocoder XCTAssertNil(geocoder.lastGeocodedString) } func testViewControllerCancelsGeocoderIfAlreadyStarted() { let geocoder = viewController?.geocoder as! FakeGeocoder geocoder.canCallCompletionHandler = false viewController?.searchBar(viewController!.searchBar, textDidChange: "To") viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") XCTAssertTrue(geocoder.didCancelGeocode) XCTAssertEqual("Tok", geocoder.lastGeocodedString) } func testViewControllerReloadsTableViewDataWhenGeocoderFinishes() { let tableView = FakeTableView() viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") viewController!.tableView = tableView XCTAssertFalse(tableView.didReloadData) } func testViewControllerHasAlwaysOnlyOneTableViewSectionForDisplayingSearchResults() { XCTAssertEqual(1, viewController!.numberOfSections(in: viewController!.tableView)) } func testViewControllerShowsZeroSearchResultsByDefault() { XCTAssertEqual(0, viewController!.tableView(viewController!.tableView, numberOfRowsInSection: 0)) } func testViewControllerReturnsCorrectNumberOfResultsAfterGeocodingLocation() { let geocoder = viewController?.geocoder as! FakeGeocoder geocoder.stubPlacemarks = [placemarkForCupertino()] viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") XCTAssertEqual(1, viewController!.tableView(viewController!.tableView, numberOfRowsInSection: 0)) } func testViewControllerShowsCorrectResultsAfterGeocodingLocation() { let geocoder = viewController?.geocoder as! FakeGeocoder geocoder.stubPlacemarks = [placemarkForCupertino()] viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") let cell = viewController!.tableView(viewController!.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) XCTAssertEqual("Cupertino, CA", cell.textLabel?.text) } func testViewControllerShowsCorrectResultsAfterGeocodingLocation2() { let geocoder = viewController?.geocoder as! FakeGeocoder geocoder.stubPlacemarks = [placemarkForLondon()] viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") let cell = viewController!.tableView(viewController!.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) XCTAssertEqual("London, UK", cell.textLabel?.text) } func testViewControllerInformsDelegateWhenUserSelectsCityFromSearchResults() { let geocoder = viewController?.geocoder as! FakeGeocoder geocoder.stubPlacemarks = [placemarkForLondon()] viewController?.searchBar(viewController!.searchBar, textDidChange: "Tok") viewController?.tableView(viewController!.tableView, didSelectRowAt: IndexPath(row: 0, section: 0)) let delegate = viewController?.delegate as! MockCitySearchViewControllerDelegate let expectedCity = Location(coordinate: CLLocationCoordinate2D(latitude: 10, longitude: 20), name: "London", country: "UK") let actualCity = delegate.returnedCity XCTAssertEqual(expectedCity, actualCity) } // MARK: Private // NOTE: AddressBook is deprecated but using Contacts keys as suggested in the deprecation warning makes returned CLPlacemark not work as expected fileprivate func placemarkForCupertino() -> CLPlacemark { let placemarkLocation = CLLocationCoordinate2D(latitude: 10, longitude: 20) let placemarkAddress: [String : AnyObject] = [kABPersonAddressCityKey as String: "Cupertino" as AnyObject, kABPersonAddressStateKey as String: "CA" as AnyObject, kABPersonAddressCountryKey as String: "USA" as AnyObject] let placemark = MKPlacemark(coordinate: placemarkLocation, addressDictionary: placemarkAddress) return placemark } fileprivate func placemarkForLondon() -> CLPlacemark { let placemarkLocation = CLLocationCoordinate2D(latitude: 10, longitude: 20) let placemarkAddress: [String : AnyObject] = [kABPersonAddressCityKey as String: "London" as AnyObject, kABPersonAddressCountryKey as String: "UK" as AnyObject] let placemark = MKPlacemark(coordinate: placemarkLocation, addressDictionary: placemarkAddress) return placemark } }
mit
7329b59b9ea09b59a9365177ea6cab35
43.346154
150
0.719737
5.835864
false
true
false
false
RamonGilabert/Walker
Source/Constructors/Still.swift
1
1642
import UIKit /** Distill performs all the animations added by the tuple. - Parameter sets: A touple with multiple animations and final values. - Parameter view: The view you want to apply the animation to. - Parameter key: An optional key to put in the animation. */ public func distill(_ sets: (animation: CAKeyframeAnimation, final: NSValue)..., view: UIView, key: String? = nil) { for set in sets { guard let keyPath = set.animation.keyPath, let property = Animation.Property(rawValue: keyPath), let presentedLayer = view.layer.presentation() else { break } if let _ = set.animation.timingFunction { set.animation.values = [Animation.propertyValue(property, layer: presentedLayer), set.final] } // TODO: Implement reusable springs. view.layer.add(set.animation, forKey: key) } } var stills: [Still] = [] public struct Still { /** Defines and returns an animation with some parameters. - Parameter property: The Animation.Property that you want to animate. - Parameter curve: The animation curve you want it to be, cannot be Spring. - Parameter duration: The duration of the animation, defaults to 0.5. - Parameter options: A set of options that can be .Reverse or .Repeat(). - Returns: A CAKeyframeAnimation you can modify. */ @discardableResult public static func bezier(_ property: Animation.Property, curve: Animation.Curve = .linear, duration: TimeInterval = 0.5, options: [Animation.Options] = []) -> CAKeyframeAnimation { return Distill.bezier(property, bezierPoints: Animation.points(curve), duration: duration, options: options) } }
mit
1a6681d8a25beee3a36b8cfbb5c076af
34.695652
116
0.713155
4.287206
false
false
false
false
luosheng/OpenSim
OpenSim/SimulatorEraseMenuItem.swift
1
1227
// // SimulatorEraseMenuItem.swift // OpenSim // // Created by Craig Peebles on 6/12/19. // Copyright © 2019 Luo Sheng. All rights reserved. // import Cocoa class SimulatorEraseMenuItem: NSMenuItem { var device: Device! init(device:Device) { self.device = device let title = "\(UIConstants.strings.menuDeleteSimulatorButton) \(device.name)" super.init(title: title, action: #selector(self.deleteSimulator(_:)), keyEquivalent: "") target = self } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func deleteSimulator(_ sender: AnyObject) { let alert: NSAlert = NSAlert() alert.messageText = String(format: UIConstants.strings.actionDeleteSimulatorAlertMessage, device.name) alert.alertStyle = .critical alert.addButton(withTitle: UIConstants.strings.actionDeleteSimulatorAlertConfirmButton) alert.addButton(withTitle: UIConstants.strings.actionDeleteSimulatorAlertCancelButton) let response = alert.runModal() if response == NSApplication.ModalResponse.alertFirstButtonReturn { SimulatorController.delete(device) } } }
mit
66566977c48de8f9c48d77271950f390
29.65
110
0.690049
4.59176
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/Common/PaintStroke.swift
1
4134
// // PaintTrack.swift // SwiftGL // // Created by jerry on 2015/5/21. // Copyright (c) 2015年 Scott Bennett. All rights reserved. // import Foundation import GLKit import SwiftGL /* if _bound == nil { for point in points { expandBound(point.position) } } */ public class PaintStroke:HasBound { var _bound:GLRect! public var bound:GLRect{ get{ if _bound == nil { _bound = GLRect(p1: points[0].position.xy, p2: points[0].position.xy) for point in points { expandBound(point.position) } } return _bound } set{ _bound = newValue } } public var points:[PaintPoint] = [] //var position:[Vec2]=[] //var timestamps:[CFTimeInterval]=[] //var velocities:[Vec2] = [] public var pointData:[PointData] = [] public var startTime:Double public var texture:Texture! public var valueInfo:ToolValueInfo public var stringInfo:ToolStringInfo //init(tool:PaintBrush) //use when recording //startTime public init(s:ToolStringInfo,v:ToolValueInfo,startTime:Double) //use when load data { //let brush = PaintToolManager.instance.getTool(s.toolName) stringInfo = s valueInfo = v self.startTime = startTime //strokeInfo = sti } public func genPointsFromPointData() { points = [] for i in 0 ..< pointData.count { points.append(pointData[i].paintPoint) } } public func isPaintingAvalible()->Bool { return points.count>2 } public func last()->PaintPoint! { if points.count>0 { return points.last } else { return nil } } public func lastTwo()->[PaintPoint] { if(points.count>1) { let c = points.count let array:[PaintPoint] = [points[c-2],points[c-1]] return array } return [] } public func lastThree()->[PaintPoint] { if(points.count>2) { let c = points.count let array:[PaintPoint] = [points[c-3],points[c-2],points[c-1]] return array } return [] } public func addPoint(_ point:PaintPoint,time:CFAbsoluteTime) { points+=[point] pointData.append(PointData(paintPoint: point,t: time)) if points.count == 1 { bound = GLRect(p1: point.position.xy,p2: point.position.xy) } expandBound(point.position) } public func expandBound(_ position:Vec4) { if position.x < _bound.leftTop.x { _bound.leftTop.x = position.x } if position.y < _bound.leftTop.y { _bound.leftTop.y = position.y } if position.x > _bound.rightButtom.x { _bound.rightButtom.x = position.x } if position.y > _bound.rightButtom.y { _bound.rightButtom.y = position.y } } /* func drawBetween(startIndex:Int,endIndex:Int) { for var i = startIndex; i<endIndex-2; i++ { Painter.renderLine(valueInfo,prev2: points[i],prev1: points[i+1],cur: points[i+2]) } // } */ func setBrush() { } public var jsonStrokeInfo:String { get{ let s = "{\"tool\":\(stringInfo.toolName),\"startTime\":\(startTime),\"endTime\":\(pointData.last?.timestamps)}" return s } } } extension Sequence where Iterator.Element == PaintStroke { public var tojson:String{ get{ var s = "[" s += self.map {$0.pointData.jsonArray}.joined(separator: ",") s += "]" return s } } public var tojsonStrokeInfo:String{ var s = "[" s += self.map {$0.jsonStrokeInfo}.joined(separator: ",") s += "]" return s } }
mit
881e22f127cce364c55d48f1b7489381
21.955556
124
0.514279
4.007759
false
false
false
false
OpsLabJPL/MarsImagesIOS
Pods/EFInternetIndicator/EFInternetIndicator/Classes/InternetStatusIndicable.swift
1
837
import Foundation import SwiftMessages public protocol InternetStatusIndicable : class { var internetConnectionIndicator:InternetViewIndicator? { get set } func startMonitoringInternet(backgroundColor:UIColor, style: MessageView.Layout, textColor:UIColor, message:String, remoteHostName: String) } extension InternetStatusIndicable where Self: UIViewController { public func startMonitoringInternet(backgroundColor: UIColor = UIColor.red, style: MessageView.Layout = .statusLine, textColor: UIColor = UIColor.white, message: String = "Please, check your internet connection", remoteHostName: String = "apple.com") { internetConnectionIndicator = InternetViewIndicator(backgroundColor: backgroundColor, style: style, textColor: textColor, message: message, remoteHostName: remoteHostName) } }
apache-2.0
a5a5aa13a8f646bd415a22c1b94569fc
51.3125
256
0.786141
5.134969
false
false
false
false
DragonCherry/HFSwipeView
Example/HFSwipeView/SimpleController.swift
1
3846
// // SimpleController.swift // HFSwipeView // // Created by DragonCherry on 8/19/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import HFSwipeView import TinyLog class SimpleController: UIViewController { fileprivate let sampleCount: Int = 4 fileprivate var didSetupConstraints: Bool = false fileprivate lazy var swipeView: HFSwipeView = { let view = HFSwipeView.newAutoLayout() view.autoAlignEnabled = true view.circulating = false view.dataSource = self view.delegate = self view.pageControlHidden = true return view }() fileprivate var currentView: UIView? fileprivate var itemSize: CGSize { return CGSize(width: 100, height: 100) } fileprivate var swipeViewFrame: CGRect { return CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: 100) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.automaticallyAdjustsScrollViewInsets = false } override func viewDidLoad() { super.viewDidLoad() view.addSubview(swipeView) } override func updateViewConstraints() { if !didSetupConstraints { swipeView.autoSetDimension(.height, toSize: itemSize.height) swipeView.autoPinEdge(toSuperviewEdge: .leading) swipeView.autoPinEdge(toSuperviewEdge: .trailing) swipeView.autoAlignAxis(toSuperviewAxis: .horizontal) didSetupConstraints = true } super.updateViewConstraints() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.swipeView.setBorder(1, color: .black) } func updateCellView(_ view: UIView, indexPath: IndexPath, isCurrent: Bool) { if let label = view as? UILabel { label.backgroundColor = isCurrent ? .yellow : .white if isCurrent { // old view currentView?.backgroundColor = .white currentView = label } label.textAlignment = .center label.text = "\(indexPath.row)" label.setBorder(1, color: .black) } else { assertionFailure("failed to retrieve UILabel for index: \(indexPath.row)") } } } // MARK: - HFSwipeViewDelegate extension SimpleController: HFSwipeViewDelegate { func swipeView(_ swipeView: HFSwipeView, didFinishScrollAtIndexPath indexPath: IndexPath) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } func swipeView(_ swipeView: HFSwipeView, didSelectItemAtPath indexPath: IndexPath) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } func swipeView(_ swipeView: HFSwipeView, didChangeIndexPath indexPath: IndexPath, changedView view: UIView) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } } // MARK: - HFSwipeViewDataSource extension SimpleController: HFSwipeViewDataSource { func swipeViewItemSize(_ swipeView: HFSwipeView) -> CGSize { return itemSize } func swipeViewItemCount(_ swipeView: HFSwipeView) -> Int { return sampleCount } func swipeView(_ swipeView: HFSwipeView, viewForIndexPath indexPath: IndexPath) -> UIView { return UILabel(frame: CGRect(origin: .zero, size: itemSize)) } func swipeView(_ swipeView: HFSwipeView, needUpdateViewForIndexPath indexPath: IndexPath, view: UIView) { updateCellView(view, indexPath: indexPath, isCurrent: false) } func swipeView(_ swipeView: HFSwipeView, needUpdateCurrentViewForIndexPath indexPath: IndexPath, view: UIView) { updateCellView(view, indexPath: indexPath, isCurrent: true) } }
mit
b13adaf1c740b4b92094515af324b43c
32.434783
116
0.643953
5.161074
false
false
false
false
mownier/photostream
Photostream/UI/Shared/ActivityTableCell/ActivityTableLikeCell.swift
1
4072
// // ActivityTableLikeCell.swift // Photostream // // Created by Mounir Ybanez on 23/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit protocol ActivityTableLikeCellDelegate: class { func didTapPhoto(cell: UITableViewCell) func didTapAvatar(cell: UITableViewCell) } @objc protocol ActivityTableLikeCellAction: class { func didTapPhoto() func didTapAvatar() } class ActivityTableLikeCell: UITableViewCell, ActivityTableLikeCellAction { weak var delegate: ActivityTableLikeCellDelegate? var avatarImageView: UIImageView! var photoImageView: UIImageView! var contentLabel: UILabel! convenience init() { self.init(style: .default, reuseIdentifier: ActivityTableLikeCell.reuseId) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } func initSetup() { avatarImageView = UIImageView() avatarImageView.contentMode = .scaleAspectFill avatarImageView.backgroundColor = UIColor.lightGray avatarImageView.cornerRadius = avatarDimension / 2 photoImageView = UIImageView() photoImageView.contentMode = .scaleAspectFill photoImageView.backgroundColor = UIColor.lightGray photoImageView.clipsToBounds = true contentLabel = UILabel() contentLabel.numberOfLines = 0 contentLabel.font = UIFont.systemFont(ofSize: 12) var tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPhoto)) tap.numberOfTapsRequired = 1 photoImageView.isUserInteractionEnabled = true photoImageView.addGestureRecognizer(tap) tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapAvatar)) tap.numberOfTapsRequired = 1 avatarImageView.isUserInteractionEnabled = true avatarImageView.addGestureRecognizer(tap) addSubview(avatarImageView) addSubview(photoImageView) addSubview(contentLabel) } override func layoutSubviews() { var rect = CGRect.zero rect.origin.x = spacing rect.origin.y = (frame.height - avatarDimension) / 2 rect.size.width = avatarDimension rect.size.height = avatarDimension avatarImageView.frame = rect rect.origin.x = frame.width - photoDimension - spacing rect.origin.y = (frame.height - photoDimension) / 2 rect.size.width = photoDimension rect.size.height = photoDimension photoImageView.frame = rect rect.origin.x = avatarImageView.frame.maxX rect.origin.x += spacing rect.size.width = frame.width - rect.origin.x rect.size.width -= photoImageView.frame.width rect.size.width -= (spacing * 2) rect.size.height = contentLabel.sizeThatFits(rect.size).height rect.origin.y = (frame.height - rect.size.height) / 2 contentLabel.frame = rect } func didTapPhoto() { delegate?.didTapPhoto(cell: self) } func didTapAvatar() { delegate?.didTapAvatar(cell: self) } } extension ActivityTableLikeCell { var spacing: CGFloat { return 4 } var avatarDimension: CGFloat { return 32 } var photoDimension: CGFloat { return 40 } } extension ActivityTableLikeCell { static var reuseId: String { return "ActivityTableLikeCell" } } extension ActivityTableLikeCell { class func dequeue(from view: UITableView) -> ActivityTableLikeCell? { return view.dequeueReusableCell(withIdentifier: self.reuseId) as? ActivityTableLikeCell } class func register(in view: UITableView) { view.register(self, forCellReuseIdentifier: self.reuseId) } }
mit
c3de1e295ba4ada09b1a0affd1e5acc3
27.87234
95
0.659052
5.00738
false
false
false
false
tomlokhorst/Promissum
Tests/PromissumTests/SourceResultTests.swift
1
4628
// // SourceResultTests.swift // Promissum // // Created by Tom Lokhorst on 2015-02-08. // Copyright (c) 2015 Tom Lokhorst. All rights reserved. // import Foundation import Foundation import XCTest import Promissum class SourceResultTests: XCTestCase { func testResult() { var result: Result<Int, NSError>? let source = PromiseSource<Int, NSError>() let p = source.promise result = p.result source.reject(NSError(domain: PromissumErrorDomain, code: 42, userInfo: nil)) XCTAssert(result == nil, "Result should be nil") } func testResultValue() { var result: Result<Int, NSError>? let source = PromiseSource<Int, NSError>() let p = source.promise p.finallyResult { r in result = r } source.resolve(42) expectation(p) { XCTAssert(result?.value == 42, "Result should be value") } } func testResultError() { var result: Result<Int, NSError>? let source = PromiseSource<Int, NSError>() let p = source.promise p.finallyResult { r in result = r } source.reject(NSError(domain: PromissumErrorDomain, code: 42, userInfo: nil)) expectation(p) { XCTAssert(result?.error?.code == 42, "Result should be error") } } func testResultMapError() { var value: Int? let source = PromiseSource<Int, NSError>() let p: Promise<Int, Never> = source.promise .mapResult { result in switch result { case .failure(let error): return .success(error.code + 1) case .success: return .success(-1) } } p.then { x in value = x } source.reject(NSError(domain: PromissumErrorDomain, code: 42, userInfo: nil)) expectation(p) { XCTAssert(value == 43, "Value should be set") } } func testResultMapValue() { var value: Int? let source = PromiseSource<Int, NSError>() let p: Promise<Int, Never> = source.promise .mapResult { result in switch result { case .success(let value): return .success(value + 1) case .failure: return .success(-1) } } p.then { x in value = x } source.resolve(42) expectation(p) { XCTAssert(value == 43, "Value should be set") } } func testResultFlatMapValueValue() { var value: Int? let source = PromiseSource<Int, NSError>() let p: Promise<Int, NSError> = source.promise .flatMapResult { result in switch result { case .success(let value): return Promise(value: value + 1) case .failure: return Promise(value: -1) } } p.then { x in value = x } source.resolve(42) expectation(p) { XCTAssert(value == 43, "Value should be set") } } func testResultFlatMapValueError() { var error: NSError? let source = PromiseSource<Int, NSError>() let p: Promise<Int, NSError> = source.promise .flatMapResult { result in switch result { case .success(let value): return Promise(error: NSError(domain: PromissumErrorDomain, code: value + 1, userInfo: nil)) case .failure: return Promise(value: -1) } } p.trap { e in error = e } source.resolve(42) expectation(p) { XCTAssert(error?.code == 43, "Error should be set") } } func testResultFlatMapErrorValue() { var value: Int? let source = PromiseSource<Int, NSError>() let p: Promise<Int, NSError> = source.promise .flatMapResult { result in switch result { case .failure(let error): return Promise(value: error.code + 1) case .success: return Promise(value: -1) } } p.then { x in value = x } source.reject(NSError(domain: PromissumErrorDomain, code: 42, userInfo: nil)) expectation(p) { XCTAssert(value == 43, "Value should be set") } } func testResultFlatMapErrorError() { var error: NSError? let source = PromiseSource<Int, NSError>() let p: Promise<Int, NSError> = source.promise .flatMapResult { result in switch result { case .failure(let error): return Promise(error: NSError(domain: PromissumErrorDomain, code: error.code + 1, userInfo: nil)) case .success: return Promise(value: -1) } } p.trap { e in error = e } source.reject(NSError(domain: PromissumErrorDomain, code: 42, userInfo: nil)) expectation(p) { XCTAssert(error?.code == 43, "Error should be set") } } }
mit
f16586415f3d54714aed488207993302
20.425926
107
0.594209
3.993097
false
true
false
false
hyperoslo/CollectionAnimations
Source/Animators/StackAnimator.swift
1
1780
import UIKit public class StackAnimator: LayoutAnimator { public enum Direction { case Back, Top } public var appearingFrom: Direction public var disappearingTo: Direction public var scaleBack: CGFloat = 0.7 public var zPositionForDisappearing: CGFloat { return disappearingTo == .Back ? -100 : 100 } public convenience init() { self.init(appearingFrom: .Back, disappearingTo: .Top) } public init(appearingFrom: Direction, disappearingTo: Direction) { self.appearingFrom = appearingFrom self.disappearingTo = disappearingTo } public func animateAppearingAttributes(attributes: UICollectionViewLayoutAttributes) { applyTransformToAttributes(attributes, direction: appearingFrom) } public func animateDisappearingAttributes(attributes: UICollectionViewLayoutAttributes, forCell cell: UICollectionViewCell) { cell.layer.zPosition = zPositionForDisappearing applyTransformToAttributes(attributes, direction: disappearingTo) } private func applyTransformToAttributes(attributes: UICollectionViewLayoutAttributes, direction: Direction) { let frame = attributes.frame if direction == .Back { attributes.center = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) attributes.transform3D = CATransform3DMakeScale(scaleBack, scaleBack, 1.0) } else { var transform: CATransform3D? attributes.center = CGPoint(x: CGRectGetMinX(frame) - CGRectGetMidX(frame), y: CGRectGetMinY(frame) - CGRectGetMinY(frame)) transform = CATransform3DIdentity transform = CATransform3DRotate(transform!, CGFloat(-M_PI / 2.0), 0.0, 0.0, 1.0) if let transform = transform { attributes.transform3D = transform } attributes.alpha = 1.0 } } }
mit
8e9e08792f367b17ba6812148d40c9f6
29.689655
129
0.734831
4.708995
false
false
false
false
CPC-Coder/CPCBannerView
Example/CPCBannerView/CPCBannerView/Custom/CPCBannerViewCustomCell.swift
2
2614
// // CPCBannerViewDefaultCellCollectionViewCell.swift // bannerView // // Created by 鹏程 on 17/7/5. // Copyright © 2017年 pengcheng. All rights reserved. // /*-------- 温馨提示 --------*/ /* CPCBannerViewDefault --> collectionView上有lab (所有cell共享控件) CPCBannerViewCustom --> 每个cell上都有lab(cell都有独有控件) CPCBannerViewTextOnly --> 只有文字 */ /*-------- 温馨提示 --------*/ import UIKit class CPCBannerViewCustomCell: UICollectionViewCell { var type : CPCBannerViewCustomType = .img{ didSet{ lab.backgroundColor = UIColor.black.withAlphaComponent(0.5) lab.textColor = UIColor.white switch type { case .img: imgV.isHidden = false lab.isHidden = true case .text: lab.backgroundColor = UIColor.white lab.textColor = UIColor.black imgV.isHidden = true lab.isHidden = false case .imgAndText: imgV.isHidden = false lab.isHidden = false } //layoutIfNeeded() } } lazy var imgV: UIImageView = { let imgV = UIImageView() imgV.contentMode = .scaleToFill imgV.clipsToBounds = true return imgV }() lazy var lab: UILabel = { let lab = UILabel() lab.numberOfLines = 0 lab.adjustsFontSizeToFitWidth = true lab.backgroundColor = UIColor.black.withAlphaComponent(0.5) lab.textColor = UIColor.white return lab }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupUI() -> () { addSubview(imgV) addSubview(lab) } override func layoutSubviews() { super.layoutSubviews() switch type { case .img: imgV.frame = bounds case .text: lab.frame = bounds case .imgAndText: imgV.frame = bounds let h:CGFloat = 37 lab.frame = CGRect(x: 0, y: bounds.height-h, width: bounds.width, height: h) } } }
mit
d8f73b2b1ebdafd680867dfcef5b75be
20.386555
88
0.474263
5.151822
false
false
false
false
tkersey/top
top/Models.swift
1
8042
import UIKit struct Reddit { func topListingURL(subreddit: String) -> URL? { return URL(string: "https://www.reddit.com/r/\(subreddit)/top.json") } } struct Row { let after: String? let author: String let createdAt: Date let numberOfComments: Int let previewImage: UIImage? let thumbnail: UIImage? let title: String } extension Row: Codable { enum CodingKeys: String, CodingKey { case after, author, createdAt, numberOfComments, previewImage, thumbnail, title } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) after = try container.decode(String.self, forKey: .after) author = try container.decode(String.self, forKey: .author) createdAt = try container.decode(Date.self, forKey: .createdAt) numberOfComments = try container.decode(Int.self, forKey: .numberOfComments) title = try container.decode(String.self, forKey: .title) if let previewImageData = try container.decodeIfPresent(Data.self, forKey: .previewImage) { previewImage = NSKeyedUnarchiver.unarchiveObject(with: previewImageData) as? UIImage } else { previewImage = nil } if let thumbnailData = try container.decodeIfPresent(Data.self, forKey: .thumbnail) { thumbnail = NSKeyedUnarchiver.unarchiveObject(with: thumbnailData) as? UIImage } else { thumbnail = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(after, forKey: .after) try container.encode(author, forKey: .author) try container.encode(createdAt, forKey: .createdAt) try container.encode(numberOfComments, forKey: .numberOfComments) try container.encode(title, forKey: .title) if let previewImage = previewImage { let imageData = NSKeyedArchiver.archivedData(withRootObject: previewImage) try container.encode(imageData, forKey: .previewImage) } if let thumbnail = thumbnail { let imageData = NSKeyedArchiver.archivedData(withRootObject: thumbnail) try container.encode(imageData, forKey: .thumbnail) } } } struct Listing: Decodable { let data: ListingData let kind: String } struct ListingData: Decodable { let before: JSONNull? let after: String? let children: [Child] } struct Child: Decodable { let data: ChildData let kind: String } struct ChildData: Decodable { let author: String let createdUtc: Int let numComments: Int let preview: Preview? let title: String let thumbnail: String } struct Preview: Decodable { let images: [PreviewImage] } struct PreviewImage: Decodable { let resolutions: [Resolution] let source: Resolution } struct Resolution: Decodable { let url: String let height: Int let width: Int } extension ChildData { enum CodingKeys: String, CodingKey { case author case createdUtc = "created_utc" case numComments = "num_comments" case preview case title case thumbnail } } class JSONNull: Decodable { public init() {} public required init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if !container.decodeNil() { throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) } } } class JSONCodingKey : CodingKey { let key: String required init?(intValue: Int) { return nil } required init?(stringValue: String) { key = stringValue } var intValue: Int? { return nil } var stringValue: String { return key } } class JSONAny: Decodable { public let value: Any static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") return DecodingError.typeMismatch(JSONAny.self, context) } static func decode(from container: SingleValueDecodingContainer) throws -> Any { if let value = try? container.decode(Bool.self) { return value } if let value = try? container.decode(Int64.self) { return value } if let value = try? container.decode(Double.self) { return value } if let value = try? container.decode(String.self) { return value } if container.decodeNil() { return JSONNull() } throw decodingError(forCodingPath: container.codingPath) } static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { if let value = try? container.decode(Bool.self) { return value } if let value = try? container.decode(Int64.self) { return value } if let value = try? container.decode(Double.self) { return value } if let value = try? container.decode(String.self) { return value } if let value = try? container.decodeNil() { if value { return JSONNull() } } if var container = try? container.nestedUnkeyedContainer() { return try decodeArray(from: &container) } if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { return try decodeDictionary(from: &container) } throw decodingError(forCodingPath: container.codingPath) } static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any { if let value = try? container.decode(Bool.self, forKey: key) { return value } if let value = try? container.decode(Int64.self, forKey: key) { return value } if let value = try? container.decode(Double.self, forKey: key) { return value } if let value = try? container.decode(String.self, forKey: key) { return value } if let value = try? container.decodeNil(forKey: key) { if value { return JSONNull() } } if var container = try? container.nestedUnkeyedContainer(forKey: key) { return try decodeArray(from: &container) } if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { return try decodeDictionary(from: &container) } throw decodingError(forCodingPath: container.codingPath) } static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { var arr: [Any] = [] while !container.isAtEnd { let value = try decode(from: &container) arr.append(value) } return arr } static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] { var dict = [String: Any]() for key in container.allKeys { let value = try decode(from: &container, forKey: key) dict[key.stringValue] = value } return dict } public required init(from decoder: Decoder) throws { if var arrayContainer = try? decoder.unkeyedContainer() { self.value = try JSONAny.decodeArray(from: &arrayContainer) } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { self.value = try JSONAny.decodeDictionary(from: &container) } else { let container = try decoder.singleValueContainer() self.value = try JSONAny.decode(from: container) } } }
mit
9b8bdecc3a2d1d8c6877af81f2089962
30.291829
159
0.626834
4.653935
false
false
false
false
nbhasin2/NBNavigationController
Example/GobstonesSwift/ViewControllers/InitialViewController.swift
1
3479
// // InitialViewController.swift // GobstonesSwift // // Created by Nishant Bhasin on 2016-12-21. // Copyright © 2016 Nishant Bhasin. All rights reserved. // import Foundation import UIKit import NBNavigationController class InitialViewController: BaseViewController { @IBOutlet weak var addItemButton: UIButton! @IBOutlet weak var tableView: UITableView! fileprivate var initialViewCellIdentifier = "InitialViewCellIdentifier" fileprivate let navigationItems = ["Fade In", "Bottom Up", "Top Down"] let transitionController = NBNavigationController() override func viewDidLoad() { super.viewDidLoad() self.setup() } func setup() { self.addItemButton.setTitle("➕", for: .normal) //Setup TableView self.tableView.backgroundColor = UIColor.clear self.tableView.register(UINib(nibName: "InitialViewCell", bundle: nil), forCellReuseIdentifier: self.initialViewCellIdentifier) self.tableView.allowsSelection = true self.tableView.separatorInset = UIEdgeInsets.zero self.tableView.separatorStyle = .none self.tableView.delegate = self self.tableView.dataSource = self self.tableView.cellLayoutMarginsFollowReadableWidth = false self.tableView.contentInset = UIEdgeInsetsMake(0,0,0,0); } @IBAction func addItemAction(_ sender: UIButton) { } } extension InitialViewController: UITableViewDelegate, UITableViewDataSource { // UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } // UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return navigationItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Return proper cell with text return self.configureCell(tableView, cellForRowAtindexpath: indexPath) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let gifViewController = GifViewController(barType: .SemiTransparent, title: navigationItems[indexPath.item], shouldPop: true) let customTransition:UIViewControllerAnimatedTransitioning! switch indexPath.item { case 0: customTransition = FadeInTransition(transitionDuration: 2.0) case 1: customTransition = BottomUpTransition() case 2: customTransition = TopDownTransition() default: customTransition = FadeInTransition() } transitionController.pushViewController(gifViewController, ontoNavigationController: self.navigationController!, animatedTransition: customTransition) } // Helper methods func configureCell(_ tableView:UITableView, cellForRowAtindexpath indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: self.initialViewCellIdentifier) as? initialViewCell! { cell.foodLabel?.text = navigationItems[indexPath.item] cell.contentView.backgroundColor = UIColor.clear cell.backgroundColor = UIColor.clear cell.selectionStyle = .none return cell } return UITableViewCell(style: .default, reuseIdentifier: "emptyCell") } }
mit
4743b8cb0b244d993a7e8b5ab3afc6aa
34.835052
158
0.691312
5.48265
false
false
false
false
RiftDC/riftdc.github.io
XCode/TAHEJXBIANA/TAHEJXBIANA/ViewController.swift
1
2065
// // ViewController.swift // TAHEJXBIANA // // Created by Rodrigo Mesquita on 02/12/2017. // Copyright © 2017 Rift Inc. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var firstButton: UIButton! @IBOutlet weak var secondButton: UIButton! var timesClickedPong = 0 override func viewDidLoad() { super.viewDidLoad() self.firstButton.alpha = 0 self.secondButton.alpha = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Your code with delay UIView.animate(withDuration: 2, animations: { self.firstButton.alpha = 1 }) } @IBAction func pingClick(_ sender: UIButton) { UIView.animate(withDuration: 2, animations: { self.firstButton.alpha=0 }, completion: { (finished:Bool) in self.firstButton.isEnabled = false self.secondButton.isEnabled = true UIView.animate(withDuration: 2, animations: { self.secondButton.alpha = 1 }) }) } @IBAction func pongClick(_ sender: UIButton) { //if self.timesClickedPong == 5 { UIView.animate(withDuration: 2, animations: { self.secondButton.alpha=0 }, completion: { (finished:Bool) in self.secondButton.isEnabled = false self.firstButton.isEnabled = true UIView.animate(withDuration: 2, animations: { self.firstButton.alpha = 1 }) }) //} else { // self.timesClickedPong += 1 //} } }
mit
e97e77e6f3fd63d74afbb55538d6fecf
21.933333
61
0.499031
5.533512
false
false
false
false
benlangmuir/swift
test/Parse/type_expr.swift
6
13630
// RUN: %target-typecheck-verify-swift -swift-version 4 // not ready: dont_run: %target-typecheck-verify-swift -enable-astscope-lookup -swift-version 4 // Types in expression contexts must be followed by a member access or // constructor call. struct Foo { struct Bar { init() {} static var prop: Int = 0 static func meth() {} func instMeth() {} } init() {} static var prop: Int = 0 static func meth() {} func instMeth() {} } protocol Zim { associatedtype Zang init() // TODO class var prop: Int { get } static func meth() {} // expected-error{{protocol methods must not have bodies}} func instMeth() {} // expected-error{{protocol methods must not have bodies}} } protocol Bad { init() {} // expected-error{{protocol initializers must not have bodies}} } struct Gen<T> { struct Bar { init() {} static var prop: Int { return 0 } static func meth() {} func instMeth() {} } init() {} static var prop: Int { return 0 } static func meth() {} func instMeth() {} } func unqualifiedType() { _ = Foo.self _ = Foo.self _ = Foo() _ = Foo.prop _ = Foo.meth let _ : () = Foo.meth() _ = Foo.instMeth _ = Foo // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{10-10=()}} expected-note{{use '.self'}} {{10-10=.self}} _ = Foo.dynamicType // expected-error {{type 'Foo' has no member 'dynamicType'}} _ = Bad // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}}{{10-10=.self}} } func qualifiedType() { _ = Foo.Bar.self let _ : Foo.Bar.Type = Foo.Bar.self let _ : Foo.Protocol = Foo.self // expected-error{{cannot use 'Protocol' with non-protocol type 'Foo'}} _ = Foo.Bar() _ = Foo.Bar.prop _ = Foo.Bar.meth let _ : () = Foo.Bar.meth() _ = Foo.Bar.instMeth _ = Foo.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{14-14=()}} expected-note{{use '.self'}} {{14-14=.self}} _ = Foo.Bar.dynamicType // expected-error {{type 'Foo.Bar' has no member 'dynamicType'}} } // We allow '.Type' in expr context func metaType() { let _ = Foo.Type.self let _ = Foo.Type.self let _ = Foo.Type // expected-error{{expected member name or constructor call after type name}} // expected-note@-1 {{use '.self' to reference the type object}} let _ = type(of: Foo.Type) // expected-error{{expected member name or constructor call after type name}} // expected-note@-1 {{use '.self' to reference the type object}} } func genType() { _ = Gen<Foo>.self _ = Gen<Foo>() _ = Gen<Foo>.prop _ = Gen<Foo>.meth let _ : () = Gen<Foo>.meth() _ = Gen<Foo>.instMeth _ = Gen<Foo> // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}} // expected-note@-2{{add arguments after the type to construct a value of the type}} } func genQualifiedType() { _ = Gen<Foo>.Bar.self _ = Gen<Foo>.Bar() _ = Gen<Foo>.Bar.prop _ = Gen<Foo>.Bar.meth let _ : () = Gen<Foo>.Bar.meth() _ = Gen<Foo>.Bar.instMeth _ = Gen<Foo>.Bar // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{add arguments after the type to construct a value of the type}} // expected-note@-2{{use '.self' to reference the type object}} _ = Gen<Foo>.Bar.dynamicType // expected-error {{type 'Gen<Foo>.Bar' has no member 'dynamicType'}} } func typeOfShadowing() { // Try to shadow type(of:) func type<T>(of t: T.Type, flag: Bool) -> T.Type { // expected-note {{'type(of:flag:)' declared here}} return t } func type<T, U>(of t: T.Type, _ : U) -> T.Type { return t } func type<T>(_ t: T.Type) -> T.Type { return t } func type<T>(fo t: T.Type) -> T.Type { return t } _ = type(of: Gen<Foo>.Bar) // expected-error{{missing argument for parameter 'flag' in call}} {{28-28=, flag: <#Bool#>}} _ = type(Gen<Foo>.Bar) // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{add arguments after the type to construct a value of the type}} // expected-note@-2{{use '.self' to reference the type object}} _ = type(of: Gen<Foo>.Bar.self, flag: false) // No error here. _ = type(fo: Foo.Bar.self) // No error here. _ = type(of: Foo.Bar.self, [1, 2, 3]) // No error here. } func archetype<T: Zim>(_: T) { _ = T.self _ = T() // TODO let prop = T.prop _ = T.meth let _ : () = T.meth() _ = T // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{8-8=()}} expected-note{{use '.self'}} {{8-8=.self}} } func assocType<T: Zim>(_: T) where T.Zang: Zim { _ = T.Zang.self _ = T.Zang() // TODO _ = T.Zang.prop _ = T.Zang.meth let _ : () = T.Zang.meth() _ = T.Zang // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{13-13=()}} expected-note{{use '.self'}} {{13-13=.self}} } class B { class func baseMethod() {} } class D: B { class func derivedMethod() {} } func derivedType() { let _: B.Type = D.self _ = D.baseMethod let _ : () = D.baseMethod() let _: D.Type = D.self _ = D.derivedMethod let _ : () = D.derivedMethod() let _: B.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}} let _: D.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}} } // Referencing a nonexistent member or constructor should not trigger errors // about the type expression. func nonexistentMember() { let cons = Foo("this constructor does not exist") // expected-error{{argument passed to call that takes no arguments}} let prop = Foo.nonexistent // expected-error{{type 'Foo' has no member 'nonexistent'}} let meth = Foo.nonexistent() // expected-error{{type 'Foo' has no member 'nonexistent'}} } protocol P {} func meta_metatypes() { let _: P.Protocol = P.self _ = P.Type.self _ = P.Protocol.self _ = P.Protocol.Protocol.self // expected-error{{cannot use 'Protocol' with non-protocol type '(any P).Type'}} _ = P.Protocol.Type.self _ = B.Type.self } class E { private init() {} } func inAccessibleInit() { _ = E // expected-error {{expected member name or constructor call after type name}} expected-note {{use '.self'}} {{8-8=.self}} } enum F: Int { case A, B } struct G { var x: Int } func implicitInit() { _ = F // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}} _ = G // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}} } // https://bugs.swift.org/browse/SR-502 func testFunctionCollectionTypes() { _ = [(Int) -> Int]() _ = [(Int, Int) -> Int]() _ = [(x: Int, y: Int) -> Int]() // Make sure associativity is correct let a = [(Int) -> (Int) -> Int]() let b: Int = a[0](5)(4) _ = [String: (Int) -> Int]() _ = [String: (Int, Int) -> Int]() _ = [1 -> Int]() // expected-error {{expected type before '->'}} _ = [Int -> 1]() // expected-error {{expected type after '->'}} // expected-error@-1 {{single argument function types require parentheses}} // Should parse () as void type when before or after arrow _ = [() -> Int]() _ = [(Int) -> ()]() _ = 2 + () -> Int // expected-error {{expected type before '->'}} _ = () -> (Int, Int).2 // expected-error {{expected type after '->'}} _ = (Int) -> Int // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}} _ = @convention(c) () -> Int // expected-error{{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}} _ = 1 + (@convention(c) () -> Int).self // expected-error{{cannot convert value of type '(@convention(c) () -> Int).Type' to expected argument type 'Int'}} _ = (@autoclosure () -> Int) -> (Int, Int).2 // expected-error {{expected type after '->'}} _ = ((@autoclosure () -> Int) -> (Int, Int)).1 // expected-error {{type '(@autoclosure () -> Int) -> (Int, Int)' has no member '1'}} _ = ((inout Int) -> Void).self _ = [(Int) throws -> Int]() _ = [@convention(swift) (Int) throws -> Int]().count _ = [(inout Int) throws -> (inout () -> Void) -> Void]().count _ = [String: (@autoclosure (Int) -> Int32) -> Void]().keys // expected-error {{argument type of @autoclosure parameter must be '()'}} let _ = [(Int) -> throws Int]() // expected-error{{'throws' may only occur before '->'}} let _ = [Int throws Int](); // expected-error{{'throws' may only occur before '->'}} expected-error {{consecutive statements on a line must be separated by ';'}} } protocol P1 {} protocol P2 {} protocol P3 {} func compositionType() { _ = P1 & P2 // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self'}} {{7-7=(}} {{14-14=).self}} _ = P1 & P2.self // expected-error {{binary operator '&' cannot be applied to operands of type '(any P1).Type' and '(any P2).Type'}} _ = (P1 & P2).self // Ok. _ = (P1 & (P2)).self // FIXME: OK? while `typealias P = P1 & (P2)` is rejected. _ = (P1 & (P2, P3)).self // expected-error {{non-protocol, non-class type '(any P2, any P3)' cannot be used within a protocol-constrained type}} _ = (P1 & Int).self // expected-error {{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}} _ = (P1? & P2).self // expected-error {{non-protocol, non-class type '(any P1)?' cannot be used within a protocol-constrained type}} _ = (P1 & P2.Type).self // expected-error {{non-protocol, non-class type 'any P2.Type' cannot be used within a protocol-constrained type}} _ = P1 & P2 -> P3 // expected-error @-1 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}} // expected-error @-2 {{expected member name or constructor call after type name}} // expected-note @-3 {{use '.self'}} {{7-7=(}} {{20-20=).self}} _ = P1 & P2 -> P3 & P1 -> Int // expected-error @-1 {{single argument function types require parentheses}} {{18-18=(}} {{25-25=)}} // expected-error @-2 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}} // expected-error @-3 {{expected member name or constructor call after type name}} // expected-note @-4 {{use '.self'}} {{7-7=(}} {{32-32=).self}} _ = (() -> P1 & P2).self // Ok _ = (P1 & P2 -> P3 & P2).self // expected-error {{single argument function types require parentheses}} {{8-8=(}} {{15-15=)}} _ = ((P1 & P2) -> (P3 & P2) -> P1 & Any).self // Ok } func complexSequence() { // (assign_expr // (discard_assignment_expr) // (try_expr // (type_expr typerepr='P1 & P2 throws -> P3 & P1'))) _ = try P1 & P2 throws -> P3 & P1 // expected-warning @-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error @-2 {{single argument function types require parentheses}} {{11-11=(}} {{18-18=)}} // expected-error @-3 {{expected member name or constructor call after type name}} // expected-note @-4 {{use '.self' to reference the type object}} {{11-11=(}} {{36-36=).self}} } func takesVoid(f: Void -> ()) {} // expected-error {{single argument function types require parentheses}} {{19-23=()}} func takesOneArg<T>(_: T.Type) {} func takesTwoArgs<T>(_: T.Type, _: Int) {} func testMissingSelf() { // None of these were not caught in Swift 3. // See test/Compatibility/type_expr.swift. takesOneArg(Int) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesOneArg(Swift.Int) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesTwoArgs(Int, 0) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesTwoArgs(Swift.Int, 0) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} Swift.Int // expected-warning {{expression of type 'Int.Type' is unused}} // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} _ = Swift.Int // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} }
apache-2.0
0ee751e841b2b489fbeabade3a072be1
39.088235
186
0.627733
3.466429
false
false
false
false
tomvanzummeren/TZStackView
TZStackViewDemo/ExplicitIntrinsicContentSizeView.swift
1
1116
// // Created by Tom van Zummeren on 10/06/15. // Copyright (c) 2015 Tom van Zummeren. All rights reserved. // import UIKit class ExplicitIntrinsicContentSizeView: UIView { let name: String let contentSize: CGSize init(intrinsicContentSize: CGSize, name: String) { self.name = name self.contentSize = intrinsicContentSize super.init(frame: CGRect.zero) let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ExplicitIntrinsicContentSizeView.tap)) addGestureRecognizer(gestureRecognizer) isUserInteractionEnabled = true } func tap() { UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { self.isHidden = true }, completion: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize : CGSize { return contentSize } override var description: String { return name } }
mit
aacfa5fd0fe0e6abe18f71ebbd9636ed
26.219512
152
0.677419
4.938053
false
false
false
false
LinkRober/RBRefresh
custom/RBBallRoateChaseHeader.swift
1
2960
// // RBBallRoateChaseHeader.swift // RBRefresh // // Created by 夏敏 on 06/02/2017. // Copyright © 2017 夏敏. All rights reserved. // import UIKit class RBBallRoateChaseHeader: UIView,RBPullDownToRefreshViewDelegate { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1) for i in 0..<5 { let rate = Float(i) * 1.0 / 5 let layer = CAShapeLayer() let path:UIBezierPath = UIBezierPath() path.addArc(withCenter: CGPoint.init(x: 4, y: 4), radius: 4, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false) layer.fillColor = UIColor.white.cgColor layer.path = path.cgPath layer.frame = CGRect.init(x: (frame.size.width - 8) / 2, y: 8, width: 8, height: 8) let animation = roateAnimation(x: frame.size.width / 2, y: frame.size.height / 2,rate:rate) layer.add(animation, forKey: "animation") self.layer.addSublayer(layer) } } func roateAnimation(x:CGFloat,y:CGFloat,rate:Float) -> CAAnimationGroup { let duration:CFTimeInterval = 1.5 let fromScale = 1 - rate let toScale = 0.2 + rate let timeFunc = CAMediaTimingFunction.init(controlPoints: 0.5, 0.15 + rate, 0.25, 1.0) //scale animation let scaleAnimation = CABasicAnimation.init(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.repeatCount = HUGE scaleAnimation.fromValue = fromScale scaleAnimation.toValue = toScale //positon animtaion let positionAnimation = CAKeyframeAnimation.init(keyPath: "position") positionAnimation.duration = duration positionAnimation.repeatCount = HUGE positionAnimation.path = UIBezierPath.init(arcCenter: CGPoint.init(x: x, y: y), radius: 15, startAngle: 3 * CGFloat(M_PI) * 0.5, endAngle: 3 * CGFloat(M_PI) * 0.5 + 2 * CGFloat(M_PI), clockwise: true).cgPath //animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation,positionAnimation] animation.timingFunction = timeFunc animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pullDownToRefreshAnimationDidEnd(_ view: RBHeader) { } func pullDownToRefreshAnimationDidStart(_ view: RBHeader) { } func pullDownToRefresh(_ view: RBHeader, progressDidChange progress: CGFloat) { } func pullDownToRefresh(_ view: RBHeader, stateDidChange state: RBPullDownToRefreshViewState) { } }
mit
07a4ac214f4e0e0192a8ce29bed8bb27
36.833333
215
0.631311
4.314327
false
false
false
false
materik/stubborn
Stubborn/Stubborn.swift
1
2669
import Foundation public class Stubborn { public enum LogLevel: Int { case debug case verbose var flag: String { switch self { case .debug: return "DEBUG " case .verbose: return "VERBOSE" } } } public typealias RequestResponse = (Request) -> (Body) public typealias UnhandledRequestResponse = (Request) -> () public static var logLevel: LogLevel? public static var isOn: Bool = false public static var isAllowingUnhandledRequest: Bool = false static private(set) var stubs: [Stub] = [] static private(set) var unhandledRequestResponse: UnhandledRequestResponse? private init() { // Do nothing... } @discardableResult public static func add(url: String, response: @escaping RequestResponse) -> Stub { return self.add(stub: Stub(url, response: response)) } @discardableResult public static func add(url: String, dictionary: Stubborn.Body.Dictionary) -> Stub { return self.add(stub: Stub(url, dictionary: dictionary)) } @discardableResult public static func add(url: String, error: Stubborn.Body.Error) -> Stub { return self.add(stub: Stub(url, error: error)) } @discardableResult public static func add(url: String, simple: Stubborn.Body.Simple) -> Stub { return self.add(stub: Stub(url, simple: simple)) } @discardableResult public static func add(url: String, resource: Stubborn.Body.Resource) -> Stub { return self.add(stub: Stub(url, resource: resource)) } private static func add(stub: Stub) -> Stub { self.start() stub.index = self.stubs.count self.stubs.append(stub) self.log("add stub: <\(stub)>") return stub } public static func unhandledRequest(_ response: @escaping UnhandledRequestResponse) { self.unhandledRequestResponse = response } public static func start() { guard !self.isOn else { return } self.isOn = true self.log("start") StubbornProtocol.register() } public static func reset() { self.log("reset") self.stubs = [] self.unhandledRequestResponse = nil } static func log(_ message: String, level: LogLevel = .debug) { if level.rawValue <= (self.logLevel?.rawValue ?? -1) { print("Stubborn (\(self.stubs.count)): \(level.flag): \(message)") } } }
mit
f37ebabd2b8091abb4ba86b7991003d9
25.959596
89
0.575871
4.585911
false
false
false
false
rsaenzi/MyWeatherForecastApp
MyWeatherForecastApp/MyWeatherForecastApp/TravelLocationsVC.swift
1
12453
// // TravelLocationsVC.swift // MyWeatherForecastApp // // Created by Rigoberto Sáenz Imbacuán on 1/28/16. // Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import ForecastIO import KVNProgress import GoogleMaps class TravelLocationsVC: UIViewController { // APi Access private let googleMapsGeocodingAPIKey = "AIzaSyABstQbHmTXkLvaaPtC1GCfqE9Bmv0DJgA" private let forecastIOClient = APIClient(apiKey: "c617b4ec377c53f3fac8ca7018526435") // Recomendation private var firstTemperature: Float = 0 private var secondTemperature: Float = 0 // First Country @IBOutlet weak var labelFirstTemperature: UILabel! @IBOutlet weak var labelFirstCountry: UILabel! // Second Country @IBOutlet weak var labelSecondTemperature: UILabel! @IBOutlet weak var labelSecondCountry: UILabel! // Recomendation @IBOutlet weak var labelRecomendationTitle: UILabel! @IBOutlet weak var labelRecomendationCity: UILabel! @IBOutlet weak var imageRecomendation: UIImageView! // Containers @IBOutlet weak var containerFirstCountry: UIView! @IBOutlet weak var containerSecondCountry: UIView! @IBOutlet weak var containerRecomendation: UIView! override func viewDidLoad() { super.viewDidLoad() // Definimos el sistema de medidas forecastIOClient.units = .SI } private func hideAllButtons(){ containerFirstCountry.hidden = true containerSecondCountry.hidden = true containerRecomendation.hidden = true } override func viewWillAppear(animated: Bool){ // Called when the view is about to made visible. Default does nothing super.viewWillAppear(true) // Mostramos un alert de progreso KVNProgress.showWithStatus("Getting weather forecast...") // Por seguridad, todos los botones estan desactivados hideAllButtons() // Si aplica, mostramos la data del primer pais if Model.instance.getSelectedCountry(.FirstCountry) != nil && Model.instance.getSelectedCity(.FirstCountry) != nil { // Solicitamos la info del clima para el primer pais getFirstCountryWheather(Model.instance.getSelectedCountry(.FirstCountry)!, firstCity: Model.instance.getSelectedCity(.FirstCountry)!) }else { // Mostramos el primer boton para que el usuario pueda seleccionar la primera ciudad self.containerFirstCountry.hidden = false // Cerramos el alert de progreso KVNProgress.dismiss() } } // ---------------------------------------------------------------------- // First Country // ---------------------------------------------------------------------- func getFirstCountryWheather(firstCountry: String, firstCity: String){ do{ // Creamos los parametros para el request let parameters = [ "address": "\(firstCity),\(firstCountry)".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!, "key": googleMapsGeocodingAPIKey ] // Solicitamos la info del area geografica actual a partir de la ubicacion actual Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters) .responseString { response in // Si el request fue exitoso if response.result.isSuccess { // Convertimos el string en un arbol JSON let jsonTree = SwiftyJSON.JSON.parse(response.result.value!) // Extraemos las coordenas let firstCityCoords = (jsonTree["results"][0]["geometry"]["location"]["lat"].double!, jsonTree["results"][0]["geometry"]["location"]["lng"].double!) // Solicitamos el reporte del clima para el area actual self.forecastIOClient.getForecast(latitude: firstCityCoords.0, longitude: firstCityCoords.1) { (currentForecast, error) -> Void in // Si el reporte es valido if let currentForecast = currentForecast { // Guardamos la temperatura para hacer la comparacion posterior self.firstTemperature = currentForecast.currently!.temperature! // Ejecutamos en el thread que maneja la UI dispatch_async(dispatch_get_main_queue(),{ // Mostramos la temperatura self.containerFirstCountry.hidden = false self.labelFirstCountry.text = "\(firstCity), \(firstCountry)" self.labelFirstTemperature.text = "\(self.firstTemperature) °c" }) // Si aplica, mostramos la data del segundo pais if Model.instance.getSelectedCountry(.SecondCountry) != nil && Model.instance.getSelectedCity(.SecondCountry) != nil { // Solicitamos la info del clima para el segundo pais self.getSecondCountryWheather(Model.instance.getSelectedCountry(.SecondCountry)!, secondCity: Model.instance.getSelectedCity(.SecondCountry)!) }else { // Ejecutamos en el thread que maneja la UI dispatch_async(dispatch_get_main_queue(),{ // Mostramos el segundo boton para que el usuario pueda seleccionar la segunda ciudad self.containerSecondCountry.hidden = false }) // Cerramos el alert de progreso KVNProgress.dismiss() } } else { // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } }else{ // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } }catch{ // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } // ---------------------------------------------------------------------- // Second Country // ---------------------------------------------------------------------- func getSecondCountryWheather(secondCountry: String, secondCity: String){ do{ // Creamos los parametros para el request let parameters = [ "address": "\(secondCity),\(secondCountry)".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!, "key": googleMapsGeocodingAPIKey ] // Solicitamos la info del area geografica actual a partir de la ubicacion actual Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters) .responseString { response in // Si el request fue exitoso if response.result.isSuccess { // Convertimos el string en un arbol JSON let jsonTree = SwiftyJSON.JSON.parse(response.result.value!) // Extraemos las coordenas let secondCityCoords = (jsonTree["results"][0]["geometry"]["location"]["lat"].double!, jsonTree["results"][0]["geometry"]["location"]["lng"].double!) // Solicitamos el reporte del clima para el area actual self.forecastIOClient.getForecast(latitude: secondCityCoords.0, longitude: secondCityCoords.1) { (currentForecast, error) -> Void in // Si el reporte es valido if let currentForecast = currentForecast { // Guardamos la temperatura para hacer la comparacion posterior self.secondTemperature = currentForecast.currently!.temperature! // Ejecutamos en el thread que maneja la UI dispatch_async(dispatch_get_main_queue(),{ // Mostramos la temperatura self.containerSecondCountry.hidden = false self.labelSecondCountry.text = "\(secondCity), \(secondCountry)" self.labelSecondTemperature.text = "\(self.secondTemperature) °c" // LLegados a este punto podemos mostrar la recomendacion self.containerRecomendation.hidden = false // Determinamos cual ciudad es mejor para vacacionar if self.firstTemperature > self.secondTemperature { self.labelRecomendationCity.text = self.labelFirstCountry.text }else { self.labelRecomendationCity.text = self.labelSecondCountry.text } }) // Cerramos el alert de progreso KVNProgress.dismiss() } else { // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } }else{ // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } }catch{ // Error self.hideAllButtons() // Cerramos el alert de progreso KVNProgress.dismiss() } } @IBAction func onClickFirstCountry(sender: UIButton, forEvent event: UIEvent) { Model.instance.setCountryPointerForSelection(OrderSelection.FirstCountry) } @IBAction func onClickSecondCountry(sender: UIButton, forEvent event: UIEvent) { Model.instance.setCountryPointerForSelection(OrderSelection.SecondCountry) } }
mit
8ee3999b71194fc36a4055a456266558
44.937269
178
0.466902
6.258421
false
false
false
false
tapz/MWPhotoBrowserSwift
Pod/Classes/CaptionView.swift
1
2686
// // CaptionView.swift // MWPhotoBrowserSwift // // Created by Tapani Saarinen on 04/09/15. // Original obj-c created by Michael Waterfall 2013 // // import UIKit public class CaptionView: UIToolbar { private var photo: Photo? private var label = UILabel() public let labelPadding = CGFloat(10.0) init(photo: Photo?) { super.init(frame: CGRectMake(0, 0, 320.0, 44.0)) // Random initial frame self.photo = photo setupCaption() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCaption() } public override func sizeThatFits(size: CGSize) -> CGSize { var maxHeight = CGFloat(9999.0) if label.numberOfLines > 0 { maxHeight = label.font.leading * CGFloat(label.numberOfLines) } let textSize: CGSize if let text = label.text { textSize = text.boundingRectWithSize( CGSizeMake(size.width - labelPadding * 2.0, maxHeight), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil).size } else { textSize = CGSizeMake(0.0, 0.0) } return CGSizeMake(size.width, textSize.height + labelPadding * 2.0) } private func setupCaption() { userInteractionEnabled = false barStyle = .Default tintColor = UIColor.clearColor() barTintColor = UIColor.whiteColor() backgroundColor = UIColor.whiteColor() opaque = false translucent = true clipsToBounds = true setBackgroundImage(nil, forToolbarPosition: .Any, barMetrics: .Default) autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin] label = UILabel(frame: CGRectIntegral(CGRectMake( labelPadding, 0.0, self.bounds.size.width - labelPadding * 2.0, self.bounds.size.height))) label.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] label.opaque = false label.backgroundColor = UIColor.clearColor() label.textAlignment = NSTextAlignment.Center label.lineBreakMode = .ByWordWrapping label.minimumScaleFactor = 0.6 label.adjustsFontSizeToFitWidth = true label.numberOfLines = 0 label.textColor = UIColor.blackColor() label.font = UIFont.systemFontOfSize(17.0) if let p = photo { label.text = p.caption } self.addSubview(label) } }
mit
6425b71ef7f9a33d50ccccd85bba8c12
29.522727
91
0.596426
5.011194
false
false
false
false
ACChe/eidolon
Kiosk/App/Views/RegisterFlowView.swift
1
4017
import UIKit import ORStackView import ReactiveCocoa class RegisterFlowView: ORStackView { dynamic var highlightedIndex = 0 let jumpToIndexSignal = RACSubject() lazy var appSetup: AppSetup = .sharedState var details: BidDetails? { didSet { self.update() } } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = .whiteColor() self.bottomMarginHeight = CGFloat(NSNotFound) self.updateConstraints() } private struct SubViewParams { let title: String let keypath: Array<String> } private lazy var subViewParams: Array<SubViewParams> = { return [ [SubViewParams(title: "Mobile", keypath: ["phoneNumber"])], [SubViewParams(title: "Email", keypath: ["email"])], [SubViewParams(title: "Postal/Zip", keypath: ["zipCode"])].filter { _ in self.appSetup.needsZipCode }, // TODO: may remove, in which case no need to flatten the array [SubViewParams(title: "Credit Card", keypath: ["creditCardName", "creditCardType"])] ].flatMap {$0} }() func update() { let user = details!.newUser removeAllSubviews() for (i, subViewParam) in subViewParams.enumerate() { let itemView = ItemView(frame: self.bounds) itemView.createTitleViewWithTitle(subViewParam.title) addSubview(itemView, withTopMargin: "10", sideMargin: "0") if let value = (subViewParam.keypath.flatMap { user.valueForKey($0) as? String }.first) { itemView.createInfoLabel(value) let button = itemView.createJumpToButtonAtIndex(i) button.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside) itemView.constrainHeight("44") } else { itemView.constrainHeight("20") } if i == highlightedIndex { itemView.highlight() } } let spacer = UIView(frame: bounds) spacer.setContentHuggingPriority(12, forAxis: .Horizontal) addSubview(spacer, withTopMargin: "0", sideMargin: "0") self.bottomMarginHeight = 0 } func pressed(sender: UIButton!) { jumpToIndexSignal.sendNext(sender.tag) } class ItemView : UIView { var titleLabel: UILabel? func highlight() { titleLabel?.textColor = .artsyPurple() } func createTitleViewWithTitle(title: String) { let label = UILabel(frame:self.bounds) label.font = UIFont.sansSerifFontWithSize(16) label.text = title.uppercaseString titleLabel = label self.addSubview(label) label.constrainWidthToView(self, predicate: "0") label.alignLeadingEdgeWithView(self, predicate: "0") label.alignTopEdgeWithView(self, predicate: "0") } func createInfoLabel(info: String) { let label = UILabel(frame:self.bounds) label.font = UIFont.serifFontWithSize(16) label.text = info self.addSubview(label) label.constrainWidthToView(self, predicate: "-52") label.alignLeadingEdgeWithView(self, predicate: "0") label.constrainTopSpaceToView(titleLabel!, predicate: "8") } func createJumpToButtonAtIndex(index: NSInteger) -> UIButton { let button = UIButton(type: .Custom) button.tag = index button.setImage(UIImage(named: "edit_button"), forState: .Normal) button.userInteractionEnabled = true button.enabled = true self.addSubview(button) button.alignTopEdgeWithView(self, predicate: "0") button.alignTrailingEdgeWithView(self, predicate: "0") button.constrainWidth("36") button.constrainHeight("36") return button } } }
mit
e370148776c60d4ebae273cd64020aba
31.136
178
0.597212
4.990062
false
false
false
false
grzegorzkrukowski/CellRegistration
CellRegistration/Classes/UICollectionView+register.swift
1
1774
// // UICollectionView+register.swift // Pods // // Created by Grzegorz Krukowski on 08/03/2017. // // import Foundation private struct AssociatedObjectKey { static var registeredCells = "registeredCells" } extension UICollectionView { private var registeredCells: Set<String> { get { if objc_getAssociatedObject(self, &AssociatedObjectKey.registeredCells) as? Set<String> == nil { self.registeredCells = Set<String>() } return objc_getAssociatedObject(self, &AssociatedObjectKey.registeredCells) as! Set<String> } set(newValue) { objc_setAssociatedObject(self, &AssociatedObjectKey.registeredCells, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func register<T: ReusableView>(_: T.Type) { let bundle = Bundle(for: T.self) if bundle.path(forResource: T.reuseIdentifier, ofType: "nib") != nil { let nib = UINib(nibName: T.reuseIdentifier, bundle: bundle) register(nib, forCellWithReuseIdentifier: T.reuseIdentifier) } else { register(T.self, forCellWithReuseIdentifier: T.reuseIdentifier) } } public func dequeueReusableCell<T: ReusableView>(forIndexPath indexPath: IndexPath) -> T { if self.registeredCells.contains(T.reuseIdentifier) == false { self.registeredCells.insert(T.reuseIdentifier) self.register(T.self) } guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError("Error dequeuing cell with reuse identifier: \(T.reuseIdentifier)") } return cell } }
mit
cda74dcfa2eee8bfb50458c169f513c5
33.115385
148
0.642616
4.873626
false
false
false
false
anthonyohare/SwiftScientificLibrary
Sources/SwiftScientificLibrary/base/Complex.swift
1
5854
import Foundation public final class Complex: Numeric, ExpressibleByFloatLiteral, CustomStringConvertible { public typealias FloatLiteralType = Float64 public typealias IntegerLiteralType = Int64 public typealias Magnitude = Double /// The real part of the complex number. private var _real: Double = 0.0 public var real: Double { get { return _real } set { _real = newValue } } /// The imaginary part of the complex number. private var _imag: Double = 0.0 public var imag: Double { get { return _imag } set { _imag = newValue } } public var magnitude: Double { get { return sqrt(self.real * self.real + self.imag * imag) } } public required init(integerLiteral value: Int64) { self.real = Double(value) self.imag = 0.0 } public required init(floatLiteral value: Float64) { self.real = Double(value) self.imag = 0.0 } public init(real: Double, imag: Double) { self.real = real self.imag = imag } // FIXME(integers): implement properly public init?<T>(exactly source: T) where T: BinaryInteger { fatalError() } /// A string description of the complex number. public var description: String { if imag.isEqual(to: 0.0) { return String(describing: real) } else if real == 0 { return String(describing: imag) + "i" } else { return (imag.sign == .minus) ? "\(real)\(imag)i" : "\(real)+\(imag)i" } } /// Compute the difference of two complex numbers. /// /// - Parameters: /// - lhs: the left hand complex number. /// - rhs: the right hand complex number. /// - Returns: The difference of the two numbers. public static func - (lhs: Complex, rhs: Complex) -> Complex { return self.init(real: (lhs.real - rhs.real), imag: (lhs.imag - rhs.imag)) } /// Compute the sum of two complex numbers. /// /// - Parameters: /// - lhs: the left hand complex number. /// - rhs: the right hand complex number. /// - Returns: The product of the two numbers. public static func + (lhs: Complex, rhs: Complex) -> Complex { return self.init(real: (rhs.real + lhs.real), imag: (rhs.imag + lhs.imag)) } /// Compute the product of two complex numbers. /// /// - Parameters: /// - lhs: the left hand complex number. /// - rhs: the right hand complex number. /// - Returns: The product of the two numbers. public static func * (lhs: Complex, rhs: Complex) -> Complex { return self.init(real: (lhs.real * rhs.real - lhs.imag * rhs.imag), imag: (lhs.real * rhs.imag + lhs.imag * rhs.real)) } /// Compute the quotient of two complex numbers. /// /// - Parameters: /// - lhs: the left hand complex number. /// - rhs: the right hand complex number. /// - Returns: the quotient of two numbers. public static func / (lhs: Complex, rhs: Complex) -> Complex { let denominator = rhs.real*rhs.real + rhs.imag*rhs.imag let numerator = (lhs * rhs.conjugate()) return Complex(real: (numerator.real / denominator), imag: (numerator.imag / denominator)) } public static func -= (lhs: inout Complex, rhs: Complex) { lhs -= rhs } public static func += (lhs: inout Complex, rhs: Complex) { lhs += rhs } public static func *= (lhs: inout Complex, rhs: Complex) { lhs *= rhs } /// Determines if two complex numbers are equal to a given complex number (i.e. both real parts /// and imaginery parts are equal (to within a tolerance). /// /// - Parameters: /// - lhs: the first complex number /// - rhs: the second complex number /// - Returns: True if the numbers are equal, false otherwise. public static func == (lhs: Complex, rhs: Complex) -> Bool { return lhs.real.isEqual(to: rhs.real, accuracy: 0.00001) && lhs.imag.isEqual(to: rhs.imag, accuracy: 0.00001) } /// Compute the conjugate of the complex number. /// - SeeAlso https://en.wikipedia.org/wiki/Complex_conjugate /// /// - Returns: The conjugate of self. public func conjugate() -> Complex { return Complex(real: self.real, imag: -self.imag) } /// Compute the principal argument (the angle the complex number /// makes with the positive real axes) of the complex number. /// /// - SeeAlso https://en.wikipedia.org/wiki/Argument_(complex_analysis) /// - SeeAlso http://www.theoretical-physics.net/dev/math/complex.html#argument-function /// /// - Returns: The argument of self. public func arg() -> Double { return atan2(self.imag, self.real) } /// Compute the modulus (absolute value) of the complex number. /// - SeeAlso https://en.wikipedia.org/wiki/Absolute_value#Complex_numbers1 /// /// - Returns: The modulus of self. public func modulus() -> Double { return self.magnitude } /// Compute the absolute value (modulus) of the complex number. /// - SeeAlso https://en.wikipedia.org/wiki/Absolute_value#Complex_numbers1 /// /// - Returns: The modulus of self. public func abs() -> Double { return self.magnitude } /// Compute the Euclidean norm of the complex number. /// - SeeAlso https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm_of_a_complex_number /// /// - Returns: The Euclidean norm of self. public func norm() -> Double { return self.magnitude } }
mit
115f8d2d543de7534665ecf1adb338c9
31.522222
117
0.58302
4.160625
false
false
false
false
einsteinx2/iSub
Classes/Data Model/Playlist.swift
1
1315
// // Playlist.swift // LibSub // // Created by Benjamin Baron on 2/10/16. // // import Foundation extension Playlist: Item, Equatable { var itemId: Int64 { return playlistId } var itemName: String { return name } } final class Playlist { let repository: PlaylistRepository var playlistId: Int64 var serverId: Int64 var name: String var coverArtId: String? // TODO: See if we should always load these from database rather than using the loadSubItems concept from the other models var songs = [Song]() init(playlistId: Int64, serverId: Int64, name: String, coverArtId: String?, repository: PlaylistRepository = PlaylistRepository.si) { self.playlistId = playlistId self.serverId = serverId self.name = name self.coverArtId = coverArtId self.repository = repository } } // Notifications extension Playlist { struct Notifications { static let playlistChanged = Notification.Name("playlistChanged") struct Keys { static let playlistId = "playlistId" } } func notifyPlaylistChanged() { NotificationCenter.postOnMainThread(name: Playlist.Notifications.playlistChanged, object: nil, userInfo: [Notifications.Keys.playlistId: playlistId]) } }
gpl-3.0
39178e8805d0934284be07104158249b
25.836735
157
0.671483
4.427609
false
false
false
false
nodes-ios/model-generator
model-generator-cli/ModelGeneratorCLI.swift
1
2448
// // ModelGeneratorCLI.swift // model-generator // // Created by Dominik Hádl on 19/01/16. // Copyright © 2016 Nodes. All rights reserved. // import Foundation public final class ModelGeneratorCLI: CommandLineKit { let sourceCode = StringOption( shortFlag: "s", longFlag: "source-code", required: true, helpMessage: "Source code for model generator to generate model boilerplate code.") let moduleName = StringOption( shortFlag: "m", longFlag: "module-name", required: false, helpMessage: "Optional module name to prepend to a struct/class name.") let nativeDictionaries = BoolOption( shortFlag: "n", longFlag: "native-swift-dictionaries", required: false, helpMessage: "Optionally use native swift dictionaries instead of NSDictionary in generated model code.") let noCamelCaseConversion = BoolOption( shortFlag: "c", longFlag: "no-convert-camel-case", required: false, helpMessage: "Optionally don't convert property keys from camel case to underscores.") public init() { super.init() addOptions(sourceCode, moduleName, nativeDictionaries, noCamelCaseConversion) } public func run() { checkInput() generateCode() } // MARK: - Private - private func checkInput() { do { try parse() } catch { printUsage(error: error) exit(EX_USAGE) } } private func generateCode() { // If no source code provided, then exit guard let code = sourceCode.value else { exit(EX_NOINPUT) } // Create the generator settings var settings = ModelGeneratorSettings() settings.noConvertCamelCase = noCamelCaseConversion.value settings.useNativeDictionaries = nativeDictionaries.value settings.moduleName = moduleName.value // Try generating the model and print to stdout if success do { let modelCode = try ModelGenerator.modelCode(fromSourceCode: code, withSettings: settings) if let data = modelCode.data(using: String.Encoding.utf8) { FileHandle.standardOutput.write(data) exit(EX_OK) } else { exit(EXIT_FAILURE) } } catch { exit(EXIT_FAILURE) } } }
mit
e471159027d7f94d680a3dd2d07e5f5c
28.46988
113
0.607522
4.796078
false
false
false
false
hweetty/EasyTransitioning
EasyTransitioning/Classes/ETElement.swift
1
1276
// // ETElement.swift // EasyTransitioning // // Created by Jerry Yu on 2016-11-12. // Copyright © 2016 Jerry Yu. All rights reserved. // import UIKit public struct ETElement { public var actions: [ETAction] internal var snapshotView: UIView? init(view: UIView, actions: [ETAction] = [], shouldSnapshot: Bool = true) { self.actions = actions self.snapshotView = shouldSnapshot ? view.snapshotView(afterScreenUpdates: true) : view snapshotView?.frame = view.superview?.convert(view.frame, to: nil) ?? view.frame } init(view: UIView, action: ETAction) { self.init(view: view, actions: [action]) } fileprivate init(actions: [ETAction], snapshotView: UIView?) { self.actions = actions self.snapshotView = snapshotView } public func reversed() -> ETElement { let reversedActions = actions.map{ $0.reversed() } return ETElement(actions: reversedActions, snapshotView: snapshotView) } } public extension UIView { func easyTransition(_ actions: [ETAction], shouldSnapshot: Bool = true) -> ETElement { return ETElement(view: self, actions: actions, shouldSnapshot: shouldSnapshot) } func easyTransition(_ action: ETAction, shouldSnapshot: Bool = true) -> ETElement { return easyTransition([action], shouldSnapshot: shouldSnapshot) } }
mit
8a4e2f413969dcc3475f04a8aad9015e
26.12766
89
0.723922
3.581461
false
false
false
false
ZackKingS/Tasks
task/Classes/Others/Lib/TakePhoto/PhotoPreviewViewController.swift
2
6969
// // PhotoPreviewViewController.swift // PhotoPicker // // Created by liangqi on 16/3/8. // Copyright © 2016年 dailyios. All rights reserved. // import UIKit import Photos class PhotoPreviewViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,PhotoPreviewBottomBarViewDelegate,PhotoPreviewToolbarViewDelegate,PhotoPreviewCellDelegate { var allSelectImage: PHFetchResult<AnyObject>? var collectionView: UICollectionView? var currentPage: Int = 1 let cellIdentifier = "PhotoPreviewCell" weak var fromDelegate: PhotoCollectionViewControllerDelegate? private var toolbar: PhotoPreviewToolbarView? private var bottomBar: PhotoPreviewBottomBarView? private var isAnimation = false override func viewDidLoad() { super.viewDidLoad() self.configCollectionView() self.configToolbar() } private func configToolbar(){ self.toolbar = PhotoPreviewToolbarView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50)) self.toolbar?.delegate = self self.toolbar?.sourceDelegate = self let positionY = self.view.bounds.height - 50 self.bottomBar = PhotoPreviewBottomBarView(frame: CGRect(x: 0,y: positionY,width: self.view.bounds.width,height: 50)) self.bottomBar?.delegate = self self.bottomBar?.changeNumber(number: PhotoImage.instance.selectedImage.count, animation: false) self.view.addSubview(toolbar!) self.view.addSubview(bottomBar!) } // MARK: - delegate func onDoneButtonClicked() { if let nav = self.navigationController as? PhotoPickerController { nav.imageSelectFinish() } } // MARK: - from page delegate func onToolbarBackArrowClicked() { _ = self.navigationController?.popViewController(animated: true) if let delegate = self.fromDelegate { delegate.onPreviewPageBack() } } func onSelected(select: Bool) { let currentModel = self.allSelectImage![self.currentPage] if select { PhotoImage.instance.selectedImage.append(currentModel as! PHAsset) } else { if let index = PhotoImage.instance.selectedImage.index(of: currentModel as! PHAsset){ PhotoImage.instance.selectedImage.remove(at: index) } } self.bottomBar?.changeNumber(number: PhotoImage.instance.selectedImage.count, animation: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // fullscreen controller self.navigationController?.isNavigationBarHidden = true UIApplication.shared.setStatusBarHidden(true, with: .none) self.collectionView?.setContentOffset(CGPoint(x: CGFloat(self.currentPage) * self.view.bounds.width, y: 0), animated: false) self.changeCurrentToolbar() } func configCollectionView(){ self.automaticallyAdjustsScrollViewInsets = false let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: self.view.frame.width,height: self.view.frame.height) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) self.collectionView!.backgroundColor = UIColor.black self.collectionView!.dataSource = self self.collectionView!.delegate = self self.collectionView!.isPagingEnabled = true self.collectionView!.scrollsToTop = false self.collectionView!.showsHorizontalScrollIndicator = false self.collectionView!.contentOffset = CGPoint.zero self.collectionView!.contentSize = CGSize(width: self.view.bounds.width * CGFloat(self.allSelectImage!.count), height: self.view.bounds.height) self.view.addSubview(self.collectionView!) self.collectionView!.register(PhotoPreviewCell.self, forCellWithReuseIdentifier: self.cellIdentifier) } // MARK: - collectionView dataSource delagate func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.allSelectImage!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellIdentifier, for: indexPath as IndexPath) as! PhotoPreviewCell cell.delegate = self if let asset = self.allSelectImage![indexPath.row] as? PHAsset { cell.renderModel(asset: asset) } return cell } // MARK: - Photo Preview Cell Delegate func onImageSingleTap() { if self.isAnimation { return } self.isAnimation = true if self.toolbar!.frame.origin.y < 0 { UIView.animate(withDuration: 0.3, delay: 0, options: [UIViewAnimationOptions.curveEaseOut], animations: { () -> Void in self.toolbar!.frame.origin = CGPoint.zero var originPoint = self.bottomBar!.frame.origin originPoint.y = originPoint.y - self.bottomBar!.frame.height self.bottomBar!.frame.origin = originPoint }, completion: { (isFinished) -> Void in if isFinished { self.isAnimation = false } }) } else { UIView.animate(withDuration: 0.3, delay: 0, options: [UIViewAnimationOptions.curveEaseOut], animations: { () -> Void in self.toolbar!.frame.origin = CGPoint(x:0, y: -self.toolbar!.frame.height) var originPoint = self.bottomBar!.frame.origin originPoint.y = originPoint.y + self.bottomBar!.frame.height self.bottomBar!.frame.origin = originPoint }, completion: { (isFinished) -> Void in if isFinished { self.isAnimation = false } }) } } // MARK: - scroll page func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset self.currentPage = Int(offset.x / self.view.bounds.width) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.changeCurrentToolbar() } private func changeCurrentToolbar(){ let model = self.allSelectImage![self.currentPage] as! PHAsset if let _ = PhotoImage.instance.selectedImage.index(of: model){ self.toolbar!.setSelect(select: true) } else { self.toolbar!.setSelect(select: false) } } }
apache-2.0
0c69019a625780f024169c02fd537a6f
38.355932
195
0.645564
5.148559
false
false
false
false
davecom/SwiftGraph
Sources/SwiftGraph/SwiftPriorityQueue.swift
2
6822
// // SwiftPriorityQueue.swift // SwiftPriorityQueue // // Copyright (c) 2015-2019 David Kopec // // 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. // This code was inspired by Section 2.4 of Algorithms by Sedgewick & Wayne, 4th Edition /// A PriorityQueue takes objects to be pushed of any type that implements Comparable. /// It will pop the objects in the order that they would be sorted. A pop() or a push() /// can be accomplished in O(lg n) time. It can be specified whether the objects should /// be popped in ascending or descending order (Max Priority Queue or Min Priority Queue) /// at the time of initialization. public struct PriorityQueue<T: Comparable> { fileprivate var heap = [T]() private let ordered: (T, T) -> Bool public init(ascending: Bool = false, startingValues: [T] = []) { self.init(order: ascending ? { $0 > $1 } : { $0 < $1 }, startingValues: startingValues) } /// Creates a new PriorityQueue with the given ordering. /// /// - parameter order: A function that specifies whether its first argument should /// come after the second argument in the PriorityQueue. /// - parameter startingValues: An array of elements to initialize the PriorityQueue with. public init(order: @escaping (T, T) -> Bool, startingValues: [T] = []) { ordered = order // Based on "Heap construction" from Sedgewick p 323 heap = startingValues var i = heap.count/2 - 1 while i >= 0 { sink(i) i -= 1 } } /// How many elements the Priority Queue stores public var count: Int { return heap.count } /// true if and only if the Priority Queue is empty public var isEmpty: Bool { return heap.isEmpty } /// Add a new element onto the Priority Queue. O(lg n) /// /// - parameter element: The element to be inserted into the Priority Queue. public mutating func push(_ element: T) { heap.append(element) swim(heap.count - 1) } /// Remove and return the element with the highest priority (or lowest if ascending). O(lg n) /// /// - returns: The element with the highest priority in the Priority Queue, or nil if the PriorityQueue is empty. public mutating func pop() -> T? { if heap.isEmpty { return nil } if heap.count == 1 { return heap.removeFirst() } // added for Swift 2 compatibility // so as not to call swap() with two instances of the same location heap.swapAt(0, heap.count - 1) let temp = heap.removeLast() sink(0) return temp } /// Removes the first occurence of a particular item. Finds it by value comparison using ==. O(n) /// Silently exits if no occurrence found. /// /// - parameter item: The item to remove the first occurrence of. public mutating func remove(_ item: T) { if let index = heap.firstIndex(of: item) { heap.swapAt(index, heap.count - 1) heap.removeLast() swim(index) sink(index) } } /// Removes all occurences of a particular item. Finds it by value comparison using ==. O(n) /// Silently exits if no occurrence found. /// /// - parameter item: The item to remove. public mutating func removeAll(_ item: T) { var lastCount = heap.count remove(item) while (heap.count < lastCount) { lastCount = heap.count remove(item) } } /// Get a look at the current highest priority item, without removing it. O(1) /// /// - returns: The element with the highest priority in the PriorityQueue, or nil if the PriorityQueue is empty. public func peek() -> T? { return heap.first } /// Eliminate all of the elements from the Priority Queue. public mutating func clear() { heap.removeAll(keepingCapacity: false) } // Based on example from Sedgewick p 316 private mutating func sink(_ index: Int) { var index = index while 2 * index + 1 < heap.count { var j = 2 * index + 1 if j < (heap.count - 1) && ordered(heap[j], heap[j + 1]) { j += 1 } if !ordered(heap[index], heap[j]) { break } heap.swapAt(index, j) index = j } } // Based on example from Sedgewick p 316 private mutating func swim(_ index: Int) { var index = index while index > 0 && ordered(heap[(index - 1) / 2], heap[index]) { heap.swapAt((index - 1) / 2, index) index = (index - 1) / 2 } } } // MARK: - GeneratorType extension PriorityQueue: IteratorProtocol { public typealias Element = T mutating public func next() -> Element? { return pop() } } // MARK: - SequenceType extension PriorityQueue: Sequence { public typealias Iterator = PriorityQueue public func makeIterator() -> Iterator { return self } } // MARK: - CollectionType extension PriorityQueue: Collection { public typealias Index = Int public var startIndex: Int { return heap.startIndex } public var endIndex: Int { return heap.endIndex } public subscript(i: Int) -> T { return heap[i] } public func index(after i: PriorityQueue.Index) -> PriorityQueue.Index { return heap.index(after: i) } } // MARK: - CustomStringConvertible, CustomDebugStringConvertible extension PriorityQueue: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return heap.description } public var debugDescription: String { return heap.debugDescription } }
apache-2.0
486709919ff8576e5b28cb6bac2b67e7
35.677419
117
0.633392
4.485207
false
false
false
false
ReSwift/ReSwift-Todo-Example
ReSwift-Todo/ToDoListPresenter.swift
1
910
// // ToDoListPresenter.swift // ReSwift-Todo // // Created by Christian Tietze on 30/01/16. // Copyright © 2016 ReSwift. All rights reserved. // import Foundation import ReSwift class ToDoListPresenter { typealias View = DisplaysToDoList let view: View init(view: View) { self.view = view } } extension ToDoViewModel { init(toDo: ToDo) { self.identifier = toDo.toDoID.identifier self.title = toDo.title self.checked = toDo.isFinished } } extension ToDoListPresenter: StoreSubscriber { func newState(state: ToDoListState) { let itemViewModels = state.toDoList.items.map(ToDoViewModel.init) let viewModel = ToDoListViewModel( title: state.toDoList.title ?? "", items: itemViewModels, selectedRow: state.selection) view.displayToDoList(toDoListViewModel: viewModel) } }
mit
6a10cff9d39e0d1b11f7e961c533ef3f
18.76087
73
0.654565
4.169725
false
false
false
false