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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
superk589/DereGuide | DereGuide/Unit/Editing/Controller/UnitTemplateController.swift | 2 | 3907 | //
// UnitTemplateController.swift
// DereGuide
//
// Created by zzk on 2017/6/12.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import CoreData
protocol UnitTemplateControllerDelegate: class {
func unitTemplateController(_ unitTemplateController: UnitTemplateController, didSelect unit: Unit)
}
class UnitTemplateController: BaseTableViewController {
weak var delegate: UnitTemplateControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("队伍模板", comment: "")
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 99
tableView.register(UnitTemplateCell.self, forCellReuseIdentifier: UnitTemplateCell.description())
tableView.tableFooterView = UIView()
loadUnitTemplates()
// Do any additional setup after loading the view.
}
var parentContext: NSManagedObjectContext? {
didSet {
context = parentContext?.newChildContext()
}
}
private var context: NSManagedObjectContext?
private var templates = [UnitTemplate]()
private func loadUnitTemplates() {
guard let context = context else {
fatalError("parent context not set")
}
if let path = Bundle.main.path(forResource: "UnitTemplate", ofType: "plist") {
if let dict = NSDictionary(contentsOfFile: path) as? [String: [Any]] {
for (name, array) in dict {
var members = [Member]()
for id in array {
if let subDict = id as? [String: Any] {
if let id = subDict["id"] as? Int, let potentials = subDict["potential"] as? [String: Int] {
let member = Member.insert(into: context, cardID: id, skillLevel: 10, potential: Potential(vocal: potentials["vocalLevel"]!, dance: potentials["danceLevel"]!, visual: potentials["visualLevel"]!, skill: 0, life: 0))
members.append(member)
}
} else if let id = id as? Int {
let card = CGSSDAO.shared.findCardById(id)
let member = Member.insert(into: context, cardID: id, skillLevel: 10, potential: card?.properPotential ?? .zero)
members.append(member)
}
}
guard members.count == 6 else {
continue
}
let unit = Unit.insert(into: context, customAppeal: 0, supportAppeal: Config.maximumSupportAppeal, usesCustomAppeal: false, members: members)
let template = UnitTemplate(name: name, unit: unit)
templates.append(template)
}
reloadUI()
}
}
}
private func reloadUI() {
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return templates.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.unitTemplateController(self, didSelect: templates[indexPath.row].unit)
navigationController?.popViewController(animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UnitTemplateCell.description(), for: indexPath) as! UnitTemplateCell
cell.setup(with: templates[indexPath.row].name, unit: templates[indexPath.row].unit)
return cell
}
}
| mit | 25de526769d2583a00535f1abc1df1d7 | 40.031579 | 246 | 0.601334 | 5.246299 | false | false | false | false |
jessesquires/JSQCoreDataKit | Tests/SaveTests.swift | 1 | 11418 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015-present Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
@testable import JSQCoreDataKit
import XCTest
final class SaveTests: TestCase {
func test_ThatSaveAndWait_WithoutChanges_CompletionHandlerIsNotCalled() {
// GIVEN: a stack and context without changes
var didCallCompletion = false
// WHEN: we attempt to save the context
// THEN: the save operation is ignored
self.inMemoryStack.mainContext.saveSync { _ in
didCallCompletion = true
}
XCTAssertFalse(didCallCompletion, "Save should be ignored")
}
func test_ThatSaveAndWait_WithChangesSucceeds_CompletionHandlerIsCalled() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.mainContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
var didSaveMain = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didSaveMain = true
return true
}
var didUpdateBackground = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didUpdateBackground = true
return true
}
let saveExpectation = self.expectation(description: #function)
// WHEN: we attempt to save the context
self.inMemoryStack.mainContext.saveSync { result in
// THEN: the save succeeds without an error
XCTAssertNotNil(try? result.get(), "Save should not error")
saveExpectation.fulfill()
}
// THEN: then the main and background contexts are saved and the completion handler is called
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveMain, "Main context should be saved")
XCTAssertTrue(didUpdateBackground, "Background context should be updated")
}
}
func test_ThatSaveAndWait_WithChanges_WithoutCompletionClosure_Succeeds() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.mainContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
var didSaveMain = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didSaveMain = true
return true
}
var didUpdateBackground = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didUpdateBackground = true
return true
}
// WHEN: we attempt to save the context
// THEN: the save succeeds without an error
self.inMemoryStack.mainContext.saveSync()
// THEN: then the main and background contexts are saved
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveMain, "Main context should be saved")
XCTAssertTrue(didUpdateBackground, "Background context should be updated")
}
}
func test_ThatSaveAsync_WithoutChanges_ReturnsImmediately() {
// GIVEN: a stack and context without changes
var didCallCompletion = false
// WHEN: we attempt to save the context asynchronously
self.inMemoryStack.mainContext.saveAsync { _ in
didCallCompletion = true
}
// THEN: the save operation is ignored
XCTAssertFalse(didCallCompletion, "Save should be ignored")
}
func test_ThatSaveAsync_WithChanges_Succeeds() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.mainContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
var didSaveMain = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didSaveMain = true
return true
}
var didUpdateBackground = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didUpdateBackground = true
return true
}
let saveExpectation = self.expectation(description: #function)
// WHEN: we attempt to save the context asynchronously
self.inMemoryStack.mainContext.saveAsync { result in
// THEN: the save succeeds without an error
XCTAssertNotNil(try? result.get(), "Save should not error")
saveExpectation.fulfill()
}
// THEN: then the main and background contexts are saved and the completion handler is called
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveMain, "Main context should be saved")
XCTAssertTrue(didUpdateBackground, "Background context should be updated")
}
}
func test_ThatSavingChildContext_SucceedsAndSavesParentMainContext() {
// GIVEN: a stack and child context with changes
let childContext = self.inMemoryStack.childContext(concurrencyType: .mainQueueConcurrencyType)
childContext.performAndWait {
self.generateCompaniesInContext(childContext, count: 3)
}
var didSaveChild = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: childContext) { _ -> Bool in
didSaveChild = true
return true
}
var didSaveMain = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didSaveMain = true
return true
}
var didUpdateBackground = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didUpdateBackground = true
return true
}
let saveExpectation = self.expectation(description: #function)
// WHEN: we attempt to save the context
childContext.saveSync { result in
// THEN: the save succeeds without an error
XCTAssertNotNil(try? result.get(), "Save should not error")
saveExpectation.fulfill()
}
// THEN: then all contexts are saved, synchronized and the completion handler is called
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveChild, "Child context should be saved")
XCTAssertTrue(didSaveMain, "Main context should be saved")
XCTAssertTrue(didUpdateBackground, "Background context should be updated")
}
}
func test_ThatSavingChildContext_SucceedsAndSavesParentBackgroundContext() {
// GIVEN: a stack and child context with changes
let childContext = self.inMemoryStack.childContext(concurrencyType: .privateQueueConcurrencyType)
childContext.performAndWait {
self.generateCompaniesInContext(childContext, count: 3)
}
var didSaveChild = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: childContext) { _ -> Bool in
didSaveChild = true
return true
}
var didSaveBackground = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didSaveBackground = true
return true
}
var didUpdateMain = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didUpdateMain = true
return true
}
let saveExpectation = self.expectation(description: #function)
// WHEN: we attempt to save the context
childContext.saveSync { result in
// THEN: the save succeeds without an error
XCTAssertNotNil(try? result.get(), "Save should not error")
saveExpectation.fulfill()
}
// THEN: then all contexts are saved, synchronized and the completion handler is called
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveChild, "Child context should be saved")
XCTAssertTrue(didSaveBackground, "Background context should be saved")
XCTAssertTrue(didUpdateMain, "Main context should be updated")
}
}
func test_ThatSavingBackgroundContext_SucceedsAndUpdateMainContext() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.backgroundContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
var didSaveBackground = false
self.expectation(forNotification: .NSManagedObjectContextDidSave,
object: self.inMemoryStack.backgroundContext) { _ -> Bool in
didSaveBackground = true
return true
}
var didUpdateMain = false
self.expectation(forNotification: .NSManagedObjectContextObjectsDidChange,
object: self.inMemoryStack.mainContext) { _ -> Bool in
didUpdateMain = true
return true
}
let saveExpectation = self.expectation(description: #function)
// WHEN: we attempt to save the context asynchronously
self.inMemoryStack.backgroundContext.saveAsync { result in
// THEN: the save succeeds without an error
XCTAssertNotNil(try? result.get(), "Save should not error")
saveExpectation.fulfill()
}
// THEN: then the main and background contexts are saved and the completion handler is called
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
XCTAssertTrue(didSaveBackground, "Background context should be saved")
XCTAssertTrue(didUpdateMain, "Main context should be updated")
}
}
}
| mit | 9d033caedacf378dbaa3f078e461925e | 37.570946 | 105 | 0.644127 | 5.845878 | false | false | false | false |
mortorqrobotics/Morganizer-ios | Morganizer/ConvoViewController.swift | 2 | 3181 | //
// FirstViewController.swift
// Morganizer
//
// Created by Farbod Rafezy on 6/12/15.
// Copyright (c) 2015 mortorq. All rights reserved.
//
import UIKit
class ConvoViewController: UIViewController, LGChatControllerDelegate {
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
var otherUsername:String!
var name:String!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var navName: UINavigationItem!
/* func launchChatController() {
let chatController = LGChatController()
chatController.opponentImage = UIImage(named: "User")
chatController.title = "Simple Chat"
let helloWorld = LGChatMessage(content: "Hello World!", sentBy: .User)
chatController.messages = [helloWorld]
chatController.delegate = self
self.navigationController?.pushViewController(chatController, animated: true)
}
// MARK: LGChatControllerDelegate
func chatController(chatController: LGChatController, didAddNewMessage message: LGChatMessage) {
println("Did Add Message: \(message.content)")
}
*/
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
func shouldChatController(chatController: LGChatController, addMessage message: LGChatMessage) -> Bool {
/*
Use this space to prevent sending a message, or to alter a message. For example, you might want to hold a message until its successfully uploaded to a server.
*/
return true
}
override func viewDidLoad() {
//
setTabBarVisible(false, animated: false);
//self.launchChatController();
usernameLabel.text = otherUsername;
navName.title = name;
super.viewDidLoad()
}
override func viewWillDisappear(animated : Bool) {
super.viewWillDisappear(animated)
setTabBarVisible(true, animated: false);
//if (self.isMovingFromParentViewController){
println("left");
//}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | e2d74f5ea5d31765998301036236f13d | 32.484211 | 167 | 0.641622 | 5.065287 | false | false | false | false |
TransitionKit/Union | Union/Navigator.swift | 1 | 3070 | //
// Navigator.swift
// Union
//
// Created by Hirohisa Kawasaki on 10/7/15.
// Copyright © 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public class Navigator: NSObject {
let before = AnimationManager()
let present = AnimationManager()
var duration: NSTimeInterval {
return before.duration + present.duration
}
func animate(transitionContext: UIViewControllerContextTransitioning) {
setup(transitionContext)
start(transitionContext)
}
public class func animate() -> UIViewControllerAnimatedTransitioning {
return Navigator()
}
}
extension Navigator: UIViewControllerAnimatedTransitioning {
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
animate(transitionContext)
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
}
extension Navigator {
func setup(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
if let fromViewController = fromViewController, let toViewController = toViewController {
_setup(fromViewController: fromViewController, toViewController: toViewController)
}
}
func start(transitionContext: UIViewControllerContextTransitioning) {
before.completion = { [unowned self] in
self.startTransition(transitionContext)
}
before.start()
}
func startTransition(transitionContext: UIViewControllerContextTransitioning) {
if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey), let toView = transitionContext.viewForKey(UITransitionContextToViewKey) {
toView.frame = fromView.frame
transitionContext.containerView()?.insertSubview(toView, aboveSubview: fromView)
}
present.completion = {
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
fromView?.removeFromSuperview()
transitionContext.completeTransition(true)
}
present.start()
}
private func _setup(fromViewController fromViewController: UIViewController, toViewController: UIViewController) {
if let delegate = fromViewController as? Delegate {
before.animations = delegate.animationsBeforeTransition(from: fromViewController, to: toViewController)
}
// present
let fromAnimations: [Animation] = (fromViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
let toAnimations: [Animation] = (toViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
present.animations = fromAnimations + toAnimations
}
} | mit | 90464c9777051b0af22eb239374d0b20 | 34.287356 | 161 | 0.72825 | 6.420502 | false | false | false | false |
TeamDeverse/BC-Agora | BC-Agora/ViewController.swift | 1 | 5377 | //
// ViewController.swift
// BC-Agora
//
// Created by William Bowditch on 11/13/15.
// Copyright © 2015 William Bowditch. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
@IBOutlet var bcLogo: UIImageView!
@IBOutlet var user: UITextField!
@IBOutlet var password: UITextField!
@IBOutlet var wrongUser: UILabel!
@IBOutlet var wrongPassword: UILabel!
var json_dict = [:]
override func viewDidLoad() {
super.viewDidLoad()
bcLogo.image = UIImage(named: "BostonCollegeEagles.svg")
print("hello")
let json_data = getJSON("https://raw.githubusercontent.com/TeamDeverse/BC-Agora/master/user_example.json")
json_dict = getJSON_dict(json_data)
//checkLogin()
//self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Georgia", size: 20)! ]
navigationController!.navigationBar.barTintColor = UIColor(red: 0.5, green: 0.1, blue: 0.1, alpha: 1)
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Georgia-Bold", size: 20)!]
self.navigationController!.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject]
//self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Georgia", size: 20)!]
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
//avigationController?.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject]
let cornerRadius : CGFloat = 5.0
let borderAlpha : CGFloat = 0.7
user.layer.borderWidth = 1.0
user.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
user.layer.cornerRadius = cornerRadius
user.backgroundColor = UIColor.clearColor()
password.layer.borderWidth = 1.0
password.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
password.layer.cornerRadius = cornerRadius
password.backgroundColor = UIColor.clearColor()
// Do any additional setup after loading the view, typically from a nib.
// self.view.backgroundColor = UIColor(patternImage: UIImage(named: "gasson")!)
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "gasson")?.drawInRect(self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
let imageView = UIImageView(image: image)
imageView.alpha = 0.9
UIGraphicsEndImageContext()
self.view.insertSubview(imageView, atIndex: 0)
//self.view.addSubview(imageView)
print("test1")
button.frame = CGRectMake(100, 100, 200, 40)
button.setTitle("Login", forState: UIControlState.Normal)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.clearColor()
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
button.layer.cornerRadius = cornerRadius
//self.view.backgroundColor = UIColor(patternImage: image) //.colorWithAlphaComponent(0.7)//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getJSON(urlToRequest: String) -> NSData{
return NSData(contentsOfURL: NSURL(string: urlToRequest)!)!
}
func getJSON_dict(json_data: NSData) -> NSDictionary {
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(json_data, options: []) as? NSDictionary {
return jsonResult
//let k = jsonResult.allKeys
//print(k)
}
} catch {
print(error)
}
return [:]
}
@IBAction func pressLogin(sender: AnyObject) {
self.wrongPassword.text?.removeAll()
self.wrongUser.text?.removeAll()
checkLogin()
}
func loadUserDefault() {
//NSUser Default
//PS file
//run code before checkLogin code
}
func checkLogin(){
let user_data = json_dict["username"] as! String
let pass_data = json_dict["password"]as! String
print(user_data)
print(pass_data)
if self.user.text == "" {
wrongUser.text = "Please enter a username."
}
if self.password.text == "" {
wrongPassword.text = "Please enter a password."
}
if self.password.text != pass_data {
wrongPassword.text = "Incorrect password"
}
if self.user.text! == user_data && self.password.text! == pass_data {
print("correct")
self.performSegueWithIdentifier("loginSegue", sender: nil)
}
else{
print(self.password.text)
//print(pass_data)
}
print("working")
}
}
| mit | 8b9b1901bbe76db5f1fdf16891842d9d | 31.780488 | 154 | 0.606399 | 4.973173 | false | false | false | false |
bitjammer/swift | stdlib/public/core/SwiftNativeNSArray.swift | 1 | 10036 | //===--- SwiftNativeNSArray.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
//
//===----------------------------------------------------------------------===//
//
// _ContiguousArrayStorageBase supplies the implementation of the
// _NSArrayCore API (and thus, NSArray the API) for our
// _ContiguousArrayStorage<T>. We can't put this implementation
// directly on _ContiguousArrayStorage because generic classes can't
// override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// ≤ index ≤ count`.
@_versioned
@_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index <= count)
}
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@_versioned
@_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
@_versioned
internal class _SwiftNativeNSArrayWithContiguousStorage
: _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
// Operate on our contiguous storage
@_inlineable
@_versioned
internal func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
_sanityCheckFailure(
"Must override withUnsafeBufferOfObjects in derived classes")
}
}
// Implement the APIs required by NSArray
extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
@_inlineable
@_versioned
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@_inlineable
@_versioned
@objc(objectAtIndex:)
internal func objectAt(_ index: Int) -> AnyObject {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, count: objects.count),
"Array index out of range")
return objects[index]
}
}
@_inlineable
@_versioned
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyBytes(
from: objects.baseAddress! + range.location,
count: range.length * MemoryLayout<AnyObject>.stride)
}
}
@_inlineable
@_versioned
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}
}
@_inlineable
@_versioned
@objc(copyWithZone:)
internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return self
}
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@_versioned
@objc internal final class _SwiftDeferredNSArray
: _SwiftNativeNSArrayWithContiguousStorage {
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@_versioned
internal var _heapBufferBridged_DoNotUse: AnyObject?
// When this class is allocated inline, this property can become a
// computed one.
@_versioned
internal let _nativeStorage: _ContiguousArrayStorageBase
@_inlineable
@_versioned
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject>
@_inlineable
@_versioned
internal var _heapBufferBridged: HeapBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
return unsafeBitCast(ref, to: HeapBufferStorage.self)
}
return nil
}
@_versioned
internal init(_nativeStorage: _ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
@_inlineable
@_versioned
internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) {
if let bridgedStorage = hb {
let heapBuffer = _HeapBuffer(bridgedStorage)
let count = heapBuffer.value
heapBuffer.baseAddress.deinitialize(count: count)
}
}
deinit {
_destroyBridgedStorage(_heapBufferBridged)
}
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
while true {
var buffer: UnsafeBufferPointer<AnyObject>
// If we've already got a buffer of bridged objects, just use it
if let bridgedStorage = _heapBufferBridged {
let heapBuffer = _HeapBuffer(bridgedStorage)
buffer = UnsafeBufferPointer(
start: heapBuffer.baseAddress, count: heapBuffer.value)
}
// If elements are bridged verbatim, the native buffer is all we
// need, so return that.
else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
{ $0 }
) {
buffer = buf
}
else {
// Create buffer of bridged objects.
let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer()
// Atomically store a reference to that buffer in self.
if !_stdlib_atomicInitializeARCRef(
object: _heapBufferBridgedPtr, desired: objects.storage!) {
// Another thread won the race. Throw out our buffer.
_destroyBridgedStorage(
unsafeDowncast(objects.storage!, to: HeapBufferStorage.self))
}
continue // Try again
}
defer { _fixLifetime(self) }
return try body(buffer)
}
}
/// Returns the number of elements in the array.
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@_inlineable
@_versioned
@objc
internal override var count: Int {
if let bridgedStorage = _heapBufferBridged {
return _HeapBuffer(bridgedStorage).value
}
// Check if elements are bridged verbatim.
return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count }
?? _nativeStorage._getNonVerbatimBridgedCount()
}
}
#else
// Empty shim version for non-objc platforms.
@_versioned
class _SwiftNativeNSArrayWithContiguousStorage {
@_inlineable
@_versioned
init() {}
}
#endif
/// Base class of the heap buffer backing arrays.
@_versioned
@_fixed_layout
internal class _ContiguousArrayStorageBase
: _SwiftNativeNSArrayWithContiguousStorage {
@_versioned
final var countAndCapacity: _ArrayBody
init(_doNotCallMeBase: ()) {
_sanityCheckFailure("creating instance of _ContiguousArrayStorageBase")
}
#if _runtime(_ObjC)
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
return result
}
_sanityCheckFailure(
"Can't use a buffer of non-verbatim-bridged elements as an NSArray")
}
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
@_versioned
internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
_sanityCheckFailure(
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
@_versioned
internal func _getNonVerbatimBridgedCount() -> Int {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedCount")
}
@_versioned
internal func _getNonVerbatimBridgedHeapBuffer() ->
_HeapBuffer<Int, AnyObject> {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer")
}
#endif
@_versioned
func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
_sanityCheckFailure(
"Concrete subclasses must implement canStoreElements(ofDynamicType:)")
}
/// A type that every element in the array is.
@_versioned
var staticElementType: Any.Type {
_sanityCheckFailure(
"Concrete subclasses must implement staticElementType")
}
deinit {
_sanityCheck(
self !== _emptyArrayStorage, "Deallocating empty array storage?!")
}
}
| apache-2.0 | 26cd53ae104a7d9f5d16d2ac02717e0e | 29.12012 | 80 | 0.684048 | 5.117347 | false | false | false | false |
exponent/exponent | ios/versioned/sdk44/ExpoModulesCore/Swift/Records/FieldOption.swift | 4 | 1664 | /**
Enum-like struct representing field options that for example can specify if the field
is required and so it must be provided by the dictionary from which the field is created.
*/
public struct FieldOption: Equatable, Hashable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral {
public let rawValue: Int
public var key: String?
public init(_ rawValue: Int) {
self.rawValue = rawValue
}
// MARK: `Equatable`
/**
Field options are equal when their raw values and parameters are equal.
*/
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue == rhs.rawValue && lhs.key == rhs.key
}
// MARK: `Hashable`
/**
The options can be stored in `Set` which uses `hashValue` as a unique identifier.
*/
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
// MARK: `ExpressibleByIntegerLiteral`
/**
Initializer that allows to create an instance from int literal.
*/
public init(integerLiteral value: Int) {
self.rawValue = value
}
// MARK: `ExpressibleByStringLiteral`
/**
Initializer that allows to create an instance from string literal.
*/
public init(stringLiteral value: String) {
self.rawValue = 0
self.key = value
}
}
public extension FieldOption {
/**
Field option setting its key to given string. Raw value equals to `0`.
This option can also be initialized with string literal.
*/
static func keyed(_ key: String) -> FieldOption { FieldOption(stringLiteral: key) }
/**
The field must be explicitly provided by the dictionary. Raw value equals to `1`.
*/
static let required: FieldOption = 1
}
| bsd-3-clause | 18bc5bd8007bcb5601fba57a069ac279 | 25.83871 | 105 | 0.692909 | 4.461126 | false | false | false | false |
jenasubodh/tasky-ios | Tasky/Endpoints.swift | 1 | 4025 | //
// Endpoints.swift
// Tasky
//
// Created by Subodh Jena on 04/04/17.
// Copyright © 2017 Subodh Jena. All rights reserved.
//
import Foundation
import Alamofire
enum Endpoints {
enum Auth: EndpointProtocol {
case Login()
var method: HTTPMethod {
switch self {
case .Login:
return .post
}
}
public var path: String {
switch self {
case .Login:
return "auth"
}
}
var url: String {
let baseUrl = API.baseUrl
switch self {
case .Login:
return "\(baseUrl)\(path)"
}
}
}
enum Users: EndpointProtocol {
case GetUsers()
case GetUser(userId: String)
case CreateUser()
case UpdateUser(userId: String)
case DeleteUser(userId: String)
var method: HTTPMethod {
switch self {
case .GetUsers:
return .get
case .GetUser:
return .get
case .CreateUser:
return .post
case .UpdateUser:
return .put
case .DeleteUser:
return .delete
}
}
public var path: String {
switch self {
case .GetUsers:
return "users"
case .GetUser(let userId):
return "users/\(userId)"
case .CreateUser:
return "users"
case .UpdateUser(let userId):
return "users/\(userId)"
case .DeleteUser(let userId):
return "users/\(userId)"
}
}
var url: String {
let baseUrl = API.baseUrl
switch self {
case .GetUsers:
return "\(baseUrl)\(path)"
case .GetUser:
return "\(baseUrl)\(path)"
case .CreateUser:
return "\(baseUrl)\(path)"
case .UpdateUser:
return "\(baseUrl)\(path)"
case .DeleteUser:
return "\(baseUrl)\(path)"
}
}
}
enum Tasks: EndpointProtocol {
case GetTasks(authKey: String)
case GetTask(authKey: String, taskId: String)
case CreateTask()
case UpdateTask(taskId: String)
case DeleteTask(taskId: String)
var method: HTTPMethod {
switch self {
case .GetTasks:
return .get
case .GetTask:
return .get
case .CreateTask:
return .post
case .UpdateTask:
return .put
case .DeleteTask:
return .delete
}
}
public var path: String {
switch self {
case .GetTasks(let authKey):
return "tasks?access_token=\(authKey)"
case .GetTask(let authKey, let taskId):
return "tasks/\(taskId)?access_token=\(authKey)"
case .CreateTask:
return "tasks"
case .UpdateTask(let taskId):
return "tasks/\(taskId)"
case .DeleteTask(let taskId):
return "tasks/\(taskId)"
}
}
var url: String {
let baseUrl = API.baseUrl
switch self {
case .GetTasks:
return "\(baseUrl)\(path)"
case .GetTask:
return "\(baseUrl)\(path)"
case .CreateTask:
return "\(baseUrl)\(path)"
case .UpdateTask:
return "\(baseUrl)\(path)"
case .DeleteTask:
return "\(baseUrl)\(path)"
}
}
}
}
| mit | 5a663029e1c44c882984979ba4e9d63d | 24.794872 | 64 | 0.427187 | 5.5427 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | Sources/CoreAPI/Models/CoreAPI_PagedPublication.swift | 1 | 14318 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import UIKit
extension CoreAPI {
/// A `PagedPublication` is a catalog that has static images for each `Page`, with possible `Hotspot`s referencing `Offer`s on each page, that is published by a `Dealer`.
public struct PagedPublication: Decodable, Equatable {
public typealias Identifier = PagedPublicationCoreAPIIdentifier
public enum PublicationType: String, Codable {
case paged
case incito
}
/// The unique identifier of this PagedPublication.
public var id: Identifier
/// The name of the publication. eg. "Christmas Special".
public var label: String?
/// How many pages this publication has.
public var pageCount: Int
/// How many `Offer`s are in this publication.
public var offerCount: Int
/// The range of dates that this publication is valid from and until.
public var runDateRange: Range<Date>
/// The ratio of width to height for the page-images. So if an image is (w:100, h:200), the aspectRatio is 0.5 (width/height).
public var aspectRatio: Double
/// The branding information for the publication's dealer.
public var branding: Branding
/// A set of URLs for the different sized images for the cover of the publication.
public var frontPageImages: ImageURLSet
/// Whether this publication is available in all stores, or just in a select few stores.
public var isAvailableInAllStores: Bool
/// The unique identifier of the dealer that published this publication.
public var dealerId: CoreAPI.Dealer.Identifier
/// The unique identifier of the nearest store. This will only contain a value if the `PagedPublication` was fetched with a request that includes store information (eg. one that takes a precise location as a parameter).
public var storeId: CoreAPI.Store.Identifier?
/// The unique identifier of the Incito Publication related this PagedPublication
public var incitoId: IncitoGraphIdentifier?
/// Defines what types of publication this represents.
/// If it contains `paged`, the `id` can be used to view this in a PagedPublicationViewer
/// If it contains `incito`, the `incitoId` will always have a value, and it can be viewed with the IncitoViewer
/// If it ONLY contains `incito`, this cannot be viewed in a PagedPublicationViewer (see `isOnlyIncito`)
public var types: Set<PublicationType>
/// True if this publication can only be viewed as an incito (if viewed in a PagedPublication view it would appear as a single-page pdf)
public var isOnlyIncito: Bool {
return types == [.incito]
}
public init(
id: Identifier,
label: String?,
pageCount: Int,
offerCount: Int,
runDateRange: Range<Date>,
aspectRatio: Double,
branding: Branding,
frontPageImages: ImageURLSet,
isAvailableInAllStores: Bool,
dealerId: CoreAPI.Dealer.Identifier,
storeId: CoreAPI.Store.Identifier?,
incitoId: IncitoGraphIdentifier?,
types: Set<PublicationType>
) {
self.id = id
self.label = label
self.pageCount = pageCount
self.offerCount = offerCount
self.runDateRange = runDateRange
self.aspectRatio = aspectRatio
self.branding = branding
self.frontPageImages = frontPageImages
self.isAvailableInAllStores = isAvailableInAllStores
self.dealerId = dealerId
self.storeId = storeId
self.incitoId = incitoId
self.types = types
}
// MARK: Decodable
enum CodingKeys: String, CodingKey {
case id
case label = "label"
case branding
case pageCount = "page_count"
case offerCount = "offer_count"
case runFromDateStr = "run_from"
case runTillDateStr = "run_till"
case dealerId = "dealer_id"
case storeId = "store_id"
case availableAllStores = "all_stores"
case dimensions
case frontPageImageURLs = "images"
case incitoId = "incito_publication_id"
case types
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(Identifier.self, forKey: .id)
self.label = try? values.decode(String.self, forKey: .label)
self.branding = try values.decode(Branding.self, forKey: .branding)
self.pageCount = (try? values.decode(Int.self, forKey: .pageCount)) ?? 0
self.offerCount = (try? values.decode(Int.self, forKey: .offerCount)) ?? 0
var fromDate = Date.distantPast
if let fromDateStr = try? values.decode(String.self, forKey: .runFromDateStr),
let from = CoreAPI.dateFormatter.date(from: fromDateStr) {
fromDate = from
}
var tillDate = Date.distantFuture
if let tillDateStr = try? values.decode(String.self, forKey: .runTillDateStr),
let till = CoreAPI.dateFormatter.date(from: tillDateStr) {
tillDate = till
}
// make sure range is not malformed
self.runDateRange = min(tillDate, fromDate) ..< max(tillDate, fromDate)
if let dimDict = try? values.decode([String: Double].self, forKey: .dimensions),
let width = dimDict["width"], let height = dimDict["height"] {
self.aspectRatio = (width > 0 && height > 0) ? width / height : 1.0
} else {
self.aspectRatio = 1.0
}
self.isAvailableInAllStores = (try? values.decode(Bool.self, forKey: .availableAllStores)) ?? true
self.dealerId = try values.decode(Dealer.Identifier.self, forKey: .dealerId)
self.storeId = try? values.decode(Store.Identifier.self, forKey: .storeId)
if let frontPageImageURLs = try? values.decode(ImageURLSet.CoreAPI.ImageURLs.self, forKey: .frontPageImageURLs) {
self.frontPageImages = ImageURLSet(fromCoreAPI: frontPageImageURLs, aspectRatio: self.aspectRatio)
} else {
self.frontPageImages = ImageURLSet(sizedUrls: [])
}
self.incitoId = try? values.decode(IncitoGraphIdentifier.self, forKey: .incitoId)
self.types = (try? values.decode(Set<PublicationType>.self, forKey: .types)) ?? [.paged]
}
// MARK: -
public struct Page: Equatable {
public var index: Int
public var title: String?
public var aspectRatio: Double
public var images: ImageURLSet
}
// MARK: -
public struct Hotspot: Decodable, Equatable {
public var offer: CoreAPI.Offer?
/// The 0->1 range bounds of the hotspot, keyed by the pageIndex.
public var pageLocations: [Int: CGRect]
/// This returns a new hotspot whose pageLocation bounds is scaled.
func withScaledBounds(scale: CGPoint) -> Hotspot {
var newHotspot = self
newHotspot.pageLocations = newHotspot.pageLocations.mapValues({
var bounds = $0
bounds.origin.x *= scale.x
bounds.size.width *= scale.x
bounds.origin.y *= scale.y
bounds.size.height *= scale.y
return bounds
})
return newHotspot
}
// MARK: Decoding
enum CodingKeys: String, CodingKey {
case pageCoords = "locations"
case offer
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.offer = try? values.decode(CoreAPI.Offer.self, forKey: .offer)
if let pageCoords = try? values.decode([Int: [[CGFloat]]].self, forKey: .pageCoords) {
self.pageLocations = pageCoords.reduce(into: [:]) {
let pageNum = $1.key
let coordsList = $1.value
guard pageNum > 0 else { return }
let coordRange: (min: CGPoint, max: CGPoint)? = coordsList.reduce(nil, { (currRange, coords) in
guard coords.count == 2 else { return currRange }
let point = CGPoint(x: coords[0], y: coords[1])
guard var newRange = currRange else {
return (min: point, max: point)
}
newRange.max.x = max(newRange.max.x, point.x)
newRange.max.y = max(newRange.max.y, point.y)
newRange.min.x = min(newRange.min.x, point.x)
newRange.min.y = min(newRange.min.y, point.y)
return newRange
})
guard let boundsRange = coordRange else { return }
let bounds = CGRect(origin: boundsRange.min,
size: CGSize(width: boundsRange.max.x - boundsRange.min.x,
height: boundsRange.max.y - boundsRange.min.y))
$0[pageNum - 1] = bounds
}
} else {
self.pageLocations = [:]
}
}
}
}
}
// `Catalog` json response
//{
// "id": "6fe6Mg8",
// "ern": "ern:catalog:6fe6Mg8",
// "label": "Netto-avisen uge 3 2018",
// "background": null,
// "run_from": "2018-01-12T23:00:00+0000",
// "run_till": "2018-01-19T22:59:59+0000",
// "page_count": 32,
// "offer_count": 193,
// "branding": {
// "name": "Netto",
// "website": "http:\/\/netto.dk",
// "description": "Netto er lig med kvalitetsvarer til lave priser. Det har gjort Netto til en af Danmarks stu00f8rste dagligvareku00e6der.",
// "logo": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/logo\/default\/00im1ykdf4id12ye.png",
// "color": "333333",
// "pageflip": {
// "logo": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/logo\/pageflip\/00im1ykdql3p4gpl.png",
// "color": "333333"
// }
// },
// "dealer_id": "9ba51",
// "dealer_url": "https:\/\/api-edge.etilbudsavis.dk\/v2\/dealers\/9ba51",
// "store_id": null,
// "store_url": null,
// "dimensions": {
// "height": 1.44773,
// "width": 1
// },
// "images": {
// "@note.1": "this object contains a single image, used to present a catalog (usually the frontpage)",
// "thumb": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/thumb\/6fe6Mg8-1.jpg?m=p1nyeo",
// "view": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/view\/6fe6Mg8-1.jpg?m=p1nyeo",
// "zoom": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/zoom\/6fe6Mg8-1.jpg?m=p1nyeo"
// },
// "pages": {
// "@note.1": "",
// "thumb": [],
// "view": [],
// "zoom": []
// },
// "category_ids": [],
// "pdf_url": "https:\/\/api-edge.etilbudsavis.dk\/v2\/catalogs\/6fe6Mg8\/download"
//}
// `Pages` response
//[
// {
// "thumb": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/thumb\/6fe6Mg8-1.jpg?m=p1nyeo",
// "view": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/view\/6fe6Mg8-1.jpg?m=p1nyeo",
// "zoom": "https:\/\/d3ikkoqs9ddhdl.cloudfront.net\/img\/catalog\/zoom\/6fe6Mg8-1.jpg?m=p1nyeo"
// }, ...
//]
// `Hotspots` response
//[
// {
// "type": "offer",
// "locations": {
// "1": [
// [ 0.366304, 1.44773 ],
// [ 0.366304, 0.6373920871 ],
// [ 0.622826, 0.6373920871 ],
// [ 0.622826, 1.44773 ]
// ]
// },
// "id": "a8afitUF",
// "run_from": 1515798000,
// "run_till": 1516402799,
// "heading": "Gavepapir",
// "webshop": null,
// "offer": {
// "id": "a8afitUF",
// "ern": "ern:offer:a8afitUF",
// "heading": "Gavepapir",
// "pricing": {
// "price": 30,
// "pre_price": null,
// "currency": "DKK"
// },
// "quantity": {
// "unit": null,
// "size": {
// "from": 1,
// "to": 1
// },
// "pieces": {
// "from": 1,
// "to": 1
// }
// },
// "run_from": "2018-01-12T23:00:00+0000",
// "run_till": "2018-01-19T22:59:59+0000",
// "publish": "2018-01-11T17:00:00+0000"
// }
// }, ...
//]
| mit | c182a48efed575886c8cc8a6da89dc4f | 40.946588 | 227 | 0.51054 | 4.290137 | false | false | false | false |
devpunk/cartesian | cartesian/Model/DrawList/MDrawListItem.swift | 1 | 1980 | import UIKit
class MDrawListItem
{
let project:DProject
private(set) var image:UIImage?
init(project:DProject)
{
self.project = project
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.renderImage()
}
}
//MARK: private
private func renderImage()
{
guard
let nodes:[DNode] = project.nodes?.array as? [DNode]
else
{
return
}
let canvasWidth:CGFloat = CGFloat(project.width)
let canvasHeight:CGFloat = CGFloat(project.height)
let canvasSize:CGSize = CGSize(
width:canvasWidth,
height:canvasHeight)
let canvasRect:CGRect = CGRect(
origin:CGPoint.zero,
size:canvasSize)
UIGraphicsBeginImageContextWithOptions(canvasSize, true, 1)
guard
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
return
}
context.setFillColor(UIColor.white.cgColor)
context.addRect(canvasRect)
context.drawPath(using:CGPathDrawingMode.fill)
for node:DNode in nodes
{
MDrawListItemRender.renderNode(
node:node,
context:context)
}
guard
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
else
{
UIGraphicsEndImageContext()
return
}
UIGraphicsEndImageContext()
imageRendered(image:image)
}
private func imageRendered(image:UIImage)
{
self.image = image
NotificationCenter.default.post(
name:Notification.listItemRendered,
object:self)
}
}
| mit | 25aa397f3b09e3c84afb8dc342baa435 | 22.023256 | 75 | 0.517172 | 5.755814 | false | false | false | false |
misuqian/iOSDemoSwift | ABUIGroupsSwift/ABUIGroupsSwift/AddGroupViewController.swift | 1 | 1983 | //
// AddGroupViewController.swift
// ABUIGroupsSwift
//
// Created by 彭芊 on 16/4/25.
// Copyright © 2016年 彭芊. All rights reserved.
//
import UIKit
protocol GroupsDelegate {
func addNewGroups(name : String)
}
//增加新的分组VC
class AddGroupViewController: UIViewController,UITextFieldDelegate{
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var textField: UITextField!
var groupDelegate : GroupsDelegate! //VC之间采用协议通信
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool{
//取消聚焦,回收键盘
textField.resignFirstResponder()
doneButton.enabled = textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0
return true
}
//输入框内容为空不能增加分组
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
if string == ""{
doneButton.enabled = textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 1
}else{
doneButton.enabled = textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0
}
return true
}
func textFieldShouldClear(textField: UITextField) -> Bool {
doneButton.enabled = false
return true
}
@IBAction func cancel(sender: UIBarButtonItem) {
self.textField.resignFirstResponder()
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func done(sender: UIBarButtonItem) {
self.groupDelegate.addNewGroups(self.textField.text!)
self.textField.resignFirstResponder()
self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | db7408b07f9254ef02e4b711149a9ba7 | 29.15873 | 131 | 0.684737 | 5 | false | false | false | false |
MainasuK/Bangumi-M | Percolator/Percolator/Actor.swift | 1 | 612 | //
// Actor.swift
// Percolator
//
// Created by Cirno MainasuK on 2015-8-20.
// Copyright (c) 2015年 Cirno MainasuK. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Actor {
var id: Int
var url: String
var name: String
// var image = CrtImage()
init(from json: JSON) {
id = json[BangumiKey.id].intValue
url = json[BangumiKey.url].stringValue
name = json[BangumiKey.name].stringValue
// if let imageDict = actorDict[BangumiKey.imagesDict] as? NSDictionary {
// image = CrtImage(crtImageDict: imageDict)
// }
}
}
| mit | 50bdf703a5257a5ce71d2c788b8b5832 | 20.785714 | 80 | 0.631148 | 3.407821 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus Watch Extension/Controller/Favorites/FavoritesInterfaceController.swift | 1 | 2239 | import WatchKit
import Foundation
import ObjectMapper
class FavoritesInterfaceController: WKInterfaceController, PhoneMessageListener {
@IBOutlet var tableView: WKInterfaceTable!
@IBOutlet var loadingText: WKInterfaceLabel!
@IBOutlet var noFavoritesText: WKInterfaceLabel!
var busStops = [BBusStop]()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
super.willActivate()
PhoneConnection.standard.addListener(self)
PhoneConnection.standard.sendMessage(message: ["type": WatchMessage.favoriteBusStops.rawValue])
}
override func didDeactivate() {
super.didDeactivate()
PhoneConnection.standard.removeListener(self)
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
pushController(withName: "DeparturesInterfaceController", context: busStops[rowIndex])
}
}
extension FavoritesInterfaceController {
func didReceiveMessage(type: WatchMessage, data: String, message: [String: Any]) {
print("didReceiveMessage")
guard type == .favoriteBusStopsResponse else {
return
}
guard let items = Mapper<BBusStop>().mapArray(JSONString: data) else {
Log.error("Cannot map JSON to [BBusStop]")
return
}
self.busStops.removeAll()
self.busStops.append(contentsOf: items)
DispatchQueue.main.async {
self.loadingText.setHidden(true)
if items.isEmpty {
self.noFavoritesText.setHidden(false)
} else {
self.noFavoritesText.setHidden(true)
}
self.tableView.setNumberOfRows(self.busStops.count, withRowType: "FavoritesRowController")
for (index, item) in items.enumerated() {
let row = self.tableView.rowController(at: index) as! FavoritesRowController
row.name.setText(item.name())
row.city.setText(item.munic())
}
}
}
}
| gpl-3.0 | 6aa0f94e3a73878aa779af0d08327f4b | 28.460526 | 103 | 0.607861 | 5.382212 | false | false | false | false |
takamashiro/XDYZB | XDYZB/XDYZB/Classes/Home/ViewModel/RecommandViewModel.swift | 1 | 4355 | //
// RecommandViewModel.swift
// XDYZB
//
// Created by takamashiro on 2016/9/28.
// Copyright © 2016年 com.takamashiro. All rights reserved.
//
/*
1> 请求0/1数组,并转成模型对象
2> 对数据进行排序
3> 显示的HeaderView中内容
*/
import UIKit
class RecommandViewModel:BaseViewModel {
// MARK:- 懒加载属性
lazy var cycleModels : [CycleModel] = [CycleModel]()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
}
//MARK:- 发送网络请求
extension RecommandViewModel {
// 请求推荐数据
func requestData(_ finishCallback : @escaping () -> ()) {
// 1.定义参数
let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
// 2.创建Group
let dGroup = DispatchGroup()
self.bigDataGroup.anchors.removeAll()
self.prettyGroup.anchors.removeAll()
// 3.请求第一部分推荐数据
dGroup.enter()
NetworkTools.requestData(.GET, URLString: kGetbigDataRoom, parameters: ["time" : Date.getCurrentTime() as NSString]) { (result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchors.append(anchor)
}
// 3.3.离开组
dGroup.leave()
}
// 4.请求第二部分颜值数据
dGroup.enter()
NetworkTools.requestData(.GET, URLString: kGetVerticalRoom, parameters: parameters as [String : NSString]?) { (result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
// 3.3.离开组
dGroup.leave()
}
// 5.请求2-12部分游戏数据
dGroup.enter()
// http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1474252024
loadAnchorData(isGroupData: true,URLString: kgetHotCate, parameters: parameters) {
dGroup.leave()
}
// 6.所有的数据都请求到,之后进行排序
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
// 请求无线轮播的数据
func requestCycleData(finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.GET, URLString: kGetCycleData, parameters: ["version" : "2.300"]) { (result) in
// 1.获取整体字典数据
guard let resultDict = result as? [String : NSObject] else { return }
self.cycleModels.removeAll()
// 2.根据data的key获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}
}
| mit | d8acdc3990d25ac4fcafd4f8a6e01d19 | 31.01626 | 138 | 0.538344 | 4.573751 | false | false | false | false |
johnno1962c/swift-corelibs-foundation | Foundation/ByteCountFormatter.swift | 7 | 20276 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
extension ByteCountFormatter {
public struct Units : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
// Specifying any of the following causes the specified units to be used in showing the number.
public static let useBytes = Units(rawValue: 1 << 0)
public static let useKB = Units(rawValue: 1 << 1)
public static let useMB = Units(rawValue: 1 << 2)
public static let useGB = Units(rawValue: 1 << 3)
public static let useTB = Units(rawValue: 1 << 4)
public static let usePB = Units(rawValue: 1 << 5)
public static let useEB = Units(rawValue: 1 << 6)
public static let useZB = Units(rawValue: 1 << 7)
public static let useYBOrHigher = Units(rawValue: 0x0FF << 8)
// Can use any unit in showing the number.
public static let useAll = Units(rawValue: 0x0FFFF)
}
public enum CountStyle : Int {
// Specifies display of file or storage byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the decimal style, but that may change over time.
case file
// Specifies display of memory byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the binary style, but that may change over time.
case memory
// The following two allow specifying the number of bytes for KB explicitly. It's better to use one of the above values in most cases.
case decimal // 1000 bytes are shown as 1 KB
case binary // 1024 bytes are shown as 1 KB
}
}
open class ByteCountFormatter : Formatter {
public override init() {
super.init()
}
public required init?(coder: NSCoder) {
NSUnimplemented()
}
/* Specify the units that can be used in the output. If ByteCountFormatter.Units is empty, uses platform-appropriate settings; otherwise will only use the specified units. This is the default value. Note that ZB and YB cannot be covered by the range of possible values, but you can still choose to use these units to get fractional display ("0.0035 ZB" for instance).
*/
open var allowedUnits: Units = []
/* Specify how the count is displayed by indicating the number of bytes to be used for kilobyte. The default setting is ByteCountFormatter.CountStyle.fileCount, which is the system specific value for file and storage sizes.
*/
open var countStyle: CountStyle = .file
/* Choose whether to allow more natural display of some values, such as zero, where it may be displayed as "Zero KB," ignoring all other flags or options (with the exception of ByteCountFormatter.Units.useBytes, which would generate "Zero bytes"). The result is appropriate for standalone output. Default value is YES. Special handling of certain values such as zero is especially important in some languages, so it's highly recommended that this property be left in its default state.
*/
open var allowsNonnumericFormatting: Bool = true
/* Choose whether to include the number or the units in the resulting formatted string. (For example, instead of 723 KB, returns "723" or "KB".) You can call the API twice to get both parts, separately. But note that putting them together yourself via string concatenation may be wrong for some locales; so use this functionality with care. Both of these values are YES by default. Setting both to NO will unsurprisingly result in an empty string.
*/
open var includesUnit: Bool = true
open var includesCount: Bool = true
/* Choose whether to parenthetically (localized as appropriate) display the actual number of bytes as well, for instance "723 KB (722,842 bytes)". This will happen only if needed, that is, the first part is already not showing the exact byte count. If includesUnit or includesCount are NO, then this setting has no effect. Default value is NO.
*/
open var includesActualByteCount: Bool = false
/* Choose the display style. The "adaptive" algorithm is platform specific and uses a different number of fraction digits based on the magnitude (in 10.8: 0 fraction digits for bytes and KB; 1 fraction digits for MB; 2 for GB and above). Otherwise the result always tries to show at least three significant digits, introducing fraction digits as necessary. Default is YES.
*/
open var isAdaptive: Bool = true
/* Choose whether to zero pad fraction digits so a consistent number of fraction digits are displayed, causing updating displays to remain more stable. For instance, if the adaptive algorithm is used, this option formats 1.19 and 1.2 GB as "1.19 GB" and "1.20 GB" respectively, while without the option the latter would be displayed as "1.2 GB". Default value is NO.
*/
open var zeroPadsFractionDigits: Bool = false
/* Specify the formatting context for the formatted string. Default is NSFormattingContextUnknown.
*/
open var formattingContext: Context = .unknown
/* A variable to store the actual bytes passed into the methods. This value is used if the includesActualByteCount property is set.
*/
private var actualBytes: String = ""
/* Create an instance of NumberFormatter for use in various methods
*/
private let numberFormatter = NumberFormatter()
/* Shortcut for converting a byte count into a string without creating an ByteCountFormatter and an NSNumber. If you need to specify options other than countStyle, create an instance of ByteCountFormatter first.
*/
open class func string(fromByteCount byteCount: Int64, countStyle: ByteCountFormatter.CountStyle) -> String {
let formatter = ByteCountFormatter()
formatter.countStyle = countStyle
return formatter.string(fromByteCount: byteCount)
}
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
*/
open func string(fromByteCount byteCount: Int64) -> String {
//Convert actual bytes to a formatted string for use later
numberFormatter.numberStyle = .decimal
actualBytes = numberFormatter.string(from: NSNumber(value: byteCount))!
if countStyle == .decimal || countStyle == .file {
return convertValue(fromByteCount: byteCount, for: decimalByteSize)
} else {
return convertValue(fromByteCount: byteCount, for: binaryByteSize)
}
}
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
*/
open override func string(for obj: Any?) -> String? {
guard let value = obj as? Double else {
return nil
}
return string(fromByteCount: Int64(value))
}
/* This method accepts a byteCount and a byteSize value. Checks to see what range the byteCount falls into and then converts to the units determined by that range. The range to be used is decided by the byteSize parameter. The conversion is done by making use of the divide method.
*/
private func convertValue(fromByteCount byteCount: Int64, for byteSize: [Unit: Double]) -> String {
let byte = Double(byteCount)
if byte == 0, allowsNonnumericFormatting, allowedUnits == [], includesUnit, includesCount {
return partsToIncludeFor(value: "Zero", unit: Unit.KB)
} else if byte == 1 || byte == -1 {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return formatNumberFor(bytes: byte, unit: Unit.byte)
} else {
return valueToUseFor(byteCount: byte, unit: allowedUnits)
}
} else if byte < byteSize[Unit.KB]! && byte > -byteSize[Unit.KB]!{
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return formatNumberFor(bytes: byte, unit: Unit.bytes)
} else {
return valueToUseFor(byteCount: byte, unit: allowedUnits)
}
} else if byte < byteSize[Unit.MB]! && byte > -byteSize[Unit.MB]! {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .KB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
} else if byte < byteSize[Unit.GB]! && byte > -byteSize[Unit.GB]! {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .MB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
} else if byte < byteSize[Unit.TB]! && byte > -byteSize[Unit.TB]! {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .GB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
} else if byte < byteSize[Unit.PB]! && byte > -byteSize[Unit.PB]! {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .TB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
} else if byte < byteSize[Unit.EB]! && byte > -byteSize[Unit.EB]! {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .PB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
} else {
if allowedUnits.contains(.useAll) || allowedUnits == [] {
return divide(byte, by: byteSize, for: .EB)
}
return valueToUseFor(byteCount: byte, unit: allowedUnits)
}
}
/*
A helper method to deal with the Option Set, caters for setting an individual value or passing in an array of values.
Returns the correct value based on the units that are allowed for use.
*/
private func valueToUseFor(byteCount: Double, unit: ByteCountFormatter.Units) -> String {
var byteSize: [Unit: Double]
//Check to see whether we're using 1000bytes per KB or 1024 per KB
if countStyle == .decimal || countStyle == .file {
byteSize = decimalByteSize
} else {
byteSize = binaryByteSize
}
if byteCount == 0, allowsNonnumericFormatting, includesCount, includesUnit {
return partsToIncludeFor(value: "Zero", unit: Unit.KB)
}
//Handles the cases where allowedUnits is set to a specific individual value. e.g. allowedUnits = .useTB
switch allowedUnits {
case Units.useBytes: return partsToIncludeFor(value: actualBytes, unit: Unit.bytes)
case Units.useKB: return divide(byteCount, by: byteSize, for: .KB)
case Units.useMB: return divide(byteCount, by: byteSize, for: .MB)
case Units.useGB: return divide(byteCount, by: byteSize, for: .GB)
case Units.useTB: return divide(byteCount, by: byteSize, for: .TB)
case Units.usePB: return divide(byteCount, by: byteSize, for: .PB)
case Units.useEB: return divide(byteCount, by: byteSize, for: .EB)
case Units.useZB: return divide(byteCount, by: byteSize, for: .ZB)
case Units.useYBOrHigher: return divide(byteCount, by: byteSize, for: .YB)
default: break
}
//Initialise an array that will hold all the units we can use
var unitsToUse: [Unit] = []
//Based on what units have been selected for use, build an array out of them.
if unit.contains(.useBytes) && byteCount == 1 {
unitsToUse.append(.byte)
} else if unit.contains(.useBytes) {
unitsToUse.append(.bytes)
}
if unit.contains(.useKB) {
unitsToUse.append(.KB)
}
if unit.contains(.useMB) {
unitsToUse.append(.MB)
}
if unit.contains(.useGB) {
unitsToUse.append(.GB)
}
if unit.contains(.useTB) {
unitsToUse.append(.TB)
}
if unit.contains(.usePB) {
unitsToUse.append(.PB)
}
if unit.contains(.useEB) {
unitsToUse.append(.EB)
}
if unit.contains(.useZB) {
unitsToUse.append(.ZB)
}
if unit.contains(.useYBOrHigher) {
unitsToUse.append(.YB)
}
var counter = 0
for _ in unitsToUse {
counter += 1
if counter > unitsToUse.count - 1 {
counter = unitsToUse.count - 1
}
/*
The units are appended to the array in asceding order, so if the value for byteCount is smaller than the byteSize value of the next unit
in the Array we use the previous unit. e.g. if byteCount = 1000, and AllowedUnits = [.useKB, .useGB] check to see if byteCount is smaller
than a GB in bytes(pow(1000, 3)) and if so, we'll use the previous unit which is KB in this case.
*/
if byteCount < byteSize[unitsToUse[counter]]! {
return divide(byteCount, by: byteSize, for: unitsToUse[counter - 1])
}
}
return divide(byteCount, by: byteSize, for: unitsToUse[counter])
}
// Coverts the number of bytes to the correct value given a specified unit, then passes the value and unit to formattedValue
private func divide(_ bytes: Double, by byteSize: [Unit: Double], for unit: Unit) -> String {
guard let byteSizeUnit = byteSize[unit] else {
fatalError("Cannot find value \(unit)")
}
let result = bytes/byteSizeUnit
return formatNumberFor(bytes: result, unit: unit)
}
//Formats the byte value using the NumberFormatter class based on set properties and the unit passed in as a parameter.
private func formatNumberFor(bytes: Double, unit: Unit) -> String {
switch (zeroPadsFractionDigits, isAdaptive) {
//zeroPadsFractionDigits is true, isAdaptive is true
case (true, true):
switch unit {
case .bytes, .byte, .KB:
let result = String(format: "%.0f", bytes)
return partsToIncludeFor(value: result, unit: unit)
case .MB:
let result = String(format: "%.1f", bytes)
return partsToIncludeFor(value: result, unit: unit)
default:
let result = String(format: "%.2f", bytes)
return partsToIncludeFor(value: result, unit: unit)
}
//zeroPadsFractionDigits is true, isAdaptive is false
case (true, false):
if unit == .byte || unit == .bytes {
numberFormatter.maximumFractionDigits = 0
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
} else {
if lengthOfInt(number: Int(bytes)) == 3 {
numberFormatter.usesSignificantDigits = false
numberFormatter.maximumFractionDigits = 0
} else {
numberFormatter.maximumSignificantDigits = 3
numberFormatter.minimumSignificantDigits = 3
}
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
}
//zeroPadsFractionDigits is false, isAdaptive is true
case (false, true):
switch unit {
case .bytes, .byte, .KB:
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 0
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
case .MB:
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 1
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
default:
let result: String
//Need to add in an extra case for negative numbers as NumberFormatter formats 0.005 to 0 rather than
// 0.01
if bytes < 0 {
let negBytes = round(bytes * 100) / 100
result = numberFormatter.string(from: NSNumber(value: negBytes))!
} else {
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 2
result = numberFormatter.string(from: NSNumber(value: bytes))!
}
return partsToIncludeFor(value: result, unit: unit)
}
//zeroPadsFractionDigits is false, isAdaptive is false
case (false, false):
if unit == .byte || unit == .bytes {
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 0
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
} else {
if lengthOfInt(number: Int(bytes)) > 3 {
numberFormatter.maximumFractionDigits = 0
} else {
numberFormatter.maximumSignificantDigits = 3
}
let result = numberFormatter.string(from: NSNumber(value: bytes))
return partsToIncludeFor(value: result!, unit: unit)
}
}
}
// A helper method to return the length of an int
private func lengthOfInt(number: Int) -> Int {
var num = abs(number)
var length: [Int] = []
while num > 0 {
let remainder = num % 10
length.append(remainder)
num /= 10
}
return length.count
}
// Returns the correct string based on the includesValue and includesUnit properties
private func partsToIncludeFor(value: String, unit: Unit) -> String {
if includesActualByteCount, includesUnit, includesCount {
switch unit {
case .byte, .bytes: return "\(value) \(unit)"
default: return "\(value) \(unit) (\(actualBytes) \(Unit.bytes))"
}
} else if includesCount, includesUnit {
return "\(value) \(unit)"
} else if includesCount, !includesUnit {
if value == "Zero", allowedUnits == [] {
return "0"
} else {
return value
}
} else if !includesCount, includesUnit {
return "\(unit)"
} else {
return ""
}
}
//Enum containing available byte units
private enum Unit: String {
case byte
case bytes
case KB
case MB
case GB
case TB
case PB
case EB
case ZB
case YB
}
// Maps each unit to it's corresponding value in bytes for decimal
private let decimalByteSize: [Unit: Double] = [.byte: 1, .bytes: 1, .KB: 1000, .MB: pow(1000, 2), .GB: pow(1000, 3), .TB: pow(1000, 4), .PB: pow(1000, 5), .EB: pow(1000, 6), .ZB: pow(1000, 7), .YB: pow(1000, 8)]
// Maps each unit to it's corresponding value in bytes for binary
private let binaryByteSize: [Unit: Double] = [.byte: 1, .bytes: 1, .KB: 1024, .MB: pow(1024, 2), .GB: pow(1024, 3), .TB: pow(1024, 4), .PB: pow(1024, 5), .EB: pow(1024, 6), .ZB: pow(1024, 7), .YB: pow(1024, 8)]
}
| apache-2.0 | b7da548eded87be586281f49e303ae5d | 48.696078 | 489 | 0.614668 | 4.85769 | false | false | false | false |
zneak/swift-chess | chess/Locator.swift | 1 | 2435 | //
// Locator.swift
// chess
//
// Created by Félix on 16-02-12.
// Copyright © 2016 Félix Cloutier. All rights reserved.
//
import Foundation
private let primes = [
1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269,
2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393,
2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459]
private let fileNames: [Character] = ["a", "b", "c", "d", "e", "f", "g", "h"]
private func intToU8(int: Int) -> UInt8? {
if int >= 0 && int <= Int(UInt8.max) {
return UInt8(int)
}
return nil
}
struct Locator: Hashable {
let rank: UInt8
let file: UInt8
var index: Int {
return Int(rank * 8 + file)
}
var hashValue: Int {
return primes[index]
}
var description: String {
return "\(fileNames[Int(file)])\(rank+1)"
}
private init(rank: UInt8, file: UInt8) {
self.rank = rank
self.file = file
}
static var all: [Locator] {
return (UInt8(0)..<UInt8(64)).map {
Locator(rank: $0 / 8, file: $0 % 8)
}
}
static func rank(stringVal: String) -> UInt8? {
if let val = UInt8(stringVal) where val > 0 && val <= 8 {
return val - 1
}
return nil
}
static func file(stringVal: String) -> UInt8? {
let view = stringVal.lowercaseString.unicodeScalars
if view.count != 1 {
return nil
}
let file = view.first!.value - 0x61
if file < 0 || file >= 8 {
return nil
}
return UInt8(file)
}
static func fromCoords(file: UInt8?, rank: UInt8?) -> Locator? {
if let f = file, r = rank where file < 8 && rank < 8 {
return Locator(rank: r, file: f)
}
return nil
}
static func fromString(stringVal: String) -> Locator? {
let view = stringVal.characters
if view.count != 2 {
return nil
}
let start = view.startIndex
let end0 = start.advancedBy(1)
let end1 = end0.advancedBy(1)
if let rank = Locator.rank(String(view[start..<end0])), file = Locator.file(String(view[end0..<end1])) {
return Locator(rank: rank, file: file)
}
return nil
}
func delta(dx: Int, _ dy: Int) -> Locator? {
return Locator.fromCoords(intToU8(Int(file) + dx), rank: intToU8(Int(rank) + dy))
}
}
func ==(lhs: Locator, rhs: Locator) -> Bool {
return lhs.rank == rhs.rank && lhs.file == rhs.file
}
| gpl-3.0 | 2b2855ba49a7d28ee283d7ff791aaa8e | 23.079208 | 114 | 0.623766 | 2.640608 | false | false | false | false |
306244907/Weibo | JLSina/JLSina/Classes/Tools(工具)/UI框架/Emoticon/Model/CZEmoticon.swift | 1 | 2511 | //
// CZEmoticon.swift
// 表情包数据
//
// Created by 盘赢 on 2017/12/7.
// Copyright © 2017年 盘赢. All rights reserved.
//
import UIKit
import YYModel
@objcMembers
class CZEmoticon: NSObject {
///表情类型 ,false 图片表情,true emoji
var type = false
///表情字符串,发送给新浪微博服务器,(节约流量)
var chs: String?
///表情图片名称,用于本地图文混排
var png: String?
///emoji的十六进制编码
var code: String? {
didSet {
guard let code = code else {
return
}
let scanner = Scanner(string: code)
var result: UInt32 = 0
scanner.scanHexInt32(&result)
emoji = String(Character(UnicodeScalar(result)!))
}
}
///表情使用次数
var times: Int = 0
///emoji的字符串
var emoji: String?
///表情模型所在目录
var directory: String?
///图片表情对应的图像
var image: UIImage? {
//判断表情类型
if type {
return nil
}
guard let directory = directory ,
let png = png ,
let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil) ,
let bundle = Bundle(path: path) else {
return nil
}
return UIImage(named: "\(directory)/\(png)", in: bundle, compatibleWith: nil)
}
//将当前的图像生成图片属性文本
func imageText(font: UIFont) -> NSAttributedString {
//1,判断图像是否存在
guard let image = image else {
return NSAttributedString(string: "")
}
//2,创建文本附件
let attachment = CZEmoticonAttachment()
//记录属性文本文字
attachment.chs = chs
attachment.image = image
let height = font.lineHeight
attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
//3,返回图片属性文本
let attrStrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//设置文字属性
attrStrM.addAttributes([NSAttributedStringKey.font: font], range: NSMakeRange(0, 1))
//返回属性文本
return attrStrM
}
override var description: String {
return yy_modelDescription()
}
}
| mit | 62907d31a14de7a73259209858f52899 | 21.510204 | 110 | 0.543064 | 4.412 | false | false | false | false |
lllyyy/LY | ScrollableGraphView-master(折线图)/Classes/Plots/BarPlot.swift | 4 | 1289 |
import UIKit
open class BarPlot : Plot {
// Customisation
// #############
/// The width of an individual bar on the graph.
open var barWidth: CGFloat = 25;
/// The actual colour of the bar.
open var barColor: UIColor = UIColor.gray
/// The width of the outline of the bar
open var barLineWidth: CGFloat = 1
/// The colour of the bar outline
open var barLineColor: UIColor = UIColor.darkGray
/// Whether the bars should be drawn with rounded corners
open var shouldRoundBarCorners: Bool = false
// Private State
// #############
private var barLayer: BarDrawingLayer?
public init(identifier: String) {
super.init()
self.identifier = identifier
}
override func layers(forViewport viewport: CGRect) -> [ScrollableGraphViewDrawingLayer?] {
createLayers(viewport: viewport)
return [barLayer]
}
private func createLayers(viewport: CGRect) {
barLayer = BarDrawingLayer(
frame: viewport,
barWidth: barWidth,
barColor: barColor,
barLineWidth: barLineWidth,
barLineColor: barLineColor,
shouldRoundCorners: shouldRoundBarCorners)
barLayer?.owner = self
}
}
| mit | c9ce28df8f6cf16ffe4e5b629be84e34 | 27.021739 | 94 | 0.612878 | 4.957692 | false | false | false | false |
PlutoMa/SwiftProjects | 024.Vertical Menu Transition/VerticalMenuTransition/VerticalMenuTransition/MenuViewController.swift | 1 | 1448 | //
// MenuViewController.swift
// VerticalMenuTransition
//
// Created by Dareway on 2017/11/6.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
let dataSource: [String] = ["Menu One", "Menu Two", "Menu Three", "Menu Four"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.backgroundColor = UIColor.white
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "reuseCell")
view.addSubview(tableView)
}
}
extension MenuViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
}
| mit | 377d326aa911436ff07cdf943447ece1 | 28.489796 | 100 | 0.679585 | 5.034843 | false | false | false | false |
Gofake1/Color-Picker | Color Picker/Palette.swift | 1 | 1294 | //
// Palette.swift
// Color Picker
//
// Created by David Wu on 5/6/17.
// Copyright © 2017 Gofake1. All rights reserved.
//
import Cocoa
class Palette: NSObject, NSCoding {
@objc var name: String
@objc dynamic var colors: Set<NSColor>
let id: Int
init(id: Int? = nil, name: String = "New Palette", colors: Set<NSColor> = Set()) {
self.name = name
self.colors = colors
self.id = id ?? Date().hashValue
}
func addColor(_ color: NSColor) {
colors.insert(color)
}
func removeColor(_ color: NSColor) {
colors.remove(color)
}
// MARK: - NSCoding
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
id = aDecoder.decodeInteger(forKey: "id")
let colorData = aDecoder.decodeObject(forKey: "colorDataArray") as! [Data]
let colorArray = colorData.map { NSUnarchiver.unarchiveObject(with: $0) as! NSColor }
colors = Set(colorArray)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(id, forKey: "id")
let encodedColors = colors.map { NSArchiver.archivedData(withRootObject: $0) }
aCoder.encode(encodedColors, forKey: "colorDataArray")
}
}
| mit | 09cfafa8cd61ae0c6023f201e171b40f | 26.510638 | 93 | 0.621036 | 3.836795 | false | false | false | false |
argon/mas | MasKit/AppStore/ISStoreAccount.swift | 1 | 2492 | //
// ISStoreAccount.swift
// mas-cli
//
// Created by Andrew Naylor on 22/08/2015.
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
//
import CommerceKit
import StoreFoundation
extension ISStoreAccount: StoreAccount {
static var primaryAccountIsPresentAndSignedIn: Bool {
return CKAccountStore.shared().primaryAccountIsPresentAndSignedIn
}
static var primaryAccount: StoreAccount? {
var account: ISStoreAccount?
if #available(macOS 10.13, *) {
let group = DispatchGroup()
group.enter()
let accountService: ISAccountService = ISServiceProxy.genericShared().accountService
accountService.primaryAccount { (storeAccount: ISStoreAccount) in
account = storeAccount
group.leave()
}
_ = group.wait(timeout: .now() + 30)
} else {
// macOS 10.9-10.12
let accountStore = CKAccountStore.shared()
account = accountStore.primaryAccount
}
return account
}
static func signIn(username: String, password: String, systemDialog: Bool = false) throws -> StoreAccount {
var storeAccount: ISStoreAccount?
var maserror: MASError?
let accountService: ISAccountService = ISServiceProxy.genericShared().accountService
let client = ISStoreClient(storeClientType: 0)
accountService.setStoreClient(client)
let context = ISAuthenticationContext(accountID: 0)
context.appleIDOverride = username
if systemDialog {
context.appleIDOverride = username
} else {
context.demoMode = true
context.demoAccountName = username
context.demoAccountPassword = password
context.demoAutologinMode = true
}
let group = DispatchGroup()
group.enter()
// Only works on macOS Sierra and below
accountService.signIn(with: context) { success, account, error in
if success {
storeAccount = account
} else {
maserror = .signInFailed(error: error as NSError?)
}
group.leave()
}
if systemDialog {
group.wait()
} else {
_ = group.wait(timeout: .now() + 30)
}
if let account = storeAccount {
return account
}
throw maserror ?? MASError.signInFailed(error: nil)
}
}
| mit | 379459edb06cc63428bfc9ac10c3b252 | 28.317647 | 111 | 0.59992 | 4.848249 | false | false | false | false |
jakeheis/SwiftCLI | Sources/SwiftCLI/OptionGroup.swift | 1 | 1986 | //
// OptionGroup.swift
// SwiftCLI
//
// Created by Jake Heiser on 3/31/17.
// Copyright © 2017 jakeheis. All rights reserved.
//
public class OptionGroup: CustomStringConvertible {
public enum Restriction {
case atMostOne // 0 or 1
case exactlyOne // 1
case atLeastOne // 1 or more
}
public static func atMostOne(_ options: Option...) -> OptionGroup {
return .atMostOne(options)
}
public static func atMostOne(_ options: [Option]) -> OptionGroup {
return .init(options: options, restriction: .atMostOne)
}
public static func exactlyOne(_ options: Option...) -> OptionGroup {
return .exactlyOne(options)
}
public static func exactlyOne(_ options: [Option]) -> OptionGroup {
return .init(options: options, restriction: .exactlyOne)
}
public static func atLeastOne(_ options: Option...) -> OptionGroup {
return .atLeastOne(options)
}
public static func atLeastOne(_ options: [Option]) -> OptionGroup {
return .init(options: options, restriction: .atLeastOne)
}
public let options: [Option]
public let restriction: Restriction
internal(set) public var count: Int = 0
public var description: String {
return "OptionGroup.\(restriction)(\(options))"
}
public init(options: [Option], restriction: Restriction) {
precondition(!options.isEmpty, "must pass one or more options")
if options.count == 1 {
precondition(restriction == .exactlyOne, "cannot use atMostOne or atLeastOne when passing one option")
}
self.options = options
self.restriction = restriction
}
public func check() -> Bool {
if count == 0 && restriction != .atMostOne {
return false
}
if count > 1 && restriction != .atLeastOne {
return false
}
return true
}
}
| mit | cb4ef16ec8630e950d3e0461fb8031c7 | 27.768116 | 114 | 0.602015 | 4.853301 | false | false | false | false |
cliqz-oss/browser-ios | Client/Cliqz/Foundation/Extensions/StringExtension.swift | 2 | 2635 | //
// StringExtension.swift
// Client
//
// Created by Mahmoud Adam on 11/9/15.
// Copyright © 2015 Cliqz. All rights reserved.
//
import Foundation
import Shared
extension String {
var boolValue: Bool {
return NSString(string: self).boolValue
}
func trim() -> String {
let newString = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return newString
}
static func generateRandomString(_ length: Int, alphabet: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") -> String {
var randomString = ""
let rangeLength = UInt32 (alphabet.characters.count)
for _ in 0 ..< length {
let randomIndex = Int(arc4random_uniform(rangeLength))
randomString.append(alphabet[alphabet.characters.index(alphabet.startIndex, offsetBy: randomIndex)])
}
return String(randomString)
}
func replace(_ string:String, replacement:String) -> String {
return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
}
func removeWhitespaces() -> String {
return self.replace(" ", replacement: "")
}
func escapeURL() -> String {
if self.contains("%") { // String already escaped
return self
} else {
let allowedCharacterSet = NSMutableCharacterSet()
allowedCharacterSet.formUnion(with: CharacterSet.urlQueryAllowed)
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet)!
}
}
// Cliqz added extra URL encoding methods because stringByAddingPercentEncodingWithAllowedCharacters doesn't encodes &
func encodeURL() -> String {
return CFURLCreateStringByAddingPercentEscapes(nil,
self as CFString,
nil,
String("!*'\"();:@&=+$,/?%#[]% ") as CFString, CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) as String
}
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSFontAttributeName: font]
let boundingRect = NSString(string: self).boundingRect(with: size,
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: attrs, context: nil)
return boundingRect.height
}
}
| mpl-2.0 | 31fcbbc5eabdf74612e9cc63e0b4298d | 34.594595 | 148 | 0.629081 | 5.652361 | false | false | false | false |
ben-ng/swift | test/stmt/statements.swift | 1 | 13745 | // RUN: %target-typecheck-verify-swift
/* block comments */
/* /* nested too */ */
func markUsed<T>(_ t: T) {}
func f1(_ a: Int, _ y: Int) {}
func f2() {}
func f3() -> Int {}
func invalid_semi() {
; // expected-error {{';' statements are not allowed}} {{3-5=}}
}
func nested1(_ x: Int) {
var y : Int
func nested2(_ z: Int) -> Int {
return x+y+z
}
_ = nested2(1)
}
func funcdecl5(_ a: Int, y: Int) {
var x : Int
// a few statements
if (x != 0) {
if (x != 0 || f3() != 0) {
// while with and without a space after it.
while(true) { 4; 2; 1 } // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
while (true) { 4; 2; 1 } // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
}
}
// Assignment statement.
x = y
(x) = y
1 = x // expected-error {{cannot assign to a literal value}}
(1) = x // expected-error {{cannot assign to a literal value}}
(x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}}
var tup : (x:Int, y:Int)
tup.x = 1
_ = tup
let B : Bool
// if/then/else.
if (B) {
} else if (y == 2) {
}
// This diagnostic is terrible - rdar://12939553
if x {} // expected-error {{'Int' is not convertible to 'Bool'}}
if true {
if (B) {
} else {
}
}
if (B) {
f1(1,2)
} else {
f2()
}
if (B) {
if (B) {
f1(1,2)
} else {
f2()
}
} else {
f2()
}
// while statement.
while (B) {
}
// It's okay to leave out the spaces in these.
while(B) {}
if(B) {}
}
struct infloopbool {
var boolValue: infloopbool {
return self
}
}
func infloopbooltest() {
if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}}
}
// test "builder" API style
extension Int {
static func builder() -> Int { }
var builderProp: Int { return 0 }
func builder2() {}
}
Int
.builder()
.builderProp
.builder2()
struct SomeGeneric<T> {
static func builder() -> SomeGeneric<T> { }
var builderProp: SomeGeneric<T> { return .builder() }
func builder2() {}
}
SomeGeneric<Int>
.builder()
.builderProp
.builder2()
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
continue // expected-error {{'continue' is only allowed inside a loop}}
while true {
func f() {
break // expected-error {{'break' is only allowed inside a loop}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
// Labeled if
MyIf: if 1 != 2 {
break MyIf
continue MyIf // expected-error {{'continue' cannot be used with if statements}}
break // break the while
continue // continue the while.
}
}
// Labeled if
MyOtherIf: if 1 != 2 {
break MyOtherIf
continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}}
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
do {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
func tuple_assign() {
var a,b,c,d : Int
(a,b) = (1,2)
func f() -> (Int,Int) { return (1,2) }
((a,b), (c,d)) = (f(), f())
}
func missing_semicolons() {
var w = 321
func g() {}
g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}}
var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{expression of type 'String' is unused}}
class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}}
struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}}
func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}}
}
//===--- Return statement.
return 42 // expected-error {{return invalid outside of a func}}
return // expected-error {{return invalid outside of a func}}
func NonVoidReturn1() -> Int {
return // expected-error {{non-void function should return a value}}
}
func NonVoidReturn2() -> Int {
return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}}
}
func VoidReturn1() {
if true { return }
// Semicolon should be accepted -- rdar://11344875
return; // no-error
}
func VoidReturn2() {
return () // no-error
}
func VoidReturn3() {
return VoidReturn2() // no-error
}
//===--- If statement.
func IfStmt1() {
if 1 > 0 // expected-error {{expected '{' after 'if' condition}}
_ = 42
}
func IfStmt2() {
if 1 > 0 {
} else // expected-error {{expected '{' after 'else'}}
_ = 42
}
//===--- While statement.
func WhileStmt1() {
while 1 > 0 // expected-error {{expected '{' after 'while' condition}}
_ = 42
}
//===-- Do statement.
func DoStmt() {
// This is just a 'do' statement now.
do {
}
}
func DoWhileStmt() {
do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}}
} while true
}
//===--- Repeat-while statement.
func RepeatWhileStmt1() {
repeat {} while true
repeat {} while false
repeat { break } while true
repeat { continue } while true
}
func RepeatWhileStmt2() {
repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}}
}
func RepeatWhileStmt4() {
repeat {
} while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}}
}
func brokenSwitch(_ x: Int) -> Int {
switch x {
case .Blah(var rep): // expected-error{{enum case 'Blah' not found in type 'Int'}}
return rep
}
}
func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int {
switch (x,y,z) {
case (let a, 0, _), (0, let a, _): // OK
return a
case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}}
return a
}
}
func breakContinue(_ x : Int) -> Int {
Outer:
for _ in 0...1000 {
Switch:
switch x {
case 42: break Outer
case 97: continue Outer
case 102: break Switch
case 13: continue
case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements
}
}
// <rdar://problem/16692437> shadowing loop labels should be an error
Loop: // expected-note {{previously declared here}}
for _ in 0...2 {
Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}}
for _ in 0...2 {
}
}
// <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it
switch 5 {
case 5:
markUsed("before the break")
break
markUsed("after the break") // 'markUsed' is not a label for the break.
default:
markUsed("")
}
let x : Int? = 42
// <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals
switch x {
case .some(42): break
case nil: break
}
}
enum MyEnumWithCaseLabels {
case Case(one: String, two: Int)
}
func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) {
// <rdar://problem/20135489> Enum case labels are ignored in "case let" statements
switch a {
case let .Case(one: _, two: x): break // ok
case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}}
// TODO: In principle, reordering like this could be supported.
case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}}
}
}
// "defer"
func test_defer(_ a : Int) {
defer { VoidReturn1() }
defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}}
// Ok:
defer { while false { break } }
// Not ok.
while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}}
defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}}
}
class SomeTestClass {
var x = 42
func method() {
defer { x = 97 } // self. not required here!
}
}
func test_guard(_ x : Int, y : Int??, cond : Bool) {
// These are all ok.
guard let a = y else {}
markUsed(a)
guard let b = y, cond else {}
guard case let c = x, cond else {}
guard case let Optional.some(d) = y else {}
guard x != 4, case _ = x else { }
guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard let g = y else {
markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}}
guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}}
}
func test_is_as_patterns() {
switch 4 {
case is Int: break // expected-warning {{'is' test is always true}}
case _ as Int: break // expected-warning {{'as' test is always true}}
case _: break
}
}
// <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...)
func matching_pattern_recursion() {
switch 42 {
case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}}
for i in zs {
}
}: break
}
}
// <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors
func r18776073(_ a : Int?) {
switch a {
case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}}
case _?: break
}
}
// <rdar://problem/22491782> unhelpful error message from "throw nil"
func testThrowNil() throws {
throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}}
}
// rdar://problem/23684220
// Even if the condition fails to typecheck, save it in the AST anyway; the old
// condition may have contained a SequenceExpr.
func r23684220(_ b: Any) {
if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}}
}
// <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics
func f21080671() {
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
} catch { }
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
f21080671()
} catch let x as Int {
} catch {
}
}
// <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma
// https://twitter.com/radexp/status/694561060230184960
func f(_ x : Int, y : Int) {
if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}}
// https://twitter.com/radexp/status/694790631881883648
if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}}
}
// <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause
enum Type {
case Foo
case Bar
}
func r25178926(_ a : Type) {
switch a {
case .Foo, .Bar where 1 != 100:
// expected-warning @-1 {{'where' only applies to the second pattern match in this case}}
// expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }}
// expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}}
break
}
switch a {
case .Foo: break
case .Bar where 1 != 100: break
}
switch a {
case .Foo, // no warn
.Bar where 1 != 100:
break
}
switch a {
case .Foo where 1 != 100, .Bar where 1 != 100:
break
}
}
do {
guard 1 == 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
}
func fn(a: Int) {
guard a < 1 else {
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
}
}
func fn(x: Int) {
if x >= 0 {
guard x < 1 else {
guard x < 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
return
}
}
}
// Errors in case syntax
class
case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}}
case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}}
// NOTE: EOF is important here to properly test a code path that used to crash the parser
| apache-2.0 | 3dd66804cda843b6f2ce90989954a859 | 26.54509 | 276 | 0.626119 | 3.544353 | false | false | false | false |
google/JacquardSDKiOS | JacquardSDK/Classes/Internal/IMUDataCollectionAPI/Module.swift | 1 | 2997 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Errors that can be encountered while sending module commands.
public enum ModuleError: Error {
/// Module was not loaded in the device.
case moduleUnavailable
/// Failed to load module on the device and activate it.
case failedToLoadModule
/// Failed to activate the module.
case failedToActivateModule
/// Failed to deactivate the module.
case failedToDeactivateModule
/// Invalid response received.
case invalidResponse
/// The provided parameter is not valid or not within the supported range.
case invalidParameter
/// Request timed out.
case timedOut
/// File Manager error.
case directoryUnavailable
/// Error when there is already a download in progress.
case downloadInProgress
/// Error when empty data is recieved from the tag.
case emptyDataReceived
}
/// An object that holds information of a loadable module.
public struct Module {
/// The module name.
let name: String
/// The module identifier.
let moduleID: Identifier
/// The vendor identifier.
let vendorID: Identifier
/// The product identifier.
let productID: Identifier
/// The version of this module.
let version: Version?
/// `true` if the module is enabled. i.e. activated.
let isEnabled: Bool
init(moduleDescriptor: Google_Jacquard_Protocol_ModuleDescriptor) {
self.name = moduleDescriptor.name
self.moduleID = moduleDescriptor.moduleID
self.vendorID = moduleDescriptor.vendorID
self.productID = moduleDescriptor.productID
self.version = Version(
major: moduleDescriptor.verMajor,
minor: moduleDescriptor.verMinor,
micro: moduleDescriptor.verPoint
)
self.isEnabled = moduleDescriptor.isEnabled
}
init(
name: String,
moduleID: Identifier,
vendorID: Identifier,
productID: Identifier,
version: Version?,
isEnabled: Bool
) {
self.name = name
self.moduleID = moduleID
self.vendorID = vendorID
self.productID = productID
self.version = version
self.isEnabled = isEnabled
}
func getModuleDescriptorRequest() -> Google_Jacquard_Protocol_ModuleDescriptor {
return Google_Jacquard_Protocol_ModuleDescriptor.with { moduleDescriptor in
moduleDescriptor.moduleID = self.moduleID
moduleDescriptor.vendorID = self.vendorID
moduleDescriptor.productID = self.productID
moduleDescriptor.name = self.name
}
}
}
| apache-2.0 | 4aaea06edd12d4945ce0fc1f971efbee | 27.009346 | 82 | 0.728729 | 4.719685 | false | false | false | false |
naoto0822/try-reactive-swift | TrySwiftBond/TrySwiftBond/APIRouter.swift | 1 | 2181 | //
// APIRouter.swift
// TrySwiftBond
//
// Created by naoto yamaguchi on 2016/04/13.
// Copyright © 2016年 naoto yamaguchi. All rights reserved.
//
import UIKit
import Alamofire
extension API {
public enum Router: URLRequestConvertible {
case AllItem(page: String)
case StockItem(page: String, id: String)
private var method: Alamofire.Method {
switch self {
case .AllItem(_):
return .GET
case .StockItem(_, _):
return .GET
}
}
private var headers: [String: String] {
var headers = [String: String]()
// TODO:
// get token after login.
return headers
}
private var baseURL: String {
return "https://qiita.com/api/v2"
}
private var path: String {
switch self {
case .AllItem(_):
return "/items"
case .StockItem(_, let id):
return "/\(id)/stocks"
}
}
private var parameters: [String: AnyObject] {
var parameters = [String: AnyObject]()
parameters["per_page"] = "20"
switch self {
case .AllItem(let page):
parameters["page"] = page
case .StockItem(let page, _):
parameters["page"] = page
}
print(parameters)
return parameters
}
public var URLRequest: NSMutableURLRequest {
let URL = NSURL(string: self.baseURL)!
let request = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(self.path))
request.HTTPMethod = self.method.rawValue
switch self {
case .AllItem(_):
return Alamofire.ParameterEncoding.URL.encode(request, parameters: self.parameters).0
case .StockItem(_, _):
return Alamofire.ParameterEncoding.URL.encode(request, parameters: self.parameters).0
}
}
}
}
| mit | 4fc9926e3b8037f4dacad5da2e7533b0 | 27.657895 | 101 | 0.495409 | 5.286408 | false | false | false | false |
adrianobragaalencar/CustomCameraSwift | CustomCamera/CustomCamera/CameraPreviewView.swift | 1 | 1113 | //
// CameraPreviewView.swift
// CustomCamera
//
// Created by Adriano Braga on 31/03/15.
// Copyright (c) 2015 YattaTech. All rights reserved.
//
import UIKit
import AVFoundation
public final class CameraPreviewView: UIView {
public var orientation: AVCaptureVideoOrientation?
public var session: AVCaptureSession? {
get {
let previewLayer = layer as! AVCaptureVideoPreviewLayer
return previewLayer.session
}
set {
let previewLayer = layer as! AVCaptureVideoPreviewLayer
previewLayer.session = newValue
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
if previewLayer.connection.supportsVideoOrientation {
previewLayer.connection.videoOrientation = orientation ?? .LandscapeRight
}
}
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
orientation = .LandscapeRight
}
public class override func layerClass() -> AnyClass {
return AVCaptureVideoPreviewLayer.self
}
}
| apache-2.0 | 001c0fcc8800ee395ed8c62d7b78e4f4 | 28.289474 | 89 | 0.659479 | 5.678571 | false | false | false | false |
khizkhiz/swift | test/SILGen/objc_witnesses.swift | 1 | 3394 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
protocol Fooable {
func foo() -> String!
}
// Witnesses Fooable.foo with the original ObjC-imported -foo method .
extension Foo: Fooable {}
class Phoûx : NSObject, Fooable {
@objc func foo() -> String! {
return "phoûx!"
}
}
// witness for Foo.foo uses the foreign-to-native thunk:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo3Foo14objc_witnesses7FooableS0_FS1_3foo
// CHECK: function_ref @_TTOFCSo3Foo3foo
// *NOTE* We have an extra copy here for the time being right
// now. This will change once we teach SILGen how to not emit the
// extra copy.
//
// witness for Phoûx.foo uses the Swift vtable
// CHECK-LABEL: _TFC14objc_witnessesX8Phox_xra3foo
// CHECK: bb0([[IN_ADDR:%.*]] :
// CHECK: [[STACK_SLOT:%.*]] = alloc_stack $Phoûx
// CHECK: copy_addr [[IN_ADDR]] to [initialization] [[STACK_SLOT]]
// CHECK: [[VALUE:%.*]] = load [[STACK_SLOT]]
// CHECK: class_method [[VALUE]] : $Phoûx, #Phoûx.foo!1
protocol Bells {
init(bellsOn: Int)
}
extension Gizmo : Bells {
}
// CHECK: sil hidden [transparent] [thunk] @_TTWCSo5Gizmo14objc_witnesses5BellsS0_FS1_C
// CHECK: bb0([[SELF:%[0-9]+]] : $*Gizmo, [[I:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick Gizmo.Type):
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFCSo5GizmoC{{.*}} : $@convention(thin) (Int, @thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(thin) (Int, @thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: [[UNWRAP_FUNC:%[0-9]+]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: [[UNWRAPPED_RESULT_TEMP:%[0-9]+]] = alloc_stack $Gizmo
// CHECK: apply [[UNWRAP_FUNC]]<Gizmo>([[UNWRAPPED_RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0
// CHECK: [[UNWRAPPED_RESULT:%[0-9]+]] = load [[UNWRAPPED_RESULT_TEMP]] : $*Gizmo
// CHECK: store [[UNWRAPPED_RESULT]] to [[SELF]] : $*Gizmo
// CHECK: dealloc_stack [[UNWRAPPED_RESULT_TEMP]] : $*Gizmo
// CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<Gizmo>
// Test extension of a native @objc class to conform to a protocol with a
// subscript requirement. rdar://problem/20371661
protocol Subscriptable {
subscript(x: Int) -> AnyObject { get }
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo7NSArray14objc_witnesses13SubscriptableS0_FS1_g9subscriptFSiPs9AnyObject_ : $@convention(witness_method) (Int, @in_guaranteed NSArray) -> @owned AnyObject {
// CHECK: function_ref @_TTOFCSo7NSArrayg9subscriptFSiPs9AnyObject_ : $@convention(method) (Int, @guaranteed NSArray) -> @owned AnyObject
// CHECK-LABEL: sil shared @_TTOFCSo7NSArrayg9subscriptFSiPs9AnyObject_ : $@convention(method) (Int, @guaranteed NSArray) -> @owned AnyObject {
// CHECK: class_method [volatile] %1 : $NSArray, #NSArray.subscript!getter.1.foreign
extension NSArray: Subscriptable {}
| apache-2.0 | 28796219cf011d76592ae32f75770bb8 | 46.676056 | 213 | 0.675628 | 3.422649 | false | false | false | false |
srn214/Floral | Floral/Pods/WCDB.swift/swift/source/core/interface/MultiSelect.swift | 1 | 5484 | /*
* Tencent is pleased to support the open source community by making
* WCDB available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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
/// Chain call for multi-selecting
public final class MultiSelect: Selectable {
private let keys: [CodingTableKeyBase]
init(with core: Core,
on propertyConvertibleList: [PropertyConvertible],
tables: [String],
isDistinct: Bool = false) throws {
guard propertyConvertibleList.count > 0 else {
throw Error.reportInterface(tag: core.tag,
path: core.path,
operation: .select,
code: .misuse,
message: "Selecting nothing from \(tables) is invalid")
}
guard tables.count > 0 else {
throw Error.reportInterface(tag: core.tag,
path: core.path,
operation: .select,
code: .misuse,
message: "Empty table")
}
self.keys = propertyConvertibleList.map({ (propertyConvertible) -> CodingTableKeyBase in
let codingTableKey = propertyConvertible.codingTableKey
assert(codingTableKey.rootType is TableDecodableBase.Type,
"\(codingTableKey.rootType) must conform to TableDecodable protocol.")
return codingTableKey
})
let statement = StatementSelect().select(distinct: isDistinct, propertyConvertibleList).from(tables)
super.init(with: core, statement: statement)
}
private typealias Generator = () throws -> TableDecodableBase
struct TypedIndexedKeys {
let type: TableDecodableBase.Type
var indexedKeys: TableDecoder.HashedKey
init(_ type: TableDecodableBase.Type, key: String, index: Int) {
self.type = type
self.indexedKeys = [key.hashValue: index]
}
}
private lazy var generators: [String: Generator] = {
var mappedKeys: [String: TypedIndexedKeys] = [:]
let handleStatement = try? lazyHandleStatement()
assert(handleStatement != nil,
"It should not be failed. If you think it's a bug, please report an issue to us.")
for (index, key) in keys.enumerated() {
let tableName = handleStatement!.columnTableName(atIndex: index)
var typedIndexedKeys: TypedIndexedKeys! = mappedKeys[tableName]
if typedIndexedKeys == nil {
let tableDecodableType = key.rootType as? TableDecodableBase.Type
assert(tableDecodableType != nil,
"\(key.rootType) must conform to TableDecodable protocol.")
typedIndexedKeys = TypedIndexedKeys(tableDecodableType!, key: key.stringValue, index: index)
} else {
typedIndexedKeys.indexedKeys[key.stringValue.hashValue] = index
}
mappedKeys[tableName] = typedIndexedKeys
}
var generators: [String: Generator] = [:]
for (tableName, typedIndexedKey) in mappedKeys {
let decoder = TableDecoder(typedIndexedKey.indexedKeys, on: optionalRecyclableHandleStatement!)
let type = typedIndexedKey.type
let generator = { () throws -> TableDecodableBase in
return try type.init(from: decoder)
}
generators[tableName] = generator
}
return generators
}()
private func extractMultiObject() throws -> [String: TableDecodableBase] {
var multiObject: [String: TableDecodableBase] = [:]
for (tableName, generator) in generators {
multiObject[tableName] = try generator()
}
return multiObject
}
/// Get next selected object. You can do an iteration using it.
///
/// while let multiObject = try self.nextMultiObject() {
/// let object1 = multiObject[tableName1]
/// let object2 = multiObject[tableName2]
/// //...
/// }
///
/// - Returns: Mapping from table name to object. Nil means the end of iteration.
/// - Throws: `Error`
public func nextMultiObject() throws -> [String: TableDecodableBase]? {
guard try next() else {
return nil
}
return try extractMultiObject()
}
/// Get all selected objects.
///
/// - Returns: Array contained mapping from table name to object.
/// - Throws: `Error`
public func allMultiObjects() throws -> [[String: TableDecodableBase]] {
var multiObjects: [[String: TableDecodableBase]] = []
while try next() {
multiObjects.append(try extractMultiObject())
}
return multiObjects
}
}
| mit | feb1238755757c1ea3a85ba60f2be3ee | 40.545455 | 108 | 0.601386 | 5.101395 | false | false | false | false |
dleonard00/firebase-user-signup | Pods/Material/Sources/MaterialColor.swift | 1 | 28342 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public struct MaterialColor {
// clear
public static let clear: UIColor = UIColor.clearColor()
// white
public static let white: UIColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
// black
public static let black: UIColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
// red
public struct red {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 235/255, blue: 238/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 205/255, blue: 210/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 239/255, green: 154/255, blue: 254/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 229/255, green: 115/255, blue: 115/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 229/255, green: 83/255, blue: 80/255, alpha: 1)
public static let base: UIColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 211/255, green: 47/255, blue: 47/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 198/255, green: 40/255, blue: 40/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 183/255, green: 28/255, blue: 28/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 138/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 82/255, blue: 82/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 23/255, blue: 68/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 213/255, green: 0/255, blue: 0/255, alpha: 1)
}
// pink
public struct pink {
public static let lighten5: UIColor = UIColor(red: 252/255, green: 228/255, blue: 236/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 248/255, green: 107/255, blue: 208/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 244/255, green: 143/255, blue: 177/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 240/255, green: 98/255, blue: 146/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 236/255, green: 64/255, blue: 122/255, alpha: 1)
public static let base: UIColor = UIColor(red: 233/255, green: 30/255, blue: 99/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 216/255, green: 27/255, blue: 96/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 194/255, green: 24/255, blue: 191/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 173/255, green: 20/255, blue: 87/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 136/255, green: 14/255, blue: 79/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 128/255, blue: 171/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 245/255, green: 0/255, blue: 87/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 197/255, green: 17/255, blue: 98/255, alpha: 1)
}
// purple
public struct purple {
public static let lighten5: UIColor = UIColor(red: 243/255, green: 229/255, blue: 245/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 190/255, blue: 231/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 206/255, green: 147/255, blue: 216/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 186/255, green: 104/255, blue: 200/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 171/255, green: 71/255, blue: 188/255, alpha: 1)
public static let base: UIColor = UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 142/255, green: 36/255, blue: 170/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 106/255, green: 27/255, blue: 154/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 74/255, green: 20/255, blue: 140/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 234/255, green: 128/255, blue: 252/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 224/255, green: 64/255, blue: 251/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 213/255, green: 0/255, blue: 249/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 170/255, green: 0/255, blue: 255/255, alpha: 1)
}
// deepPurple
public struct deepPurple {
public static let lighten5: UIColor = UIColor(red: 237/255, green: 231/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 209/255, green: 196/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 179/255, green: 157/255, blue: 219/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 149/255, green: 117/255, blue: 205/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 126/255, green: 87/255, blue: 194/255, alpha: 1)
public static let base: UIColor = UIColor(red: 103/255, green: 58/255, blue: 183/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 94/255, green: 53/255, blue: 177/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 81/255, green: 45/255, blue: 168/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 69/255, green: 39/255, blue: 160/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 49/255, green: 27/255, blue: 146/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 179/255, green: 136/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 124/255, green: 77/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 101/255, green: 31/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 98/255, green: 0/255, blue: 234/255, alpha: 1)
}
// indigo
public struct indigo {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 197/255, green: 202/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 159/255, green: 168/255, blue: 218/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 121/255, green: 134/255, blue: 203/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 92/255, green: 107/255, blue: 192/255, alpha: 1)
public static let base: UIColor = UIColor(red: 63/255, green: 81/255, blue: 181/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 57/255, green: 73/255, blue: 171/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 48/255, green: 63/255, blue: 159/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 40/255, green: 53/255, blue: 147/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 26/255, green: 35/255, blue: 126/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 140/255, green: 158/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 83/255, green: 109/255, blue: 254/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 61/255, green: 90/255, blue: 254/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 48/255, green: 79/255, blue: 254/255, alpha: 1)
}
// blue
public struct blue {
public static let lighten5: UIColor = UIColor(red: 227/255, green: 242/255, blue: 253/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 187/255, green: 222/255, blue: 251/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 144/255, green: 202/255, blue: 249/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 100/255, green: 181/255, blue: 246/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 66/255, green: 165/255, blue: 245/255, alpha: 1)
public static let base: UIColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 30/255, green: 136/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 25/255, green: 118/255, blue: 210/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 13/255, green: 71/255, blue: 161/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 130/255, green: 177/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 68/255, green: 138/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 41/255, green: 121/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 41/255, green: 98/255, blue: 255/255, alpha: 1)
}
// light blue
public struct lightBlue {
public static let lighten5: UIColor = UIColor(red: 225/255, green: 245/255, blue: 254/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 179/255, green: 229/255, blue: 252/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 129/255, green: 212/255, blue: 250/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 79/255, green: 195/255, blue: 247/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 41/255, green: 182/255, blue: 246/255, alpha: 1)
public static let base: UIColor = UIColor(red: 3/255, green: 169/255, blue: 244/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 3/255, green: 155/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 2/255, green: 136/255, blue: 209/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 2/255, green: 119/255, blue: 189/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 1/255, green: 87/255, blue: 155/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 128/255, green: 216/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 64/255, green: 196/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 176/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 145/255, blue: 234/255, alpha: 1)
}
// cyan
public struct cyan {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 247/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 178/255, green: 235/255, blue: 242/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 222/255, blue: 2343/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 208/255, blue: 225/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 198/255, blue: 218/255, alpha: 1)
public static let base: UIColor = UIColor(red: 0/255, green: 188/255, blue: 212/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 172/255, blue: 193/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 151/255, blue: 167/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 131/255, blue: 143/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 96/255, blue: 100/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 132/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 24/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 229/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 184/255, blue: 212/255, alpha: 1)
}
// teal
public struct teal {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 242/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 178/255, green: 223/255, blue: 219/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 203/255, blue: 196/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 182/255, blue: 172/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 166/255, blue: 154/255, alpha: 1)
public static let base: UIColor = UIColor(red: 0/255, green: 150/255, blue: 136/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 137/255, blue: 123/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 121/255, blue: 107/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 105/255, blue: 92/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 77/255, blue: 64/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 167/255, green: 255/255, blue: 235/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 100/255, green: 255/255, blue: 218/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 29/255, green: 133/255, blue: 182/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1)
}
// green
public struct green {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 245/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 200/255, green: 230/255, blue: 201/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 165/255, green: 214/255, blue: 167/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 129/255, green: 199/255, blue: 132/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 102/255, green: 187/255, blue: 106/255, alpha: 1)
public static let base: UIColor = UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 67/255, green: 160/255, blue: 71/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 56/255, green: 142/255, blue: 60/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 46/255, green: 125/255, blue: 50/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 27/255, green: 94/255, blue: 32/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 185/255, green: 246/255, blue: 202/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 105/255, green: 240/255, blue: 174/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 230/255, blue: 118/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 200/255, blue: 83/255, alpha: 1)
}
// light green
public struct lightGreen {
public static let lighten5: UIColor = UIColor(red: 241/255, green: 248/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 220/255, green: 237/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 197/255, green: 225/255, blue: 165/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 174/255, green: 213/255, blue: 129/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 156/255, green: 204/255, blue: 101/255, alpha: 1)
public static let base: UIColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 124/255, green: 179/255, blue: 66/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 104/255, green: 159/255, blue: 56/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 85/255, green: 139/255, blue: 47/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 51/255, green: 105/255, blue: 30/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 204/255, green: 255/255, blue: 144/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 178/255, green: 255/255, blue: 89/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 118/255, green: 255/255, blue: 3/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 100/255, green: 221/255, blue: 23/255, alpha: 1)
}
// lime
public struct lime {
public static let lighten5: UIColor = UIColor(red: 249/255, green: 251/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 240/255, green: 244/255, blue: 195/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 230/255, green: 238/255, blue: 156/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 220/255, green: 231/255, blue: 117/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 212/255, green: 225/255, blue: 87/255, alpha: 1)
public static let base: UIColor = UIColor(red: 205/255, green: 220/255, blue: 57/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 192/255, green: 202/255, blue: 51/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 175/255, green: 180/255, blue: 43/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 158/255, green: 157/255, blue: 36/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 130/255, green: 119/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 244/255, green: 255/255, blue: 129/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 238/255, green: 255/255, blue: 65/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 198/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 174/255, green: 234/255, blue: 0/255, alpha: 1)
}
// yellow
public struct yellow {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 253/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 249/255, blue: 196/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 245/255, blue: 157/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 241/255, blue: 118/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 238/255, blue: 88/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 235/255, blue: 59/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 253/255, green: 216/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 251/255, green: 192/255, blue: 45/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 249/255, green: 168/255, blue: 37/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 245/255, green: 127/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 255/255, blue: 141/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 234/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 214/255, blue: 0/255, alpha: 1)
}
// amber
public struct amber {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 248/255, blue: 225/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 236/255, blue: 179/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 224/255, blue: 130/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 213/255, blue: 79/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 202/255, blue: 40/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 193/255, blue: 7/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 255/255, green: 160/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 255/255, green: 143/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 255/255, green: 111/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 229/255, blue: 127/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 215/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 196/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 171/255, blue: 0/255, alpha: 1)
}
// orange
public struct orange {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 243/255, blue: 224/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 224/255, blue: 178/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 204/255, blue: 128/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 183/255, blue: 77/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 167/255, blue: 38/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 152/255, blue: 0/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 251/255, green: 140/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 245/255, green: 124/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 239/255, green: 108/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 230/255, green: 81/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 209/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 171/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 145/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 109/255, blue: 0/255, alpha: 1)
}
// deep orange
public struct deepOrange {
public static let lighten5: UIColor = UIColor(red: 251/255, green: 233/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 204/255, blue: 188/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 171/255, blue: 145/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 138/255, blue: 101/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 112/255, blue: 67/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 87/255, blue: 34/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 244/255, green: 81/255, blue: 30/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 230/255, green: 74/255, blue: 25/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 216/255, green: 67/255, blue: 21/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 191/255, green: 54/255, blue: 12/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 158/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 110/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 61/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 221/255, green: 44/255, blue: 0/255, alpha: 1)
}
// brown
public struct brown {
public static let lighten5: UIColor = UIColor(red: 239/255, green: 235/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 215/255, green: 204/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 188/255, green: 170/255, blue: 164/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 161/255, green: 136/255, blue: 127/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 141/255, green: 110/255, blue: 99/255, alpha: 1)
public static let base: UIColor = UIColor(red: 121/255, green: 85/255, blue: 72/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 109/255, green: 76/255, blue: 65/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 93/255, green: 64/255, blue: 55/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 78/255, green: 52/255, blue: 46/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 62/255, green: 39/255, blue: 35/255, alpha: 1)
}
// grey
public struct grey {
public static let lighten5: UIColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 189/255, green: 189/255, blue: 189/255, alpha: 1)
public static let base: UIColor = UIColor(red: 158/255, green: 158/255, blue: 158/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 117/255, green: 117/255, blue: 117/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 97/255, green: 97/255, blue: 97/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 66/255, green: 66/255, blue: 66/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1)
}
// blue grey
public struct blueGrey {
public static let lighten5: UIColor = UIColor(red: 236/255, green: 239/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 207/255, green: 216/255, blue: 220/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 176/255, green: 190/255, blue: 197/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 144/255, green: 164/255, blue: 174/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 120/255, green: 144/255, blue: 156/255, alpha: 1)
public static let base: UIColor = UIColor(red: 96/255, green: 125/255, blue: 139/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 84/255, green: 110/255, blue: 122/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 69/255, green: 90/255, blue: 100/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 55/255, green: 71/255, blue: 79/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 38/255, green: 50/255, blue: 56/255, alpha: 1)
}
}
| mit | d881a20be9614b880487458fc20c1d36 | 74.780749 | 103 | 0.704396 | 3.040335 | false | false | false | false |
hsusmita/SHRichTextEditorTools | SHRichTextEditorTools/Source/SHRichTextEditor/UIViewController+Helper.swift | 1 | 1217 | //
// UIViewController+Helper.swift
// SHRichTextEditor
//
// Created by Susmita Horrow on 11/01/17.
// Copyright © 2017 hsusmita. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
public static var topMostController: UIViewController? {
var topController: UIViewController? = nil
guard let window = UIApplication.shared.keyWindow else {
return nil
}
topController = window.rootViewController
repeat {
if let newTopController = topController {
switch newTopController {
case (let newTopController as UINavigationController) where newTopController.visibleViewController != nil:
topController = newTopController.visibleViewController
case (let newTopController as UITabBarController) where newTopController.selectedViewController != nil:
topController = newTopController.selectedViewController
default:
if let presentedController = newTopController.presentedViewController {
topController = presentedController
}
}
}
} while (topController?.presentedViewController != nil)
return topController
}
final public var isTopMostController: Bool {
return (self === UIViewController.topMostController)
}
}
| mit | c09e8f8ca238c1bd97fa70a741299318 | 29.4 | 110 | 0.762336 | 4.983607 | false | false | false | false |
jkolb/Shkadov | Shkadov/RenderableObject.swift | 1 | 4978 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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 simd
class RenderableObject
{
let mesh : GPUBufferHandle
let indexBuffer : GPUBufferHandle
let texture : TextureHandle
var count : Int
var scale : vector_float3 = float3(1.0)
var position : vector_float4
var rotation : vector_float3
var rotationRate : vector_float3
var objectData : ObjectData
init()
{
self.mesh = GPUBufferHandle()
self.indexBuffer = GPUBufferHandle()
self.texture = TextureHandle()
self.count = 0
self.objectData = ObjectData()
self.objectData.LocalToWorld = matrix_identity_float4x4
self.position = vector_float4(0.0, 0.0, 0.0, 1.0)
self.rotation = float3(0.0, 0.0, 0.0)
self.rotationRate = float3(0.0, 0.0, 0.0)
}
init(m : GPUBufferHandle, idx : GPUBufferHandle, count : Int, tex : TextureHandle)
{
self.mesh = m
self.indexBuffer = idx
self.texture = tex
self.count = count
self.objectData = ObjectData()
self.objectData.LocalToWorld = matrix_identity_float4x4
self.objectData.color = float4(0.0, 0.0, 0.0, 0.0)
self.objectData.pad1 = matrix_identity_float4x4
self.objectData.pad2 = matrix_identity_float4x4
self.position = vector_float4(0.0, 0.0, 0.0, 1.0)
self.rotation = float3(0.0, 0.0, 0.0)
self.rotationRate = float3(0.0, 0.0, 0.0)
}
func SetRotationRate(_ rot : vector_float3)
{
rotationRate = rot
}
func UpdateData(_ dest : UnsafeMutablePointer<ObjectData>, deltaTime : Float) -> UnsafeMutablePointer<ObjectData>
{
rotation += rotationRate * deltaTime
objectData.LocalToWorld = getScaleMatrix(scale.x, y: scale.y, z: scale.z)
objectData.LocalToWorld = matrix_multiply(getRotationAroundX(rotation.x), objectData.LocalToWorld)
objectData.LocalToWorld = matrix_multiply(getRotationAroundY(rotation.y), objectData.LocalToWorld)
objectData.LocalToWorld = matrix_multiply(getRotationAroundZ(rotation.z), objectData.LocalToWorld)
objectData.LocalToWorld = matrix_multiply(getTranslationMatrix(position), objectData.LocalToWorld)
dest.pointee = objectData
return dest.advanced(by: 1)
}
func DrawZPass(_ enc :RenderCommandEncoder, offset : Int)
{
enc.setVertexBufferOffset(offset, at: 1)
if(indexBuffer.isValid)
{
enc.drawIndexedPrimitives(type: .triangle, indexCount: count, indexType: .uint16, indexBuffer: indexBuffer, indexBufferOffset: 0)
}
else
{
enc.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count)
}
}
func Draw(_ enc : RenderCommandEncoder, offset : Int)
{
enc.setVertexBufferOffset(offset, at: 1)
enc.setFragmentBufferOffset(offset, at: 1)
if(indexBuffer.isValid)
{
enc.drawIndexedPrimitives(type: .triangle, indexCount: count, indexType: .uint16, indexBuffer: indexBuffer, indexBufferOffset: 0)
}
else
{
enc.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count)
}
}
}
class StaticRenderableObject : RenderableObject
{
override func UpdateData(_ dest: UnsafeMutablePointer<ObjectData>, deltaTime: Float) -> UnsafeMutablePointer<ObjectData>
{
return dest
}
override func Draw(_ enc: RenderCommandEncoder, offset: Int)
{
enc.setVertexBuffer(mesh, offset: 0, at: 0)
enc.setVertexBytes(&objectData, length: MemoryLayout<ObjectData>.size, at: 1)
enc.setFragmentBytes(&objectData, length: MemoryLayout<ObjectData>.size, at: 1)
enc.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count)
}
}
| mit | 72fadccd246d14d336577effb8a2a672 | 35.072464 | 141 | 0.667738 | 4.413121 | false | false | false | false |
naokits/my-programming-marathon | ParseLoginDemo/ParseLoginDemo/ViewController.swift | 1 | 3577 | //
// ViewController.swift
// ParseLoginDemo
//
// Created by Naoki Tsutsui on 1/15/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
import ParseUI
class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
guard let currentUser = User.currentUser() else {
login()
return
}
print("ログイン中のユーザ: \(currentUser)")
currentUser.japaneseDate = NSDate()
currentUser.saveInBackground()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func signup() {
let controller = PFSignUpViewController()
controller.delegate = self
self.presentViewController(controller, animated:false, completion: nil)
}
func login() {
let controller = PFLogInViewController()
// controller.logInView?.logo = UIImageView(image: UIImage(named: ""))
controller.delegate = self
self.presentViewController(controller, animated:true, completion: nil)
}
// MARK:- PFSignUpViewControllerDelegate
func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) {
guard let e = error else {
return
}
print("サインアップエラー: \(e)")
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
print("サインアップ成功: \(user)")
}
func signUpViewController(signUpController: PFSignUpViewController, shouldBeginSignUp info: [String : String]) -> Bool {
print("Info: \(info)")
return true
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) {
print("サインアップがキャンセルされた")
}
// MARK:- PFLogInViewControllerDelegate
func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) {
guard let e = error else {
return
}
print("ログインエラー: \(e)")
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
print("ログイン成功: \(user)")
dismissViewControllerAnimated(true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool {
print("Info: \(username)")
return true
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) {
print("ログインがキャンセルされた")
}
// MARK:- Location
func saveCurrentLocation() {
let location = Location()
location.japaneseDate = NSDate()
location.geo = PFGeoPoint(latitude: 0.0, longitude: 0.0)
location.saveInBackground().continueWithBlock { (task) -> AnyObject? in
if let error = task.error {
print("保存失敗: \(error)")
} else {
print("保存成功")
}
return nil
}
}
}
| mit | 160b50d1f7fc586072da452caa93d16f | 28.791304 | 143 | 0.637186 | 5.429477 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.FilterLifeLevel.swift | 1 | 2045 | import Foundation
public extension AnyCharacteristic {
static func filterLifeLevel(
_ value: Float = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Filter Life Level",
format: CharacteristicFormat? = .float,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 100,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.filterLifeLevel(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func filterLifeLevel(
_ value: Float = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Filter Life Level",
format: CharacteristicFormat? = .float,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 100,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Float> {
GenericCharacteristic<Float>(
type: .filterLifeLevel,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | bbab1d3bbda7424d9eca06e8382d0e1e | 32.52459 | 67 | 0.577017 | 5.381579 | false | false | false | false |
kyouko-taiga/anzen | Sources/AnzenIR/AIRUnit.swift | 1 | 2025 | import AST
public class AIRUnit: CustomStringConvertible {
public init(name: String) {
self.name = name
}
/// The name of the unit.
public let name: String
public var description: String {
return functions.values.map(prettyPrint).sorted().joined(separator: "\n")
}
// MARK: Functions
/// Create or get the existing function with the given name and type.
public func getFunction(name: String, type: AIRFunctionType)
-> AIRFunction
{
if let fn = functions[name] {
assert(fn.type == type, "AIR function conflicts with previous declaration")
return fn
}
let fn = AIRFunction(name: name, type: type)
functions[name] = fn
return fn
}
/// The functions of the unit.
public private(set) var functions: [String: AIRFunction] = [:]
// MARK: Types
public func getStructType(name: String) -> AIRStructType {
if let ty = structTypes[name] {
return ty
}
let ty = AIRStructType(name: name, members: [:])
structTypes[name] = ty
return ty
}
public func getFunctionType(from domain: [AIRType], to codomain: AIRType) -> AIRFunctionType {
if let existing = functionTypes.first(where: {
($0.domain == domain) && ($0.codomain == codomain)
}) {
return existing
} else {
let ty = AIRFunctionType(domain: domain, codomain: codomain)
functionTypes.append(ty)
return ty
}
}
/// The struct types of the unit.
public private(set) var structTypes: [String: AIRStructType] = [:]
/// The function types of the unit.
public private(set) var functionTypes: [AIRFunctionType] = []
}
private func prettyPrint(function: AIRFunction) -> String {
var result = "fun $\(function.name) : \(function.type)"
if function.blocks.isEmpty {
return result + "\n"
}
result += " {\n"
for (label, block) in function.blocks {
result += "\(label):\n"
for line in block.description.split(separator: "\n") {
result += " \(line)\n"
}
}
result += "}\n"
return result
}
| apache-2.0 | dff1d7cd8fadb288a16dddd785d4271f | 24.3125 | 96 | 0.639012 | 3.886756 | false | false | false | false |
signaturit/swift-sdk | Example/Signaturit/ViewController.swift | 1 | 4250 | //
// ViewController.swift
// Signaturit
//
// Created by Signaturit on 10/13/2015.
// Copyright (c) 2015 Signaturit. All rights reserved.
//
import UIKit
import Signaturit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func send() {
_send()
}
internal func _send() {
button.alpha = 0
activityIndicator.alpha = 1
webView.alpha = 0.5
let client: Signaturit = Signaturit(accessToken: "NGFhOWE3MjAwNThlMjY5M2M1MzQxZjNlOTY1M2U0MzhmNTlmMWE1NzIyMTdmMGQwYTkzZDBjOTg4YzZlMGY1NA", production: false)
// client.getSignature(signatureId: "635f2189-91ea-11e6-868f-0680f0041fef").responseJSON { response in
// print("signatures - getSignature")
// print(response.result.value!)
// }
// client.getSignatures(limit: 2, offset: 1).responseJSON { response in
// print("signatures - getSignatures with limit 2 & offset 1")
// print(response.result.value!)
// }
// client.getSignatures(conditions: ["status": "completed"] as Dictionary<String, AnyObject>).responseJSON { response in
// print("signatures - getSignatures with condition status = completed")
// print(response.result.value!)
// }
// client.getSignatures().responseJSON { response in
// print("signatures - getSignatures")
// print(response.result.value!)
// }
// client.countSignatures().responseJSON { response in
// print("signatures - countSignatures")
// print(response.result.value!)
// }
// client.countSignatures(conditions: ["status": "completed"] as Dictionary<String, AnyObject>).responseJSON { response in
// print("signatures - countSignatures with conditions")
// print(response.result.value!)
// }
// client.downloadAuditTrail(signatureId: "635f2189-91ea-11e6-868f-0680f0041fef", documentId: "637d60e1-91ea-11e6-868f-0680f0041fef", path: DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)).responseJSON { response in
// print("signatures - downloadAuditTrail")
// }
// client.downloadSignedDocument(signatureId: "635f2189-91ea-11e6-868f-0680f0041fef", documentId: "637d60e1-91ea-11e6-868f-0680f0041fef", path: DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)).responseJSON { response in
// print("signatures - downloadSignedDocument")
// }
client.createSignature(
files: [Bundle.main.url(forResource: "Document", withExtension: "pdf")!],
recipients: [["email": "[email protected]", "fullname": "Signaturit"]],
params: ["delivery_type": "url"] as Dictionary<String, AnyObject>,
successHandler: { response in
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.activityIndicator.alpha = 0
self.label.alpha = 1
self.webView.alpha = 1
})
let signature = JSON(response.result.value!)
let url = signature["url"].stringValue
self.webView.loadRequest(
URLRequest(
url: URL(string: url)!
)
)
}
)
// client.cancelSignature(signatureId: "8b935300-f622-11e7-aa80-0620c73c8b3c").responseJSON { response in
// print("signatures - cancelSignature")
// print(response.result.value!)
// }
// client.sendSignatureReminder(signatureId: "8b935300-f622-11e7-aa80-0620c73c8b3c").responseJSON { response in
// print("signatures - sendSignatureReminder")
// print(response.result.value!)
// }
}
}
| mit | f7dbe3b2ed31980347a2b8fabd718965 | 37.288288 | 248 | 0.615294 | 4.191321 | false | false | false | false |
Cleverlance/Pyramid | Sources/Common/Core/Infrastructure/Interval.swift | 1 | 496 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
public struct Interval<T> {
public let min: T?
public let max: T?
public init(min: T?, max: T?) {
self.min = min
self.max = max
}
}
public func == <T: Equatable>(lhs: Interval<T>, rhs: Interval<T>) -> Bool {
return lhs.min == rhs.min && lhs.max == rhs.max
}
public func == <T: Equatable>(lhs: Interval<T>?, rhs: Interval<T>?) -> Bool {
return lhs?.min == rhs?.min && lhs?.max == rhs?.max
}
| mit | c461a897deb2568a2a3861bfcfec4c46 | 22.571429 | 77 | 0.569697 | 3.173077 | false | false | false | false |
BurntCaramel/Reprise | Reprise/FirstViewController.swift | 1 | 3266 | //
// FirstViewController.swift
// Reprise
//
// Created by Patrick Smith on 30/06/2015.
// Copyright © 2015 Burnt Caramel. All rights reserved.
//
import UIKit
import SafariServices
enum LinkLoadingError: ErrorType {
case ResourceNotFound
case InvalidFile
}
struct Link {
var title: String
var URL: NSURL
}
class ItemTableViewCell: UITableViewCell {
@IBOutlet var titleLabel: UILabel!
}
class FirstViewController: UITableViewController {
var links = [Link]()
var safariViewController: SFSafariViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .None
do {
try loadLinksFromJSON()
tableView.setContentOffset(CGPointZero, animated: false)
//tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: false)
}
catch {
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.contentInset = UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: 0, right: 0)
}
func loadLinksFromJSON() throws {
let bundle = NSBundle.mainBundle()
guard let linkJSONURL = bundle.URLForResource("items", withExtension: "json") else {
throw LinkLoadingError.ResourceNotFound
}
guard let data = NSData(contentsOfURL: linkJSONURL) else {
throw LinkLoadingError.InvalidFile
}
guard let JSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String: AnyObject] else {
throw LinkLoadingError.InvalidFile
}
guard let linksJSON = JSON["items"] as? [[String: AnyObject]] else {
throw LinkLoadingError.InvalidFile
}
links.removeAll()
for linkJSON in linksJSON {
guard let
title = linkJSON["title"] as? String,
URLString = linkJSON["URL"] as? String,
URL = NSURL(string: URLString)
else
{
continue
}
let link = Link(title: title, URL: URL)
links.append(
link
)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func linkForIndexPath(indexPath: NSIndexPath) -> Link {
return links[indexPath.indexAtPosition(1)]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return links.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("link", forIndexPath: indexPath) as! ItemTableViewCell
let link = linkForIndexPath(indexPath)
cell.titleLabel.text = link.title
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let link = linkForIndexPath(indexPath)
print("didSelectRowAtIndexPath \(link)")
safariViewController = SFSafariViewController(URL: link.URL, entersReaderIfAvailable: false)
safariViewController.delegate = self
presentViewController(safariViewController, animated: true, completion: nil)
}
}
extension FirstViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
} | mit | db18098bc9d9870758962b6ecb31d478 | 24.317829 | 131 | 0.744564 | 4.388441 | false | false | false | false |
tehjord/ReSwiftSaga | ReSwiftSaga/Source/SagaModule.swift | 1 | 3877 | //
// SagaModule.swift
// ReSwiftSaga
//
// Created by Jordane Gagnon Belanger on 11/8/16.
// Copyright © 2016 tehjord. All rights reserved.
//
import ReSwift
fileprivate class SagaModuleTask {
var workItem: DispatchWorkItem!
var finished: Bool = false
}
open class SagaModule<SagaStoreType: StoreType> {
let store: SagaStoreType
private var tasks: [String: [SagaModuleTask]] = [:]
required public init(withStore store: SagaStoreType) {
self.store = store
}
public func dispatch<T: Saga where T.SagaStoreStateType == SagaStoreType.State>(_ saga: T) {
self.cleanUpSagas(withName: T.name)
switch T.type {
case .takeFirst:
takeFirst(saga: saga)
case .takeEvery:
takeEvery(saga: saga)
case .takeLatest:
takeLatest(saga: saga)
}
}
public func cancelSagas(withName name: String) {
guard let tasks = self.tasks[name] else {
return
}
for task in tasks {
task.finished = true
task.workItem.cancel()
}
self.tasks[name] = nil
}
public func cancelAllSagas() {
for taskGroup in self.tasks.values {
for task in taskGroup {
task.finished = true
task.workItem.cancel()
}
}
self.tasks.removeAll()
}
private func takeFirst<T: Saga where T.SagaStoreStateType == SagaStoreType.State>(saga: T) {
if let currentTask = self.tasks[T.name]?.first, currentTask.finished == false {
return // Ignoring the task if there is an ongoing takeFirst task for this Saga
}
let task = self.task(forSaga: saga)
self.tasks[T.name] = [task]
task.workItem.perform()
}
private func takeEvery<T: Saga where T.SagaStoreStateType == SagaStoreType.State>(saga: T) {
let task = self.task(forSaga: saga)
if self.tasks[T.name] != nil {
self.tasks[T.name]!.append(task)
} else {
self.tasks[T.name] = [task]
}
task.workItem.perform()
}
private func takeLatest<T: Saga where T.SagaStoreStateType == SagaStoreType.State>(saga: T) {
if let currentTask = self.tasks[T.name]?.first, currentTask.finished == false {
currentTask.finished = true
currentTask.workItem.cancel()
}
let task = self.task(forSaga: saga)
self.tasks[T.name] = [task]
task.workItem.perform()
}
private func task<T: Saga where T.SagaStoreStateType == SagaStoreType.State>(forSaga saga: T) -> SagaModuleTask {
let task = SagaModuleTask()
task.workItem = DispatchWorkItem { [weak self, weak task] in
guard let strongSagaModule = self, let strongTask = task, strongTask.finished == false else {
return
}
let finishCallback: () -> Void = { [weak strongTask] in
strongTask?.finished = true
}
saga.action(strongSagaModule.store.state, finishCallback) { [weak strongSagaModule, weak strongTask] dispatchFn in
guard let sagaModule = strongSagaModule, let task = strongTask, task.finished == false else {
return
}
let action = dispatchFn(sagaModule.store.state)
let _ = sagaModule.store.dispatch(action)
}
}
return task
}
private func cleanUpSagas(withName name: String) {
guard var tasks = self.tasks[name] else {
return
}
tasks = tasks.filter { $0.finished == false }
self.tasks[name] = tasks
}
}
| mit | 35212ef1fc90bcb3c2f40b327ae47474 | 29.046512 | 126 | 0.558308 | 4.543962 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Models/ConfigurationMDB.swift | 1 | 1963 | //
// ConfigurationMDB.swift
// MDBSwiftWrapper
//
// Created by George on 2016-02-15.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
import Foundation
public struct ConfigurationMDB {
public var base_url: String!
public var secure_base_url: String!
public var backdrop_sizes: [String]!
public var logo_sizes: [String]!
public var poster_sizes: [String]!
public var profile_sizes: [String]!
public var still_sizes: [String]!
public var change_keys: [String]!
init(results: JSON){
let images = results["images"]
base_url = images["base_url"].string
secure_base_url = images["secure_base_url"].string
backdrop_sizes = images["backdrop_sizes"].arrayObject as! [String]
logo_sizes = images["logo_sizes"].arrayObject as! [String]
poster_sizes = images["poster_sizes"].arrayObject as! [String]
profile_sizes = images["profile_sizes"].arrayObject as! [String]
still_sizes = images["still_sizes"].arrayObject as! [String]
change_keys = results["change_keys"].arrayObject as! [String]
}
///This method currently holds the data relevant to building image URLs as well as the change key map.To build an image URL, you will need 3 pieces of data. The base_url, size and file path; . Simply combine them all and you will have a fully qualified URL. Here’s an example URL: http://image.tmdb.org/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg
public static func configuration(api_key: String!, completion: (clientReturn: ClientReturn, data: ConfigurationMDB?) -> ()) -> (){
Client.Configuration(api_key){
apiReturn in
//var aReturn = apiReturn
if(apiReturn.error == nil){
completion(clientReturn: apiReturn, data: ConfigurationMDB.init(results: apiReturn.json!))
}else{
completion(clientReturn: apiReturn, data: nil)
}
}
}
} | mit | 9b3fc9fdfdcffa6a21d2971772cb289b | 41.630435 | 347 | 0.655612 | 4.06639 | false | true | false | false |
johnno1962/eidolon | KioskTests/Models/ImageTests.swift | 1 | 2261 | import Quick
import Nimble
@testable
import Kiosk
let size = CGSize(width: 100, height: 100)
class ImageTests: QuickSpec {
override func spec() {
let id = "wah-wah"
let url = "http://url.com"
it("converts from JSON") {
let imageFormats = ["big", "small", "patch"]
let data:[String: AnyObject] = [ "id": id, "image_url": url, "image_versions": imageFormats, "original_width": size.width, "original_height": size.height]
let image = Image.fromJSON(data)
expect(image.id) == id
expect(image.imageFormatString) == url
expect(image.imageVersions.count) == imageFormats.count
expect(image.imageSize) == size
}
it("generates a thumbnail url") {
var image = self.imageForVersion("large")
expect(image.thumbnailURL()).to(beAnInstanceOf(NSURL))
image = self.imageForVersion("medium")
expect(image.thumbnailURL()).to(beAnInstanceOf(NSURL))
image = self.imageForVersion("larger")
expect(image.thumbnailURL()).to(beAnInstanceOf(NSURL))
}
it("handles unknown image formats"){
let image = self.imageForVersion("unknown")
expect(image.thumbnailURL()).to(beNil())
}
it("handles incorrect image_versions JSON") {
let data:[String: AnyObject] = [ "id": id, "image_url": url, "image_versions": "something invalid"]
expect(Image.fromJSON(data)).toNot( throwError() )
}
it("assumes it's not default if not specified") {
let image = Image.fromJSON([
"id": "",
"image_url":"http://image.com/:version.jpg",
"image_versions" : ["small"],
"original_width": size.width,
"original_height": size.height
])
expect(image.isDefault) == false
}
}
func imageForVersion(version:String) -> Image {
return Image.fromJSON([
"id": "",
"image_url":"http://image.com/:version.jpg",
"image_versions" : [version],
"original_width": size.width,
"original_height": size.height
])
}
}
| mit | c70672da6eea456188766d223975b7ee | 31.3 | 166 | 0.550641 | 4.339731 | false | false | false | false |
lokinfey/MyPerfectframework | PerfectServer/PerfectServerHTTPApp/ViewController.swift | 2 | 5532 | //
// ViewController.swift
// PerfectServerHTTPApp
//
// Created by Kyle Jessup on 2015-10-25.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet var startStopButton: NSButton?
@IBOutlet var urlButton: NSButton?
@IBOutlet var chooseButton: NSButton?
@IBOutlet var portTextField: NSTextField?
@IBOutlet var addressTextField: NSTextField?
@IBOutlet var documentRootTextField: NSTextField?
@IBOutlet var startStopButtonBackground: NSView?
@IBOutlet var urlButtonBackground: NSView?
@IBOutlet var chooseButtonBackground: NSView?
var savedFont: NSFont?
var serverUrl: String {
let appDel = AppDelegate.sharedInstance
let url = "http://\(appDel.serverAddress):\(appDel.serverPort)/"
return url
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
self.startStopButtonBackground?.layer?.backgroundColor = NSColor(red:0.93, green:0.32, blue:0.2, alpha:1).CGColor
self.urlButtonBackground?.layer?.backgroundColor = NSColor(red:0.22, green:0.22, blue:0.22, alpha:1).CGColor
self.startStopButtonBackground?.layer?.cornerRadius = 3
self.urlButtonBackground?.layer?.cornerRadius = 3
self.savedFont = self.startStopButton?.cell?.font
self.setBlackTextButton(self.startStopButton!, title: self.startStopButton!.title)
self.setBlackTextButton(self.urlButton!, title: self.urlButton!.title)
self.setBlackTextButton(self.chooseButton!, title: self.chooseButton!.title)
}
func setBlackTextButton(button: NSButton, title: String) {
let attrTitle = NSMutableAttributedString(string: title, attributes: [NSForegroundColorAttributeName: NSColor.blackColor(), NSFontAttributeName: self.savedFont!])
button.attributedTitle = attrTitle
}
func setWhiteTextButton(button: NSButton, title: String) {
let attrTitle = NSMutableAttributedString(string: title, attributes: [NSForegroundColorAttributeName: NSColor.whiteColor(), NSFontAttributeName: self.savedFont!])
button.attributedTitle = attrTitle
}
override func viewWillAppear() {
super.viewWillAppear()
self.portTextField?.stringValue = String(AppDelegate.sharedInstance.serverPort)
self.addressTextField?.stringValue = String(AppDelegate.sharedInstance.serverAddress)
self.documentRootTextField?.stringValue = String(AppDelegate.sharedInstance.documentRoot)
}
override func viewDidAppear() {
super.viewDidAppear()
self.updateButtonTitle()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction
func toggleServer(sender: AnyObject) {
let appDel = AppDelegate.sharedInstance
if appDel.serverIsRunning() {
appDel.stopServer()
} else {
do {
try appDel.startServer()
} catch { }
}
self.updateButtonTitle()
}
@IBAction
func chooseDocumentRoot(sender: NSButton) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = true
panel.canChooseFiles = false
if panel.runModal() == NSFileHandlingPanelOKButton {
if let path = panel.URL, pathPath = path.path {
self.documentRootTextField!.stringValue = pathPath
}
}
}
func updateButtonTitle() {
dispatch_async(dispatch_get_main_queue()) {
let appDel = AppDelegate.sharedInstance
if appDel.serverIsRunning() {
self.setWhiteTextButton(self.startStopButton!, title: "Stop Server")
self.startStopButtonBackground?.layer?.backgroundColor = NSColor(red:0.93, green:0.32, blue:0.2, alpha:1).CGColor
} else {
self.setWhiteTextButton(self.startStopButton!, title: "Start Server")
self.startStopButtonBackground?.layer?.backgroundColor = NSColor(red:0.12, green:0.81, blue:0.43, alpha:1).CGColor
}
self.setWhiteTextButton(self.urlButton!, title: self.serverUrl)
}
}
private func rebootServer() {
let appDel = AppDelegate.sharedInstance
let time_a = dispatch_time(0, Int64(NSEC_PER_SEC) * Int64(1))
self.updateButtonTitle()
dispatch_after(time_a, dispatch_get_main_queue()) { [weak self] in
do {
try appDel.startServer()
} catch { }
dispatch_after(dispatch_time(0, Int64(NSEC_PER_SEC) * Int64(2)), dispatch_get_main_queue()) {
self?.updateButtonTitle()
}
}
}
func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
let appDel = AppDelegate.sharedInstance
let wasRunning = appDel.serverIsRunning()
if wasRunning {
appDel.stopServer()
}
if control == self.portTextField! {
appDel.serverPort = UInt16(control.stringValue) ?? 8181
} else if control == self.addressTextField! {
appDel.serverAddress = control.stringValue
} else if control == self.documentRootTextField! {
appDel.documentRoot = control.stringValue
}
self.setBlackTextButton(self.urlButton!, title: self.serverUrl)
if wasRunning {
self.rebootServer()
}
return true
}
@IBAction
func openUrl(sender: NSButton) {
let url = self.serverUrl
NSWorkspace.sharedWorkspace().openURL(NSURL(string: url)!)
}
}
| apache-2.0 | 069a7fd7fc7430b8a21cf34f666a11f6 | 30.793103 | 170 | 0.711135 | 4.046818 | false | false | false | false |
mballeza/Syllabus-Prep | Syllabus Prep/Syllabus Prep/Types.swift | 1 | 1027 | //
// Types.swift
// Syllabus Prep
//
// Created by Matthew Balleza on 8/4/17.
// Copyright © 2017 Matthew Balleza. All rights reserved.
// This software is released under the "Apache 2.0 License".
// Please see the file LICENSE in the source distribution of
// this software for license terms.
import Foundation
// This tuple is intended for Ear Training purposes. This tuple will contain
// a name and a set of half-step values. Int8 is used because MIDI tools
// require an Int8 value.
typealias setTuple = (name: String, value: [Int8])
// This is used mainly for random number access and switch cases. If a user
// wishes to study more than one Ear Training type, RandNum is used to pick
// an Ear Training type.
struct EAR_TRAINING_TYPE_VALUES {
let interval = 0
let chord = 1
let scale = 2
}
struct EAR_TRAINING_TYPE_NAMES {
let interval = "Interval"
let chord = "Chord"
let scale = "Scale"
}
let ETT_NAMES = EAR_TRAINING_TYPE_NAMES()
let ETT_VALUES = EAR_TRAINING_TYPE_VALUES()
| apache-2.0 | 41250e46825095a3a047deaddaa15e5e | 29.176471 | 76 | 0.706628 | 3.466216 | false | false | false | false |
nfjinjing/ShadowVPN-iOS | tunnel/NSData+Hex.swift | 54 | 755 | //
// NSData+Hex.swift
// ShadowVPN
//
// Created by clowwindy on 8/9/15.
// Copyright © 2015 clowwindy. All rights reserved.
//
import Foundation
extension NSData {
public class func fromHexString (string: String) -> NSData {
let data = NSMutableData()
var temp = ""
for char in string.characters {
temp += String(char)
if temp.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 2 {
let scanner = NSScanner(string: temp)
var value: CUnsignedInt = 0
scanner.scanHexInt(&value)
data.appendBytes(&value, length: 1)
temp = ""
}
}
return data as NSData
}
} | gpl-3.0 | 61bf141dbebaa38895f56e04f142cd3e | 24.166667 | 75 | 0.534483 | 4.68323 | false | false | false | false |
tryswift/TryParsec | excludedTests/TryParsec/Specs/HelperSpec.swift | 1 | 1832 | @testable import TryParsec
import Result
import Quick
import Nimble
class HelperSpec: QuickSpec
{
override func spec()
{
describe("splitAt") {
it("splitAt(1)") {
let (heads, tails) = splitAt(1)("abc" as USV)
expect(String(heads).unicodeScalars) == ["a"]
expect(String(tails).unicodeScalars) == ["b", "c"]
}
it("splitAt(0)") {
let (heads, tails) = splitAt(0)("abc" as USV)
expect(String(heads).unicodeScalars) == []
expect(String(tails).unicodeScalars) == ["a", "b", "c"]
}
it("splitAt(999)") {
let (heads, tails) = splitAt(999)("abc" as USV)
expect(String(heads).unicodeScalars) == ["a", "b", "c"]
expect(String(tails).unicodeScalars) == []
}
it("splitAt(0)(\"\")") {
let (heads, tails) = splitAt(0)("" as USV)
expect(String(heads).unicodeScalars) == []
expect(String(tails).unicodeScalars) == []
}
}
describe("trim") {
it("trims head & tail whitespaces") {
let trimmed = trim(" Trim me! ")
expect(trimmed) == "Trim me!"
}
it("doesn't trim middle whitespaces") {
let trimmed = trim("Dooooon't trrrrrim meeeee!")
expect(trimmed) == "Dooooon't trrrrrim meeeee!"
}
}
describe("RangeReplaceableCollectionType (RRC)") {
it("any RRC e.g. `ArraySlice` can initialize with SequenceType") {
let arr = ArraySlice<UnicodeScalar>("abc" as USV)
expect(Array(arr)) == Array(["a", "b", "c"])
}
}
}
}
| mit | 6dfd4bdefe907c11ad32e3e37552f1e7 | 29.032787 | 78 | 0.465611 | 4.320755 | false | false | false | false |
xedin/swift | test/IDE/print_ast_tc_decls.swift | 1 | 55074 | // RUN: %empty-directory(%t)
//
// Build swift modules this test depends on.
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
// FIXME: END -enable-source-import hackaround
//
// This file should not have any syntax or type checker errors.
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -typecheck -verify %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt
// FIXME: rdar://15167697
// FIXME: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// FIXME: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// REQUIRES: objc_interop
import Bar
import ObjectiveC
import class Foo.FooClassBase
import struct Foo.FooStruct1
import func Foo.fooFunc1
@_exported import FooHelper
import foo_swift_module
// FIXME: enum tests
//import enum FooClangModule.FooEnum1
// PASS_COMMON: {{^}}import Bar{{$}}
// PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}}
// PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}}
// PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}}
// PASS_COMMON: {{^}}@_exported import FooHelper{{$}}
// PASS_COMMON: {{^}}import foo_swift_module{{$}}
//===---
//===--- Helper types.
//===---
struct FooStruct {}
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
protocol SubFooProtocol : FooProtocol { }
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Basic smoketest.
//===---
struct d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}}
var instanceVar1: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
var computedProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}}
func instanceFunc0() {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}}
func instanceFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}}
func instanceFunc2(a: Int, b: inout Double) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}}
func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a }
// PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}}
func instanceFuncWithDefaultArg1(a: Int = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = 0){{$}}
func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0){{$}}
func varargInstanceFunc0(v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}}
func varargInstanceFunc1(a: Float, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}}
func varargInstanceFunc2(a: Float, b: Double, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}}
func overloadedInstanceFunc1() -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}}
func overloadedInstanceFunc1() -> Double { return 0.0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}}
func overloadedInstanceFunc2(x: Int) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}}
func overloadedInstanceFunc2(x: Double) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}}
func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); }
// PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}}
subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}}
static subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} static subscript(i: Int) -> Double { get }{{$}}
func bodyNameVoidFunc1(a: Int, b x: Float) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}}
func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}}
func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}}
func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}}
struct NestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class NestedClass {}
// PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum NestedEnum {}
// PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}}
static var staticVar1: Int = 42
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var staticVar1: Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}}
static func staticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}}
static func staticFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}}
static func overloadedStaticFunc1() -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}}
static func overloadedStaticFunc1() -> Double { return 0.0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}}
static func overloadedStaticFunc2(x: Int) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}}
static func overloadedStaticFunc2(x: Double) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}}
}
// PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int = 0){{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}}
var extProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}}
func extFunc0() {}
// PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}}
static var extStaticProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}}
static func extStaticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}}
struct ExtNestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class ExtNestedClass {}
// PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
// PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias ExtNestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct.NestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}}
struct ExtNestedStruct2 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
extension d0100_FooStruct.ExtNestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}}
struct ExtNestedStruct3 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
var fooObject: d0100_FooStruct = d0100_FooStruct()
// PASS_ONE_LINE-DAG: {{^}}@_hasInitialValue var fooObject: d0100_FooStruct{{$}}
struct d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
var computedProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}}
subscript(i: Int) -> Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}}
var computedProp2: Int {
mutating get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
var computedProp3: Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
var computedProp4: Int {
mutating get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
subscript(i: Float) -> Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
extension d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
var extProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
class d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}}
required init() {}
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
// FIXME: Add these once we can SILGen them reasonable.
// init?(fail: String) { }
// init!(iuoFail: String) { }
final func baseFunc1() {}
// PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}}
func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}}
subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}}
class var baseClassVar1: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}}
// FIXME: final class var not allowed to have storage, but static is?
// final class var baseClassVar2: Int = 0
final class var baseClassVar3: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}}
static var baseClassVar4: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var baseClassVar4: Int{{$}}
static var baseClassVar5: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}}
class func baseClassFunc1() {}
// PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}}
final class func baseClassFunc2() {}
// PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}}
static func baseClassFunc3() {}
// PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}}
}
class d0121_TestClassDerived : d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}}
required init() { super.init() }
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
final override func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}}
override final subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}}
}
protocol d0130_TestProtocol {
// PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}}
associatedtype NestedTypealias
// PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}}
var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}}
var property2: Int { get set }
// PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}}
func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}}
}
@objc protocol d0140_TestObjCProtocol {
// PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}}
@objc optional var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}}
@objc optional func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}}
}
protocol d0150_TestClassProtocol : class {}
// PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : AnyObject {{{$}}
@objc protocol d0151_TestClassProtocol {}
// PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}}
class d0170_TestAvailability {
// PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}}
@available(*, unavailable)
func f1() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f1(){{$}}
@available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee")
func f2() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}}
// PASS_COMMON-NEXT: {{^}} func f2(){{$}}
@available(iOS, unavailable)
@available(OSX, unavailable)
func f3() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f3(){{$}}
@available(iOS 8.0, OSX 10.10, *)
func f4() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f4(){{$}}
// Convert long-form @available() to short form when possible.
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
func f5() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f5(){{$}}
}
@objc class d0180_TestIBAttrs {
// PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}}
@IBAction func anAction(_: AnyObject) {}
// PASS_COMMON-NEXT: {{^}} @objc @IBAction func anAction(_: AnyObject){{$}}
@IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any? { fatalError() }
// PASS_COMMON-NEXT: {{^}} @objc @IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any?{{$}}
@IBDesignable
class ADesignableClass {}
// PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}}
}
@objc class d0181_TestIBAttrs {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}}
@IBOutlet weak var anOutlet: d0181_TestIBAttrs!
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBOutlet @_implicitly_unwrapped_optional @_hasInitialValue weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}}
@IBInspectable var inspectableProp: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBInspectable @_hasInitialValue var inspectableProp: Int{{$}}
@GKInspectable var inspectableProp2: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @GKInspectable @_hasInitialValue var inspectableProp2: Int{{$}}
}
struct d0190_LetVarDecls {
// PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
// PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
let instanceVar1: Int = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
let instanceVar2 = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
static let staticVar1: Int = 42
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
static let staticVar2 = 42
// FIXME: PRINTED_WITHOUT_TYPE
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
}
struct d0200_EscapedIdentifiers {
// PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}}
struct `struct` {}
// PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum `enum` {
case `case`
}
// PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}}
// PASS_COMMON-NEXT: {{^}} case `case`{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d0200_EscapedIdentifiers.`enum`, _ b: d0200_EscapedIdentifiers.`enum`) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}} }{{$}}
class `class` {}
// PASS_COMMON-NEXT: {{^}} class `class` {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias `protocol` = `class`
// PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}}
class `extension` : `class` {}
// PASS_ONE_LINE_TYPE-DAG: {{^}} class `extension` : d0200_EscapedIdentifiers.`class` {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} class `extension` : `class` {{{$}}
// PASS_COMMON: {{^}} {{(override )?}}init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
func `func`<`let`: `protocol`, `where`>(
class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {}
// PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`protocol`, `where` : {{(d0200_EscapedIdentifiers.)?}}`protocol`{{$}}
var `var`: `struct` = `struct`()
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}}
var tupleType: (`var`: Int, `let`: `struct`)
// PASS_COMMON-NEXT: {{^}} var tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}}
var accessors1: Int {
get { return 0 }
set(`let`) {}
}
// PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}}
static func `static`(protocol: Int) {}
// PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}}
// PASS_COMMON-NEXT: {{^}} init(var: {{(d0200_EscapedIdentifiers.)?}}`struct` = {{(d0200_EscapedIdentifiers.)?}}`struct`(), tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
}
struct d0210_Qualifications {
// PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}}
// PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}}
var propFromStdlib1: Int = 0
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
var propFromSwift1: FooSwiftStruct = FooSwiftStruct()
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromSwift1: FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}}
var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0)
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
func instanceFuncFromStdlib1(a: Int) -> Float {
return 0.0
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
func instanceFuncFromStdlib2(a: ObjCBool) {}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct {
return FooSwiftStruct()
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}}
func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 {
return FooStruct1(x: 0, y: 0.0)
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
}
// FIXME: this should be printed reasonably in case we use
// -prefer-type-repr=true. Either we should print the types we inferred, or we
// should print the initializers.
class d0250_ExplodePattern {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}}
var instanceVar1 = 0
var instanceVar2 = 0.0
var instanceVar3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar3: String{{$}}
var instanceVar4 = FooStruct()
var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct())
var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct())
var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar10: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar11: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar12: FooStruct{{$}}
let instanceLet1 = 0
let instanceLet2 = 0.0
let instanceLet3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet3: String{{$}}
let instanceLet4 = FooStruct()
let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct())
let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct())
let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet10: FooStruct{{$}}
}
class d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}}
init() {
baseProp1 = 0
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}}
final var baseProp1: Int
// PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}}
var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}}
}
class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}}
override final var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}}
}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}}
struct StructWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}}
struct StructWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}}
struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}}
class ClassWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}}
class ClassWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance3 : FooClass {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance3 : FooClass {{{$}}
class ClassWithInheritance4 : FooClass, FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance4 : FooClass, FooProtocol {{{$}}
class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}}
enum EnumWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}}
enum EnumWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}}
enum EnumDeclWithUnderlyingType1 : Int { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}}
enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}}
enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}}
protocol ProtocolWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { }
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : BarProtocol, FooProtocol {{{$}}
protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {
}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in extensions
//===---
struct StructInherited { }
// PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}}
extension StructInherited : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias SimpleTypealias1 = FooProtocol
// PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}}
// Associated types.
protocol AssociatedType1 {
associatedtype AssociatedTypeDecl1 = Int
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}}
associatedtype AssociatedTypeDecl2 : FooProtocol
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}}
associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : BarProtocol, FooProtocol{{$}}
associatedtype AssociatedTypeDecl4 where AssociatedTypeDecl4 : QuxProtocol, AssociatedTypeDecl4.Qux == Int
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl4 : QuxProtocol where Self.AssociatedTypeDecl4.Qux == Int{{$}}
associatedtype AssociatedTypeDecl5: FooClass
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl5 : FooClass{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var d0300_topLevelVar1: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0300_topLevelVar1: Int{{$}}
// PASS_COMMON-NOT: d0300_topLevelVar1
var d0400_topLevelVar2: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0400_topLevelVar2: Int{{$}}
// PASS_COMMON-NOT: d0400_topLevelVar2
var d0500_topLevelVar2: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}}
// PASS_COMMON-NOT: d0500_topLevelVar2
class d0600_InClassVar1 {
// PASS_O600-LABEL: d0600_InClassVar1
var instanceVar1: Int
// PASS_COMMON: {{^}} var instanceVar1: Int{{$}}
// PASS_COMMON-NOT: instanceVar1
var instanceVar2: Int = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar2: Int{{$}}
// PASS_COMMON-NOT: instanceVar2
// FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN.
// FIXME: PRINTED_WITHOUT_TYPE
var instanceVar3 = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar3
// PASS_COMMON-NOT: instanceVar3
var instanceVar4: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}}
// PASS_COMMON-NOT: instanceVar4
// FIXME: uncomment when we have static vars.
// static var staticVar1: Int
init() {
instanceVar1 = 10
}
}
//===---
//===--- Subscript declaration printing.
//===---
class d0700_InClassSubscript1 {
// PASS_COMMON-LABEL: d0700_InClassSubscript1
subscript(i: Int) -> Int {
get {
return 42
}
}
subscript(index i: Float) -> Int { return 42 }
class `class` {}
subscript(x: Float) -> `class` { return `class`() }
// PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}}
// PASS_COMMON-NOT: subscript
// PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}}
// PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}}
}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Constructor declaration printing.
//===---
struct d0800_ExplicitConstructors1 {
// PASS_COMMON-LABEL: d0800_ExplicitConstructors1
init() {}
// PASS_COMMON: {{^}} init(){{$}}
init(a: Int) {}
// PASS_COMMON: {{^}} init(a: Int){{$}}
}
struct d0900_ExplicitConstructorsSelector1 {
// PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1
init(int a: Int) {}
// PASS_COMMON: {{^}} init(int a: Int){{$}}
init(int a: Int, andFloat b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}}
}
struct d1000_ExplicitConstructorsSelector2 {
// PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2
init(noArgs _: ()) {}
// PASS_COMMON: {{^}} init(noArgs _: ()){{$}}
init(_ a: Int) {}
// PASS_COMMON: {{^}} init(_ a: Int){{$}}
init(_ a: Int, withFloat b: Float) {}
// PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}}
init(int a: Int, _ b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}}
}
//===---
//===--- Destructor declaration printing.
//===---
class d1100_ExplicitDestructor1 {
// PASS_COMMON-LABEL: d1100_ExplicitDestructor1
deinit {}
// PASS_COMMON: {{^}} @objc deinit{{$}}
}
//===---
//===--- Enum declaration printing.
//===---
enum d2000_EnumDecl1 {
case ED1_First
case ED1_Second
}
// PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_First{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d2000_EnumDecl1, _ b: d2000_EnumDecl1) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2100_EnumDecl2 {
case ED2_A(Int)
case ED2_B(Float)
case ED2_C(Int, Float)
case ED2_D(x: Int, y: Float)
case ED2_E(x: Int, y: (Float, Double))
case ED2_F(x: Int, (y: Float, z: Double))
}
// PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2200_EnumDecl3 {
case ED3_A, ED3_B
case ED3_C(Int), ED3_D
case ED3_E, ED3_F(Int)
case ED3_G(Int), ED3_H(Int)
case ED3_I(Int), ED3_J(Int), ED3_K
}
// PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}}
// PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}}
// PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}}
// PASS_2200-NEXT: {{^}}}{{$}}
// PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}}
enum d2300_EnumDeclWithValues1 : Int {
case EDV2_First = 10
case EDV2_Second
}
// PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Int
// PASS_COMMON-DAG: {{^}} init?(rawValue: Int){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Int { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
enum d2400_EnumDeclWithValues2 : Double {
case EDV3_First = 10
case EDV3_Second
}
// PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Double
// PASS_COMMON-DAG: {{^}} init?(rawValue: Double){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Double { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Custom operator printing.
//===---
postfix operator <*>
// PASS_2500-LABEL: {{^}}postfix operator <*>{{$}}
protocol d2600_ProtocolWithOperator1 {
static postfix func <*>(_: Self)
}
// PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}}
// PASS_2500-NEXT: {{^}} postfix static func <*> (_: Self){{$}}
// PASS_2500-NEXT: {{^}}}{{$}}
struct d2601_TestAssignment {}
infix operator %%%
func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int {
return 0
}
// PASS_2500-LABEL: {{^}}infix operator %%% : DefaultPrecedence{{$}}
// PASS_2500: {{^}}func %%% (lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}}
precedencegroup BoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}}
associativity: left
// PASS_2500-NEXT: {{^}} associativity: left{{$}}
higherThan: AssignmentPrecedence
// PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: assignment
// PASS_2500-NOT: lowerThan
}
precedencegroup ReallyBoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}}
associativity: right
// PASS_2500-NEXT: {{^}} associativity: right{{$}}
// PASS_2500-NOT: higherThan
// PASS_2500-NOT: lowerThan
// PASS_2500-NOT: assignment
}
precedencegroup BoringAssignmentPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}}
lowerThan: AssignmentPrecedence
assignment: true
// PASS_2500-NEXT: {{^}} assignment: true{{$}}
// PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: associativity
// PASS_2500-NOT: higherThan
}
// PASS_2500: {{^}}}{{$}}
//===---
//===--- Printing of deduced associated types.
//===---
protocol d2700_ProtocolWithAssociatedType1 {
associatedtype TA1
func returnsTA1() -> TA1
}
// PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}}
// PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}}}{{$}}
struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {
func returnsTA1() -> Int {
return 42
}
}
// PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}}
// PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} typealias TA1 = Int
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Generic parameter list printing.
//===---
struct GenericParams1<
StructGenericFoo : FooProtocol,
StructGenericFooX : FooClass,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
// PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
init<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func genericParams1<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
}
struct GenericParams2<T : FooProtocol> where T : BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}}
struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}}
struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
struct GenericParams7<T : QuxProtocol, U : QuxProtocol> where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
//===---
//===--- Tupe sugar for library types.
//===---
struct d2900_TypeSugar1 {
// PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
func f1(x: [Int]) {}
// PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}}
func f2(x: Array<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}}
func f3(x: Int?) {}
// PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}}
func f4(x: Optional<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}}
func f5(x: [Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}}
func f6(x: Array<Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}}
func f7(x: [Int : Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
func f8(x: Dictionary<String, Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}}
}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
// @discardableResult attribute
public struct DiscardableThingy {
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public init()
@discardableResult
public init() {}
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public func useless() -> Int
@discardableResult
public func useless() -> Int { return 0 }
}
// Parameter Attributes.
// <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place
// PASS_PRINT_AST: public func ParamAttrs1(a: @autoclosure () -> ())
public func ParamAttrs1(a : @autoclosure () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ())
public func ParamAttrs2(a : @autoclosure @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs3(a: () -> ())
public func ParamAttrs3(a : () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ())
public func ParamAttrs4(a : @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs5(a: (@escaping () -> ()) -> ())
public func ParamAttrs5(a : (@escaping () -> ()) -> ()) {
}
// PASS_PRINT_AST: public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
// PASS_PRINT_AST: public var ParamAttrs7: (@escaping () -> ()) -> ()
public var ParamAttrs7: (@escaping () -> ()) -> () = { f in f() }
// Setter
// PASS_PRINT_AST: class FooClassComputed {
class FooClassComputed {
// PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)?
var stored : (((Int) -> Int) -> Int)? = nil
// PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set }
var computed : ((Int) -> Int) -> Int {
get { return stored! }
set { stored = newValue }
}
// PASS_PRINT_AST: }
}
// Protocol extensions
protocol ProtocolToExtend {
associatedtype Assoc
}
extension ProtocolToExtend where Self.Assoc == Int {}
// PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int {
// Protocol with where clauses
protocol ProtocolWithWhereClause : QuxProtocol where Qux == Int {}
// PREFER_TYPE_REPR_PRINTING: protocol ProtocolWithWhereClause : QuxProtocol where Self.Qux == Int {
protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Qux == Int {
// PREFER_TYPE_REPR_PRINTING-DAG: protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Self.Qux == Int {
associatedtype A1 : QuxProtocol where A1 : FooProtocol, A1.Qux : QuxProtocol, Int == A1.Qux.Qux
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A1 : FooProtocol, QuxProtocol where Self.A1.Qux : QuxProtocol, Self.A1.Qux.Qux == Int{{$}}
// FIXME: this same type requirement with Self should be printed here
associatedtype A2 : QuxProtocol where A2.Qux == Self
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A2 : QuxProtocol where Self == Self.A2.Qux{{$}}
}
#if true
#elseif false
#else
#endif
// PASS_PRINT_AST: #if
// PASS_PRINT_AST: #elseif
// PASS_PRINT_AST: #else
// PASS_PRINT_AST: #endif
public struct MyPair<A, B> { var a: A, b: B }
public typealias MyPairI<B> = MyPair<Int, B>
// PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B>
public typealias MyPairAlias<T, U> = MyPair<T, U>
// PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
typealias MyPairAlias2<T: FooProtocol, U> = MyPair<T, U> where U: BarProtocol
// PASS_PRINT_AST: typealias MyPairAlias2<T, U> = MyPair<T, U> where T : FooProtocol, U : BarProtocol
| apache-2.0 | c29327aee0a91c73520f17521ef7aa86 | 38.650108 | 385 | 0.649562 | 3.693267 | false | false | false | false |
zSOLz/viper-base | ViperBase/ViperBase/Views/BaseViewControllers/ContainerViewController/ContainerViewControllerTransitionContext.swift | 1 | 2817 | //
// ContainerViewControllerTransitionContext.swift
// ViperBase
//
// Created by SOL on 14.05.17.
// Copyright © 2017 SOL. All rights reserved.
//
/**
Transition context that represents basic non-interactive logic
*/
open class ContainerViewControllerTransitionContext: NSObject, UIViewControllerContextTransitioning {
open var fromViewController: UIViewController?
open var toViewController: UIViewController?
open var containerView: UIView
public init(containerView: UIView, from: UIViewController? = nil, to: UIViewController? = nil) {
self.containerView = containerView
self.fromViewController = from
self.toViewController = to
}
open var isAnimated: Bool {
return true
}
open var isInteractive: Bool {
return false
}
open var transitionWasCancelled: Bool {
return false
}
open var presentationStyle: UIModalPresentationStyle {
return .custom
}
open func updateInteractiveTransition(_ percentComplete: CGFloat) {
// Does nothing. Interactive transition does not support in this version.
}
open func finishInteractiveTransition() {
// Does nothing. Interactive transition does not support in this version.
}
open func cancelInteractiveTransition() {
// Does nothing. Interactive transition does not support in this version.
}
@available(iOS 10.0, *)
open func pauseInteractiveTransition() {
// Does nothing. Interactive transition does not support in this version.
}
open func completeTransition(_ didComplete: Bool) {
// Does nothing.
}
public func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? {
switch key {
case UITransitionContextViewControllerKey.from:
return fromViewController
case UITransitionContextViewControllerKey.to:
return toViewController
default:
return nil
}
}
@available(iOS 8.0, *)
public func view(forKey key: UITransitionContextViewKey) -> UIView? {
switch key {
case UITransitionContextViewKey.from:
return fromViewController?.view
case UITransitionContextViewKey.to:
return toViewController?.view
default:
return nil
}
}
@available(iOS 8.0, *)
public var targetTransform: CGAffineTransform {
return .identity
}
public func initialFrame(for vc: UIViewController) -> CGRect {
return containerView.bounds
}
public func finalFrame(for vc: UIViewController) -> CGRect {
return containerView.bounds
}
}
| mit | c182d69f3080e58066ed7f4439b93577 | 27.444444 | 103 | 0.645241 | 5.966102 | false | false | false | false |
JV17/MyCal-iWatch | MyCal-Calculator/TransitionManager.swift | 1 | 3928 | //
// TransitionManager.swift
// MyCal-Calculator
//
// Created by Jorge Valbuena on 2015-04-19.
// Copyright (c) 2015 Jorge Valbuena. All rights reserved.
//
import UIKit
class TransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = true
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
// get the duration of the animation
// DON'T just type '0.5s' -- the reason why won't make sense until the next post
// but for now it's important to just follow this approach
let duration = self.transitionDuration(transitionContext)
// add the view to our view controller
container.addSubview(toView)
// perform the animation!
// for this example, just slid both fromView and toView to the left at the same time
// meaning fromView is pushed off the screen and toView slides into view
// we also use the block animation usingSpringWithDamping for a little bounce
let travelDistance: CGFloat = container.bounds.size.width
let travel: CGAffineTransform = CGAffineTransformMakeTranslation(self.presenting ? -travelDistance : travelDistance, 0)
let travel2: CGAffineTransform = CGAffineTransformMakeTranslation(self.presenting ? -travelDistance/5 : travelDistance/5, 0)
toView.transform = CGAffineTransformInvert(travel)
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [], animations: {
// slide fromView off either the left or right edge of the screen
// depending if we're presenting or dismissing this view
fromView.transform = travel2
fromView.alpha = 0.3
toView.transform = CGAffineTransformIdentity
toView.alpha = 1
}, completion: { finished in
fromView.transform = CGAffineTransformIdentity
fromView.alpha = 1
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
})
}
// return how many seconds the transiton animation will take
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1.0
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
// remmeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// these methods are the perfect place to set our `presenting` flag to either true or false - voila!
self.presenting = true
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
} | mit | 10e09bbba1961bee1a6f1e5ace75eb8b | 45.223529 | 217 | 0.694756 | 6.22504 | false | false | false | false |
QuarkX/Quark | Sources/Quark/HTTP/Message/Headers.swift | 1 | 1616 | public struct Headers {
public var headers: [CaseInsensitiveString: String]
public init(_ headers: [CaseInsensitiveString: String]) {
self.headers = headers
}
}
extension Headers : ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (CaseInsensitiveString, String)...) {
var headers: [CaseInsensitiveString: String] = [:]
for (key, value) in elements {
headers[key] = value
}
self.headers = headers
}
}
extension Headers : Sequence {
public func makeIterator() -> DictionaryIterator<CaseInsensitiveString, String> {
return headers.makeIterator()
}
public var count: Int {
return headers.count
}
public var isEmpty: Bool {
return headers.isEmpty
}
public subscript(field: CaseInsensitiveString) -> String? {
get {
return headers[field]
}
set(header) {
headers[field] = header
}
}
public subscript(field: CaseInsensitiveStringRepresentable) -> String? {
get {
return headers[field.caseInsensitiveString]
}
set(header) {
headers[field.caseInsensitiveString] = header
}
}
}
extension Headers : CustomStringConvertible {
public var description: String {
var string = ""
for (header, value) in headers {
string += "\(header): \(value)\n"
}
return string
}
}
extension Headers : Equatable {}
public func == (lhs: Headers, rhs: Headers) -> Bool {
return lhs.headers == rhs.headers
}
| mit | c10d8e4f6f4ef311f867a96bc0fa2178 | 21.760563 | 85 | 0.600866 | 4.86747 | false | false | false | false |
art-divin/mester-client-ios | Mester/UI/cells/TestCaseCell.swift | 1 | 4182 | //
// TestCaseCell.swift
// Mester
//
// Created by Ruslan Alikhamov on 23/01/15.
// Copyright (c) 2015 Ruslan Alikhamov. All rights reserved.
//
import UIKit
class TestCaseCell: UITableViewCell {
var callback: ((AnyObject) -> Void)?
weak var object: AnyObject?
var button: UIButton = UIButton()
var textLbl: UILabel = UILabel()
var statusLbl: UILabel = UILabel()
private var swiperView: SwiperView?
override func awakeFromNib() {
super.awakeFromNib()
swiperView = SwiperView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), leftInset: -95, rightInset: 0)
let separatorView = UIView()
separatorView.backgroundColor = ThemeDefault.colorForTint()
self.contentView.addSubview(separatorView)
self.contentView.addSubview(swiperView!)
separatorView.translatesAutoresizingMaskIntoConstraints = false
swiperView!.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[swiper]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "swiper" : swiperView! ]))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[swiper][sepView(==1)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "swiper" : swiperView!, "sepView" : separatorView ]))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[sepView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "sepView" : separatorView ]))
self.contentView.bringSubviewToFront(swiperView!)
textLbl.numberOfLines = 0;
textLbl.lineBreakMode = .ByWordWrapping
swiperView!.topmostView().addSubview(statusLbl)
swiperView!.topmostView().addSubview(textLbl)
statusLbl.translatesAutoresizingMaskIntoConstraints = false
textLbl.translatesAutoresizingMaskIntoConstraints = false
var constraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label][statusLbl]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "label" : textLbl, "statusLbl" : statusLbl ]) as [NSLayoutConstraint]
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "label" : textLbl ]) as [NSLayoutConstraint]
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[statusLbl]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "statusLbl" : statusLbl ]) as [NSLayoutConstraint]
swiperView!.topmostView().addConstraints(constraints)
button.setTitleColor(ThemeDefault.colorForButtonTitle(.Active), forState: .Normal)
button.setTitleColor(ThemeDefault.colorForButtonTitle(.Selected), forState: .Highlighted)
button.setTitleColor(ThemeDefault.colorForButtonTitle(.Inactive), forState: .Disabled)
button.backgroundColor = ThemeDefault.colorForButtonBg(.Success)
swiperView?.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
swiperView?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[button(>=100)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "button" : button ]))
swiperView?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "button" : button ]))
swiperView?.rightCallback = { [weak self] in
if let callback = self?.callback {
if let object: AnyObject = self?.object {
callback(object)
}
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
let frame = self.contentView.bounds
swiperView?.frame = CGRectMake(CGRectGetMinX(frame), CGRectGetMinY(frame), CGRectGetWidth(frame), CGRectGetHeight(frame) - 1)
}
func setButtonVisibility(visible: Bool) {
self.button.hidden = !visible
}
override func prepareForReuse() {
self.callback = nil
self.object = nil
self.button.setTitle("", forState: .Normal)
self.statusLbl.text = ""
self.textLbl.text = ""
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 3e8b7c35f0c5a17831003e7116db3a54 | 48.785714 | 252 | 0.762315 | 4.402105 | false | false | false | false |
sschiau/swift | test/DebugInfo/typealias.swift | 6 | 3845 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-DAG: ![[INTTYPE:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int", {{.*}})
public class DWARF {
// CHECK-DAG: ![[BASE:.*]] = !DICompositeType({{.*}}identifier: "$ss6UInt32VD"
// CHECK-DAG: ![[DIEOFFSET:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias5DWARFC9DIEOffsetaD",{{.*}} line: [[@LINE+1]], baseType: ![[BASE]])
typealias DIEOffset = UInt32
// CHECK-DAG: ![[VOID:.*]] = !DICompositeType({{.*}}identifier: "$sytD"
// CHECK-DAG: ![[PRIVATETYPE:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias5DWARFC11PrivateType{{.+}}aD",{{.*}} line: [[@LINE+1]], baseType: ![[VOID]])
fileprivate typealias PrivateType = ()
fileprivate static func usePrivateType() -> PrivateType { return () }
}
public struct Generic<T> {
public enum Inner {
case value
}
}
public typealias Specific = Generic<Int>
public typealias NotSpecific<T> = Generic<T>.Inner
public struct Outer : P {
public enum Inner {
case x
}
}
public protocol P {
typealias T = Outer
}
// CHECK-DAG: [[INNER_TYPE:![0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type{{.*}} identifier: "$s9typealias5OuterV5InnerOD"
public func main() {
// CHECK-DAG: !DILocalVariable(name: "a",{{.*}} type: ![[DIEOFFSET]]
var a : DWARF.DIEOffset = 123
markUsed(a)
// CHECK-DAG: !DILocalVariable(name: "b",{{.*}} type: ![[DIEOFFSET]]
var b = DWARF.DIEOffset(456) as DWARF.DIEOffset
markUsed(b)
// CHECK-DAG: !DILocalVariable(name: "c",{{.*}} type: ![[PRIVATETYPE]]
var c = DWARF.usePrivateType()
markUsed(c);
// CHECK-DAG: !DILocalVariable(name: "d", {{.*}} type: [[NONGENERIC_TYPE:![0-9]+]])
// CHECK-DAG: [[NONGENERIC_TYPE]] = !DICompositeType(tag: DW_TAG_structure_type{{.*}} identifier: "$s9typealias7GenericV5InnerOySi_GD"
var d: Specific.Inner = .value
markUsed(d)
// CHECK-DAG: !DILocalVariable(name: "e", {{.*}} type: [[INNER_TYPE]])
var e: Outer.T.Inner = .x
markUsed(e)
// CHECK-DAG: !DILocalVariable(name: "f", {{.*}} type: [[OUTER_T_TYPE:![0-9]+]])
// CHECK-DAG: [[OUTER_T_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias1PP1TayAA5OuterV_GD"
var f: Outer.T = Outer()
markUsed(f)
// CHECK-DAG: !DILocalVariable(name: "g", {{.*}} type: [[GENERIC_TYPE:![0-9]+]])
// CHECK-DAG: [[GENERIC_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias11NotSpecificaySiGD"
var g: NotSpecific<Int> = .value
markUsed(g)
// Make sure we're not using the abbreviation for this obsolete type that was replaced with a typealias in Swift 4
//
// CHECK-DAG: !DILocalVariable(name: "h", {{.*}} type: [[UNICODE_SCALAR_TYPE:![0-9]+]])
// CHECK-DAG: [[UNICODE_SCALAR_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$ss13UnicodeScalaraD"
var h: UnicodeScalar = "a"
markUsed(h)
}
public class Halter {}
public class Tack<T> {
public typealias A = Halter
public func f1(y: (Array<A>, Array<A>)) {
markUsed(y)
}
public func f2(y: ([A], Array<A>)) {
markUsed(y)
}
public func f3(y: (Array<A>, [A])) {
markUsed(y)
}
public func f4(y: ([A], [A])) {
markUsed(y)
}
}
public class GenericClass<T> {}
public typealias GenericAlias<T> = GenericClass<T>
public func usesGeneric(y: (GenericAlias<Int>, GenericClass<Int>, GenericAlias<Int>, GenericClass<Int>)) {
let x = y
markUsed(x)
}
public struct Ox<T> {}
extension Ox where T == Int {
public typealias Plow = Int
}
var v: Ox<Int>.Plow = 0
public protocol Up {
associatedtype A : Down
}
public protocol Down {
associatedtype A
}
public typealias DependentAlias<T : Up> = T.A.A
extension Up where A.A == Int {
public func foo() {
// CHECK-DAG: !DILocalVariable(name: "gg",{{.*}} type: ![[INTTYPE]]
var gg: DependentAlias<Self> = 123
}
}
| apache-2.0 | 16ca6cb544d183746f6e4b1d1d2cfcfa | 28.806202 | 169 | 0.638492 | 3.220268 | false | false | false | false |
mathiasnagler/SwiftyAcknowledgements | SwiftyAcknowledgements/Acknowledgement.swift | 1 | 1745 | //
// Acknowledgement.swift
// SwiftyAcknowledgements
//
// Created by Mathias Nagler on 08.09.15.
// Copyright © 2015 Mathias Nagler. All rights reserved.
//
import Foundation
public struct Acknowledgement: Equatable {
// MARK: Properties
public let title: String
public let text: String
// MARK: Initialization
/// Initializes a new Acknowledgement instance with the given title and text
public init(title: String, text: String) {
self.title = title
self.text = text
}
// MARK: Loading Acknowledgement from Plist
/**
Loads a plist at a given path and initializes an Acknowledgement instance for every
element of the plist. The plist's top level element has to be an array and every
element in the array should be a dictionary with the two keys **title** and **text**.
If the plist is not in the correct format an empty array will be returned.
- Returns: An array of Acknowledgements.
*/
public static func acknowledgements(fromPlistAt path: String) -> [Acknowledgement] {
var acknowledgements = [Acknowledgement]()
if let plist = NSArray(contentsOfFile: path) as? Array<Dictionary<String, String>> {
for dict in plist {
if let
title = dict["title"],
let text = dict["text"]
{
acknowledgements.append(Acknowledgement(title: title, text: text))
}
}
}
return acknowledgements
}
}
// MARK: - Equatable
public func ==(lhs: Acknowledgement, rhs: Acknowledgement) -> Bool {
return ((lhs.title == rhs.title) && (lhs.text == rhs.text))
}
| mit | b0bf3b0e629d2b6bead1f606c8a3a9d7 | 29.068966 | 92 | 0.612385 | 4.804408 | false | false | false | false |
grubFX/ICE | ICE/ViewController.swift | 1 | 5623 | //
// ViewController.swift
// ICE
//
// Created by Felix Gruber on 25.03.15.
// Copyright (c) 2015 Felix Gruber. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{
var numbers = [String]()
var persondata: PersonData?
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let personDataRequest = NSFetchRequest(entityName: "PersonData")
let numbersRequest = NSFetchRequest(entityName: "NumberString")
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bloodType: UILabel!
@IBOutlet weak var allergies: UILabel!
@IBOutlet weak var medHist: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self;
tableView.delegate = self;
imageView.layer.borderWidth=1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.grayColor().CGColor
imageView.layer.cornerRadius = 13
imageView.layer.cornerRadius = imageView.frame.size.height/2
imageView.clipsToBounds = true
loadPersonDataFromDB()
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
loadPersonDataFromDB()
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numbers.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
cell!.textLabel!.text = numbers[indexPath.row]
cell!.textLabel!.numberOfLines = 2
return cell!
}
func loadPersonDataFromDB(){
var error: NSError?
var recordCount = context!.countForFetchRequest(personDataRequest, error: &error)
var fetchedResults: [NSManagedObject]? = nil;
if(recordCount>0){
do{
fetchedResults = try context!.executeFetchRequest(personDataRequest) as? [NSManagedObject]
}catch _{}
if let results = fetchedResults {
persondata = results[0] as? PersonData
if persondata != nil{
name.text = "\(persondata!.firstName) \(persondata!.lastName)"
bloodType.text = persondata!.bloodType
allergies.text = persondata!.allergies
medHist.text = persondata!.medHist
if let temp = UIImage(data: persondata!.img as NSData){
imageView.image = temp
}
}
}
}
recordCount = context!.countForFetchRequest(numbersRequest, error: &error)
if(recordCount>0){
do{
fetchedResults = try context!.executeFetchRequest(numbersRequest) as? [NSManagedObject]
}catch _{}
if let results = fetchedResults {
numbers.removeAll(keepCapacity: false)
for result in results {
addNumber((result as! NumberString).number)
}
}
}else{
numbers = ["here will be the numbers you choose","they will show up on the homescreen in this order","swipe left to remove"]
}
}
func addNumber(number: String){
if !numbers.contains(number){
numbers.append(number)
}
}
@IBAction func unwindSegue(segue: UIStoryboardSegue){ /*kinda useless*/ }
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
numbers.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
override func viewWillDisappear(animated: Bool) {
var fetchedResults: [NSManagedObject]? = nil
do{
fetchedResults = try context!.executeFetchRequest(numbersRequest) as? [NSManagedObject]
}catch _{}
if let results = fetchedResults {
for result in results {
context!.deleteObject(result as NSManagedObject)
}
}
do {
try context!.save()
} catch _ {
}
for num in numbers {
(NSEntityDescription.insertNewObjectForEntityForName("NumberString", inManagedObjectContext: context!) as! NumberString).number=num
do {
try context!.save()
} catch _ {
}
}
// save to userdefaults
let defaults: NSUserDefaults = NSUserDefaults(suiteName: "group.at.fhooe.mc.MOM4.ICE")!
defaults.setObject(numbers, forKey: "numbers")
if persondata != nil{
defaults.setObject(persondata!.firstName + " " + persondata!.lastName, forKey: "name")
defaults.setObject(persondata!.bloodType, forKey: "bloodtype")
defaults.setObject(persondata!.medHist, forKey: "medhist")
defaults.setObject(persondata!.allergies, forKey: "allergies")
}
defaults.synchronize()
}
} | bsd-3-clause | c40a5ee23a35bf5054848e482c95fb93 | 36.245033 | 148 | 0.614619 | 5.464529 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | AztecTests/Renderers/CommentAttachmentRendererTests.swift | 2 | 1574 | import XCTest
@testable import Aztec
class CommentAttachmentRendererTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testShouldRender() {
let renderer = CommentAttachmentRenderer(font: .systemFont(ofSize: 12))
let goodAttachment = CommentAttachment()
let badAttachment = NSTextAttachment(data: nil, ofType: nil)
let textView = TextViewStub()
XCTAssertTrue(renderer.textView(textView, shouldRender: goodAttachment))
XCTAssertFalse(renderer.textView(textView, shouldRender: badAttachment))
}
func testBoundsForAttachment() {
let textView = TextView(
defaultFont: UIFont.systemFont(ofSize: 12),
defaultMissingImage: UIImage())
textView.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let attachment = CommentAttachment()
attachment.text = "Some comment!"
let renderer = CommentAttachmentRenderer(font: .systemFont(ofSize: 12))
let lineFragment = CGRect(x: 0, y: 0, width: 100, height: 50)
// These bounds were extracted from an initial successful run.
let expectedBounds = CGRect(
x: 14.0,
y: -3.0,
width: 72.0,
height: 15.0)
let bounds = renderer.textView(textView, boundsFor: attachment, with: lineFragment)
XCTAssertEqual(bounds, expectedBounds)
}
}
| mpl-2.0 | 2626e1f9ff43ed008025df39dbbd166a | 31.122449 | 91 | 0.610546 | 5.012739 | false | true | false | false |
practicalswift/swift | test/decl/subscript/noescape_accessors.swift | 34 | 3148 | // RUN: %target-typecheck-verify-swift
var global: () -> () = {}
struct Properties {
var property1: () -> () {
get {
return global
}
set {
global = newValue
}
}
var property2: () -> () {
get {
return global
}
set(value) {
global = value
}
}
}
func testProperties_property1(nonescaping: () -> (), // expected-note {{implicitly non-escaping}}
escaping: @escaping () -> ()) {
var p = Properties()
p.property1 = nonescaping // expected-error {{assigning non-escaping parameter}}
p.property1 = escaping
}
func testProperties_property2(nonescaping: () -> (), // expected-note {{implicitly non-escaping}}
escaping: @escaping () -> ()) {
var p = Properties()
p.property2 = nonescaping // expected-error {{assigning non-escaping parameter}}
p.property2 = escaping
}
struct Subscripts {
subscript(value1 fn: Int) -> () -> () {
get {
return global
}
set {
global = newValue
}
}
subscript(value2 fn: Int) -> () -> () {
get {
return global
}
set(value) {
global = value
}
}
subscript(nonescapingIndexWithAddressor fn: () -> Void) -> Int {
get {
return 0
}
unsafeMutableAddress {
fatalError()
}
}
// expected-note@+1 2 {{implicitly non-escaping}}
subscript(nonescapingIndex fn: () -> ()) -> Int {
get {
global = fn // expected-error {{assigning non-escaping parameter}}
return 0
}
set {
global = fn // expected-error {{assigning non-escaping parameter}}
}
}
subscript(escapingIndex fn: @escaping () -> ()) -> Int {
get {
global = fn
return 0
}
set {
global = fn
}
}
}
// expected-note@+1 {{implicitly non-escaping}}
func testSubscripts_value1(nonescaping: () -> (),
escaping: @escaping () -> ()) {
var s = Subscripts()
_ = s[value1: 0]
s[value1: 0] = escaping
s[value1: 0] = nonescaping // expected-error {{assigning non-escaping parameter}}
}
// expected-note@+1 {{implicitly non-escaping}}
func testSubscripts_value2(nonescaping: () -> (),
escaping: @escaping () -> ()) {
var s = Subscripts()
_ = s[value2: 0]
s[value2: 0] = escaping
s[value2: 0] = nonescaping // expected-error {{assigning non-escaping parameter}}
}
func testSubscripts_nonescapingIndex(nonescaping: () -> (),
escaping: @escaping () -> ()) {
var s = Subscripts()
_ = s[nonescapingIndex: nonescaping]
_ = s[nonescapingIndex: escaping]
s[nonescapingIndex: nonescaping] = 0
s[nonescapingIndex: escaping] = 0
}
// expected-note@+1 2 {{implicitly non-escaping}}
func testSubscripts_escapingIndex(nonescaping: () -> (),
escaping: @escaping () -> ()) {
var s = Subscripts()
_ = s[escapingIndex: nonescaping] // expected-error {{passing non-escaping parameter}}
_ = s[escapingIndex: escaping]
s[escapingIndex: nonescaping] = 0 // expected-error {{passing non-escaping parameter}}
s[escapingIndex: escaping] = 0
}
| apache-2.0 | 2f6ce9a7909064764e5f349d2621781b | 24.387097 | 97 | 0.569568 | 4.072445 | false | false | false | false |
InsectQY/HelloSVU_Swift | HelloSVU_Swift/Application/Api.swift | 1 | 2047 | //
// Api.swift
// HelloSVU_Swift
//
// Created by Insect on 2017/9/26.
// Copyright © 2017年 Insect. All rights reserved.
//
import Foundation
import Moya
let LoadingPlugin = NetworkActivityPlugin { (type, target) in
switch type {
case .began:
SVUHUD.show(.black)
case .ended:
SVUHUD.dismiss()
}
}
let timeoutClosure = { (endpoint: Endpoint, closure: MoyaProvider<Api>.RequestResultClosure) -> Void in
if var urlRequest = try? endpoint.urlRequest() {
urlRequest.timeoutInterval = 15
closure(.success(urlRequest))
} else {
closure(.failure(MoyaError.requestMapping(endpoint.url)))
}
}
let ApiProvider = MoyaProvider<Api>(requestClosure: timeoutClosure)
let ApiLoadingProvider = MoyaProvider<Api>(requestClosure: timeoutClosure, plugins: [LoadingPlugin])
enum Api {
case wallpaper
case wallpaperCategory(String, Int)
}
extension Api: TargetType {
var baseURL: URL {
switch self {
case .wallpaper:
return URL(string: "http://service.picasso.adesk.com/v1/lightwp/category")!
case .wallpaperCategory(_,_):
return URL(string: "http://service.picasso.adesk.com/v1/lightwp/category")!
}
}
var path: String {
switch self {
case let .wallpaperCategory(id, _):
return "\(id)/vertical"
default:
return ""
}
}
var method: Moya.Method {
switch self {
default:
return .get
}
}
var sampleData: Data {
return "".data(using: String.Encoding.utf8)!
}
var task: Task {
switch self {
case let .wallpaperCategory(_, skip):
return .requestParameters(parameters: ["limit": 15,
"skip": skip], encoding: URLEncoding.default)
default:
return .requestPlain
}
}
var headers: [String : String]? {
return nil
}
}
| apache-2.0 | ba325ddbf020a7e217309e0c8090b767 | 22.767442 | 103 | 0.572896 | 4.321353 | false | false | false | false |
huonw/swift | stdlib/public/core/Optional.swift | 1 | 28515 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that represents either a wrapped value or `nil`, the absence of a
/// value.
///
/// You use the `Optional` type whenever you use optional values, even if you
/// never type the word `Optional`. Swift's type system usually shows the
/// wrapped type's name with a trailing question mark (`?`) instead of showing
/// the full type name. For example, if a variable has the type `Int?`, that's
/// just another way of writing `Optional<Int>`. The shortened form is
/// preferred for ease of reading and writing code.
///
/// The types of `shortForm` and `longForm` in the following code sample are
/// the same:
///
/// let shortForm: Int? = Int("42")
/// let longForm: Optional<Int> = Int("42")
///
/// The `Optional` type is an enumeration with two cases. `Optional.none` is
/// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped
/// value. For example:
///
/// let number: Int? = Optional.some(42)
/// let noNumber: Int? = Optional.none
/// print(noNumber == nil)
/// // Prints "true"
///
/// You must unwrap the value of an `Optional` instance before you can use it
/// in many contexts. Because Swift provides several ways to safely unwrap
/// optional values, you can choose the one that helps you write clear,
/// concise code.
///
/// The following examples use this dictionary of image names and file paths:
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// Getting a dictionary's value using a key returns an optional value, so
/// `imagePaths["star"]` has type `Optional<String>` or, written in the
/// preferred manner, `String?`.
///
/// Optional Binding
/// ----------------
///
/// To conditionally bind the wrapped value of an `Optional` instance to a new
/// variable, use one of the optional binding control structures, including
/// `if let`, `guard let`, and `switch`.
///
/// if let starPath = imagePaths["star"] {
/// print("The star image is at '\(starPath)'")
/// } else {
/// print("Couldn't find the star image")
/// }
/// // Prints "The star image is at '/glyphs/star.png'"
///
/// Optional Chaining
/// -----------------
///
/// To safely access the properties and methods of a wrapped instance, use the
/// postfix optional chaining operator (postfix `?`). The following example uses
/// optional chaining to access the `hasSuffix(_:)` method on a `String?`
/// instance.
///
/// if imagePaths["star"]?.hasSuffix(".png") == true {
/// print("The star image is in PNG format")
/// }
/// // Prints "The star image is in PNG format"
///
/// Using the Nil-Coalescing Operator
/// ---------------------------------
///
/// Use the nil-coalescing operator (`??`) to supply a default value in case
/// the `Optional` instance is `nil`. Here a default path is supplied for an
/// image that is missing from `imagePaths`.
///
/// let defaultImagePath = "/images/default.png"
/// let heartPath = imagePaths["heart"] ?? defaultImagePath
/// print(heartPath)
/// // Prints "/images/default.png"
///
/// The `??` operator also works with another `Optional` instance on the
/// right-hand side. As a result, you can chain multiple `??` operators
/// together.
///
/// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
/// print(shapePath)
/// // Prints "/images/default.png"
///
/// Unconditional Unwrapping
/// ------------------------
///
/// When you're certain that an instance of `Optional` contains a value, you
/// can unconditionally unwrap the value by using the forced
/// unwrap operator (postfix `!`). For example, the result of the failable `Int`
/// initializer is unconditionally unwrapped in the example below.
///
/// let number = Int("42")!
/// print(number)
/// // Prints "42"
///
/// You can also perform unconditional optional chaining by using the postfix
/// `!` operator.
///
/// let isPNG = imagePaths["star"]!.hasSuffix(".png")
/// print(isPNG)
/// // Prints "true"
///
/// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime
/// error.
@_frozen
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
// The compiler has special knowledge of Optional<Wrapped>, including the fact
// that it is an `enum` with cases named `none` and `some`.
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public init(_ some: Wrapped) { self = .some(some) }
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that returns a nonoptional value.
/// This example performs an arithmetic operation on an
/// optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let possibleSquare = possibleNumber.map { $0 * $0 }
/// print(possibleSquare)
/// // Prints "Optional(1764)"
///
/// let noNumber: Int? = nil
/// let noSquare = noNumber.map { $0 * $0 }
/// print(noSquare)
/// // Prints "nil"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that returns an optional value.
/// This example performs an arithmetic operation with an optional result on
/// an optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
/// let (result, overflowed) = x.multipliedReportingOverflow(by: x)
/// return overflowed ? nil : result
/// }
/// print(nonOverflowingSquare)
/// // Prints "Optional(1764)"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
switch self {
case .some(let y):
return try transform(y)
case .none:
return .none
}
}
/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize an `Optional` instance with a `nil` literal. For example:
///
/// var i: Index? = nil
///
/// In this example, the assignment to the `i` variable calls this
/// initializer behind the scenes.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public init(nilLiteral: ()) {
self = .none
}
/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable
public var unsafelyUnwrapped: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_debugPreconditionFailure("unsafelyUnwrapped of nil optional")
}
}
/// - Returns: `unsafelyUnwrapped`.
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@inlinable
public // SPI(SwiftExperimental)
var _unsafelyUnwrappedUnchecked: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_sanityCheckFailure("_unsafelyUnwrappedUnchecked of nil optional")
}
}
}
extension Optional : CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
switch self {
case .some(let value):
var result = "Optional("
debugPrint(value, terminator: "", to: &result)
result += ")"
return result
case .none:
return "nil"
}
}
}
extension Optional : CustomReflectable {
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
switch self {
case .some(let value):
return Mirror(
self,
children: [ "some": value ],
displayStyle: .optional)
case .none:
return Mirror(self, children: [:], displayStyle: .optional)
}
}
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // COMPILER_INTRINSIC
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word) {
_preconditionFailure(
"Unexpectedly found nil while unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
}
extension Optional : Equatable where Wrapped : Equatable {
/// Returns a Boolean value indicating whether two optional instances are
/// equal.
///
/// Use this equal-to operator (`==`) to compare any two optional instances of
/// a type that conforms to the `Equatable` protocol. The comparison returns
/// `true` if both arguments are `nil` or if the two arguments wrap values
/// that are equal. Conversely, the comparison returns `false` if only one of
/// the arguments is `nil` or if the two arguments wrap values that are not
/// equal.
///
/// let group1 = [1, 2, 3, 4, 5]
/// let group2 = [1, 3, 5, 7, 9]
/// if group1.first == group2.first {
/// print("The two groups start the same.")
/// }
/// // Prints "The two groups start the same."
///
/// You can also use this operator to compare a non-optional value to an
/// optional that wraps the same type. The non-optional value is wrapped as an
/// optional before the comparison is made. In the following example, the
/// `numberToMatch` constant is wrapped as an optional before comparing to the
/// optional `numberFromString`:
///
/// let numberToFind: Int = 23
/// let numberFromString: Int? = Int("23") // Optional(23)
/// if numberToFind == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// An instance that is expressed as a literal can also be used with this
/// operator. In the next example, an integer literal is compared with the
/// optional integer `numberFromString`. The literal `23` is inferred as an
/// `Int` instance and then wrapped as an optional before the comparison is
/// performed.
///
/// if 23 == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@inlinable
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
/// Returns a Boolean value indicating whether two optional instances are not
/// equal.
///
/// Use this not-equal-to operator (`!=`) to compare any two optional instances
/// of a type that conforms to the `Equatable` protocol. The comparison
/// returns `true` if only one of the arguments is `nil` or if the two
/// arguments wrap values that are not equal. The comparison returns `false`
/// if both arguments are `nil` or if the two arguments wrap values that are
/// equal.
///
/// let group1 = [2, 4, 6, 8, 10]
/// let group2 = [1, 3, 5, 7, 9]
/// if group1.first != group2.first {
/// print("The two groups start differently.")
/// }
/// // Prints "The two groups start differently."
///
/// You can also use this operator to compare a non-optional value to an
/// optional that wraps the same type. The non-optional value is wrapped as an
/// optional before the comparison is made. In this example, the
/// `numberToMatch` constant is wrapped as an optional before comparing to the
/// optional `numberFromString`:
///
/// let numberToFind: Int = 23
/// let numberFromString: Int? = Int("not-a-number") // nil
/// if numberToFind != numberFromString {
/// print("No match.")
/// }
/// // Prints "No match."
///
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@inlinable
public static func !=(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
return !(lhs == rhs)
}
}
extension Optional: Hashable where Wrapped: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch self {
case .none:
hasher.combine(0 as UInt8)
case .some(let wrapped):
hasher.combine(1 as UInt8)
hasher.combine(wrapped)
}
}
}
// Enable pattern matching against the nil literal, even if the element type
// isn't equatable.
@_fixed_layout
public struct _OptionalNilComparisonType : ExpressibleByNilLiteral {
/// Create an instance initialized with `nil`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public init(nilLiteral: ()) {
}
}
extension Optional {
/// Returns a Boolean value indicating whether an argument matches `nil`.
///
/// You can use the pattern-matching operator (`~=`) to test whether an
/// optional instance is `nil` even when the wrapped value's type does not
/// conform to the `Equatable` protocol. The pattern-matching operator is used
/// internally in `case` statements for pattern matching.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type, and then uses a `switch`
/// statement to determine whether the stream is `nil` or has a configured
/// value. When evaluating the `nil` case of the `switch` statement, this
/// operator is called behind the scenes.
///
/// var stream: DataStream? = nil
/// switch stream {
/// case nil:
/// print("No data stream is configured.")
/// case let x?:
/// print("The data stream has \(x.availableBytes) bytes available.")
/// }
/// // Prints "No data stream is configured."
///
/// - Note: To test whether an instance is `nil` in an `if` statement, use the
/// equal-to operator (`==`) instead of the pattern-matching operator. The
/// pattern-matching operator is primarily intended to enable `case`
/// statement pattern matching.
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to match against `nil`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some(_):
return false
case .none:
return true
}
}
// Enable equality comparisons against the nil literal, even if the
// element type isn't equatable
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if stream == nil {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some(_):
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if stream != nil {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some(_):
return true
case .none:
return false
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if nil == stream {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some(_):
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if nil != stream {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some(_):
return true
case .none:
return false
}
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// it returns the right-hand side as a default. The result of this operation
/// will have the nonoptional type of the left-hand side's `Wrapped` type.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// func getDefault() -> Int {
/// print("Calculating default...")
/// return 42
/// }
///
/// let goodNumber = Int("100") ?? getDefault()
/// // goodNumber == 100
///
/// let notSoGoodNumber = Int("invalid-input") ?? getDefault()
/// // Prints "Calculating default..."
/// // notSoGoodNumber == 42
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeded in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so the `getDefault()` method is called to supply a default
/// value.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` is the same
/// type as the `Wrapped` type of `optional`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default `Optional` value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// returns the right-hand side as a default. The result of this operation
/// will be the same type as its arguments.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// let goodNumber = Int("100") ?? Int("42")
/// print(goodNumber)
/// // Prints "Optional(100)"
///
/// let notSoGoodNumber = Int("invalid-input") ?? Int("42")
/// print(notSoGoodNumber)
/// // Prints "Optional(42)"
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeds in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so `Int("42")` is called to supply a default value.
///
/// Because the result of this nil-coalescing operation is itself an optional
/// value, you can chain default values by using `??` multiple times. The
/// first optional value that isn't `nil` stops the chain and becomes the
/// result of the whole expression. The next example tries to find the correct
/// text for a greeting in two separate dictionaries before falling back to a
/// static default.
///
/// let greeting = userPrefs[greetingKey] ??
/// defaults[greetingKey] ?? "Greetings!"
///
/// If `userPrefs[greetingKey]` has a value, that value is assigned to
/// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and
/// if not that, `greeting` will be set to the non-optional default value,
/// `"Greetings!"`.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` and
/// `optional` have the same type.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
//===----------------------------------------------------------------------===//
// Bridging
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
extension Optional : _ObjectiveCBridgeable {
// The object that represents `none` for an Optional of this type.
@inlinable // FIXME(sil-serialize-all)
internal static var _nilSentinel : AnyObject {
@_silgen_name("_swift_Foundation_getOptionalNilSentinelObject")
get
}
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> AnyObject {
// Bridge a wrapped value by unwrapping.
if let value = self {
return _bridgeAnythingToObjectiveC(value)
}
// Bridge nil using a sentinel.
return type(of: self)._nilSentinel
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some`.
if source === _nilSentinel {
result = .some(.none)
return
}
// Otherwise, force-bridge the underlying value.
let unwrappedResult = source as! Wrapped
result = .some(.some(unwrappedResult))
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) -> Bool {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some` to indicate success of the bridging operation, with a nil
// result.
if source === _nilSentinel {
result = .some(.none)
return true
}
// Otherwise, try to bridge the underlying value.
if let unwrappedResult = source as? Wrapped {
result = .some(.some(unwrappedResult))
return true
} else {
result = .none
return false
}
}
@inlinable // FIXME(sil-serialize-all)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Optional<Wrapped> {
if let nonnullSource = source {
// Map the nil sentinel back to none.
if nonnullSource === _nilSentinel {
return .none
} else {
return .some(nonnullSource as! Wrapped)
}
} else {
// If we unexpectedly got nil, just map it to `none` too.
return .none
}
}
}
#endif
| apache-2.0 | 03d8d8bfca63d9d2b883cb5f6f85a23a | 34.913098 | 82 | 0.63023 | 4.253431 | false | false | false | false |
yomajkel/RingGraph | RingGraph/RingGraph/FadeOutLabel.swift | 1 | 2888 | //
// FadeOutLabel.swift
// RingMeter
//
// Created by Michał Kreft on 07/04/15.
// Copyright (c) 2015 Michał Kreft. All rights reserved.
//
import UIKit
class FadeOutLabel: UILabel {
private var originalText: String?
private var lastFadeCharacterIndex = 0
private var lastFadeCharacterAlpha: Float = 1.0
private var animationHelper: RangeAnimationHelper
override init(frame: CGRect) {
animationHelper = RangeAnimationHelper(animationStart: 0.3, animationEnd: 0.7)
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var text: String? {
didSet {
originalText = text
updateDisplayedText()
}
}
func setAnimationProgress(progress: Float) {
updateStateForProgress(progress)
updateDisplayedText()
}
}
private extension FadeOutLabel {
func updateStateForProgress(_ progress: Float) {
let normalizedProgress = animationHelper.normalizedProgress(progress)
switch normalizedProgress {
case 0.0:
lastFadeCharacterIndex = 0
lastFadeCharacterAlpha = 1.0
case 1.0:
lastFadeCharacterIndex = originalText != nil ? (originalText!).count - 1 : 0
lastFadeCharacterAlpha = 0.0
default:
let intProgress = Int(normalizedProgress * 100)
let lettersCount = (originalText != nil) ? (originalText!).count : 1
let letterSpan = 100 / lettersCount
lastFadeCharacterIndex = intProgress / letterSpan
lastFadeCharacterAlpha = 1 - Float(intProgress % letterSpan) / Float(letterSpan)
}
}
func updateDisplayedText() {
if let text = self.shiftedText() {
if (text.count == 0) {
super.text = text
} else {
let color = self.textColor.withAlphaComponent(CGFloat(lastFadeCharacterAlpha))
let range = NSRange(location: 0, length: 1)
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
self.attributedText = attributedString
}
} else {
super.text = nil
}
}
func shiftedText() -> String? {
var shiftedText: String?
if let originalText = originalText {
//let index = originalText.startIndex.advanced(lastFadeCharacterIndex)
let index = originalText.index(originalText.startIndex, offsetBy: lastFadeCharacterIndex)
shiftedText = String(originalText[index...])
}
return shiftedText
}
}
| mit | c59a94fdbd89e21c5c3a827269eab880 | 32.172414 | 113 | 0.604297 | 5.153571 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Libraries/SG-Engine/FireButton.swift | 1 | 1608 | //
// FireButton.swift
// MyProposalGame
//
// Created by Luis Cabarique on 9/18/16.
// Copyright © 2016 Luis Cabarique. All rights reserved.
//
import SpriteKit
import GameplayKit
class FireButton: SKNode {
var button = SKSpriteNode()
var touchArea: SKSpriteNode!
var firePressed = false
var zPos:CGFloat = 1000
init(buttonName: String) {
let atlas = SKTextureAtlas(named: "Button")
touchArea = SKSpriteNode()
touchArea.size = CGSize(width: 130, height: 130)
touchArea.color = SKColor.clearColor()
button = SKSpriteNode(texture: atlas.textureNamed("game"))
button.zPosition = zPos
button.alpha = 0.5
button.size = CGSize(width: 100, height: 100)
touchArea.addChild(button)
super.init()
self.name = buttonName
self.userInteractionEnabled = true
self.addChild(touchArea)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: handle interactions
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for _ in touches {
button.alpha = 1.0
firePressed = true
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
button.alpha = 0.5
firePressed = false
self.userInteractionEnabled = false
self.afterDelay(0.1) {
self.userInteractionEnabled = true
}
}
}
| mit | 4cac2329cf32c1fd7d08712c7660620b | 23.723077 | 82 | 0.59303 | 4.644509 | false | false | false | false |
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/Types/Rect.swift | 1 | 13110 | //
// Rect.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/12/23.
// Copyright © 2017年 史翔新. All rights reserved.
//
import UIKit
/// A struct that shows a rect with origin point and size.
///
/// Basically it behaves like a `CGRect` type that has the same properties `origin` and `size`, but since it's declared as another type just in NotAutoLayout, you can add any extensions you want and that won't affect the system's `CGRect` type. For example, I have defined properties like `topLeft` and `bottomRight`, as well as methods like `rect(inside: insets)`. You can safely use them with `Rect` type values, and they will not cause any confliction if you have defined the same functions for `CGRect`.
///
/// Conforms to: `CGTypeConvertible`.
public struct Rect {
/// The origin point of the rect.
public var origin: Point
/// The size of the rect.
public var size: Size
/// Initializes a `Rect` with origin (as `origin`) and size (as `size`).
public init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
/// Initializes a `Rect` with origin's x position (as `x`), origin's y position (as `y`), size's width (as `width`) and size's height (as `height`).
public init(x: Float, y: Float, width: Float, height: Float) {
self.origin = Point(x: x, y: y)
self.size = Size(width: width, height: height)
}
}
extension Rect {
/// A rect that both `origin` and `size` are `.zero`
public static let zero: Rect = .init(origin: .zero, size: .zero)
/// A rect that `origin` is `.zero` and `size` is `.identity`.
public static let identity: Rect = .init(origin: .zero, size: .identity)
}
extension Rect: CGTypeConvertible {
public var cgValue: CGRect {
return .init(origin: self.origin.cgValue, size: self.size.cgValue)
}
public init(_ rect: CGRect) {
self.origin = Point(rect.origin)
self.size = Size(rect.size)
}
}
extension Rect {
/// The left position in the rect, which is produced by `self.origin.x`
public var left: Float {
return self.origin.x
}
/// The center position in the rect, which is produced by `self.origin.x + (self.size.width * 0.5)`
public var center: Float {
return self.horizontalGeometry(at: 0.5)
}
/// The right position in the rect, which is produced by `self.origin.x + self.size.width`
public var right: Float {
return self.left + self.width
}
/// The origin's x position of the rect, which is produced by `self.origin.x`
public var x: Float {
return self.origin.x
}
/// The width of the rect, which is produced by `self.size.width`
public var width: Float {
return self.size.width
}
}
extension Rect {
/// The top position in the rect, which is produced by `self.origin.y`
public var top: Float {
return self.origin.y
}
/// The middle position in the rect, which is produced by `self.origin.y + (self.size.height * 0.5)`
public var middle: Float {
return self.verticalGeometry(at: 0.5)
}
/// The bottom position in the rect, which is produced by `self.origin.y + self.size.height`
public var bottom: Float {
return self.top + self.height
}
/// The origin's y position of the rect, which is produced by `self.origin.y`
public var y: Float {
return self.origin.y
}
/// The height of the rect, which is produced by `self.size.height`
public var height: Float {
return self.size.height
}
}
extension Rect {
/// The top left point in the rect, which is produced by `Point(x: self.left, y: self.top)`
public var topLeft: Point {
return .init(x: self.left, y: self.top)
}
/// The top center point in the rect, which is produced by `Point(x: self.center, y: self.top)`
public var topCenter: Point {
return .init(x: self.center, y: self.top)
}
/// The top right point in the rect, which is produced by `Point(x: self.right, y: self.top)`
public var topRight: Point {
return .init(x: self.right, y: self.top)
}
/// The middle left point in the rect, which is produced by `Point(x: self.left, y: self.middle)`
public var middleLeft: Point {
return .init(x: self.left, y: self.middle)
}
/// The middle center point in the rect, which is produced by `Point(x: self.center, y: self.middle)`
public var middleCenter: Point {
return .init(x: self.center, y: self.middle)
}
/// The middle right point in the rect, which is produced by `Point(x: self.right, y: self.middle)`
public var middleRight: Point {
return .init(x: self.right, y: self.middle)
}
/// The bottom left point in the rect, which is produced by `Point(x: self.left, y: self.bottom)`
public var bottomLeft: Point {
return .init(x: self.left, y: self.bottom)
}
/// The bottom center point in the rect, which is produced by `Point(x: self.center, y: self.bottom)`
public var bottomCenter: Point {
return .init(x: self.center, y: self.bottom)
}
/// The bottom right point in the rect, which is produced by `Point(x: self.right, y: self.bottom)`
public var bottomRight: Point {
return .init(x: self.right, y: self.bottom)
}
}
extension Rect {
/// The horizontal span in the rect, which is produced by `Span(start: self.origin.x, length: self.size.width)`
public var horizontalSpan: Span {
return Span(horizontalFrom: self)
}
/// The vertical span in the rect, which is produced by `Span(start: self.origin.y, length: self.size.height)`
public var verticalSpan: Span {
return Span(verticalFrom: self)
}
}
extension Rect {
/// The horizontal geometry position at the given coordinate position.
///
/// e.g.:
/// - Pass `0` to `coordinate` will get the left position of the rect.
/// - Pass `1` to `coordinate` will get the right position of the rect.
/// - Pass `0.75` to `coordinate` will get the horizontal position at 75% of the rect.
///
/// - Parameters:
/// - coordinate: The horizontal coordinate position in the rect.
///
/// - Returns: The horizontal geometry position at the given horizontal coordinate position in the rect.
public func horizontalGeometry(at coordinate: Float) -> Float {
return self.origin.x + (self.size.width * coordinate)
}
/// The vertical geometry position at the given coordinate position.
///
/// e.g.:
/// - Pass `0` to `coordinate` will get the top position of the rect.
/// - Pass `1` to `coordinate` will get the bottom position of the rect.
/// - Pass `0.75` to `coordinate` will get the vertical position at 75% of the rect.
///
/// - Parameters:
/// - coordinate: The vertical coordinate position in the rect.
///
/// - Returns: The vertical geometry position at the given vertical coordinate position in the rect.
public func verticalGeometry(at coordinate: Float) -> Float {
return self.origin.y + (self.size.height * coordinate)
}
/// The geometry point at the given coordinate position (produced from coordinateX and coordinateY).
///
/// e.g.:
/// - Pass `0` to `x` and `0` to `y` will get the top left point of the rect.
/// - Pass `0` to `x` and `1` to `y` will get the bottom left point of the rect.
/// - Pass `0.75` to `x` and `0.6` to `y` will get the point which horizontally at 75% and vertically at 60% of the rect.
///
/// - Parameters:
/// - coordinateX: The horizontal coordinate position in the rect.
/// - coordinateY: The vertical coordinate position in the rect.
///
/// - Returns: The geometry point at the given coordinate point in the rect.
public func pointGeometryAt(x coordinateX: Float, y coordinateY: Float) -> Point {
let x = self.horizontalGeometry(at: coordinateX)
let y = self.verticalGeometry(at: coordinateY)
return .init(x: x, y: y)
}
/// The geometry point at the given coordinate position.
///
/// e.g.:
/// - Pass `(x: 0, y: 0)` to `coordinate` will get the top left point of the rect.
/// - Pass `(x: 0, y: 1)` to `coordinate` will get the bottom left point of the rect.
/// - Pass `(x: 0.75, y: 0.6)` to `coordinate` will get the point which horizontally at 75% and vertically at 60% of the rect.
///
/// - Parameters:
/// - coordinate: The coordinate point in the rect.
///
/// - Returns: The geometry point at the given coordinate point in the rect.
public func pointGeometry(at coordinate: Point) -> Point {
return self.pointGeometryAt(x: coordinate.x, y: coordinate.y)
}
}
extension Rect {
func convertedBy(targetView: UIView?, superView: UIView?) -> Rect {
guard let targetView = targetView,
let superView = superView
else {
return .zero
}
if targetView === superView {
return self
} else {
let frame = superView.convert(self.cgValue, to: targetView)
return Rect(frame)
}
}
}
extension Rect {
/// Produces a new rect which is inside the current rect with given insets.
///
/// - Parameters:
/// - insets: The insets inside the current rect.
///
/// - Returns: A new rect inside the current rect with given insets.
public func rect(inside insets: Insets) -> Rect {
let frame = self.cgValue.inset(by: insets.cgValue)
return Rect(frame)
}
}
extension Rect {
mutating func moveLeft(to xGoal: Float) {
self.origin.x = xGoal
}
mutating func moveCenter(to xGoal: Float) {
self.origin.x = xGoal - self.width.half
}
mutating func moveRight(to xGoal: Float) {
self.origin.x = xGoal - self.width
}
mutating func moveTop(to yGoal: Float) {
self.origin.y = yGoal
}
mutating func moveMiddle(to yGoal: Float) {
self.origin.y = yGoal - self.height.half
}
mutating func moveBottom(to yGoal: Float) {
self.origin.y = yGoal - self.height
}
mutating func moveX(by xOffset: Float) {
self.origin.x += xOffset
}
mutating func moveY(by yOffset: Float) {
self.origin.y += yOffset
}
mutating func moveOrigin(by offset: Point) {
self.origin.x += offset.x
self.origin.y += offset.y
}
mutating func pinchLeft(to xGoal: Float) {
let widthDiff = self.left - xGoal
self.origin.x = xGoal
self.size.width += widthDiff
}
mutating func pinchLeft(by xOffset: Float) {
let widthDiff = -xOffset
self.origin.x += xOffset
self.size.width += widthDiff
}
mutating func pinchRight(to xGoal: Float) {
let widthDiff = xGoal - self.right
self.size.width += widthDiff
}
mutating func pinchRight(by xOffset: Float) {
let widthDiff = xOffset
self.size.width += widthDiff
}
mutating func pinchTop(to yGoal: Float) {
let heightDiff = self.top - yGoal
self.origin.y = yGoal
self.size.height += heightDiff
}
mutating func pinchTop(by yOffset: Float) {
let heightDiff = -yOffset
self.origin.y += yOffset
self.size.height += heightDiff
}
mutating func pinchBottom(to yGoal: Float) {
let heightDiff = yGoal - self.bottom
self.size.height += heightDiff
}
mutating func pinchBottom(by yOffset: Float) {
let heightDiff = yOffset
self.size.height += heightDiff
}
mutating func expandWidth(to widthGoal: Float, from coordinateBaseline: Line.Horizontal) {
let widthDiff = widthGoal - self.width
self.size.width = widthGoal
self.origin.x += self.geometryOriginXDiff(fromCoordinateBaseline: coordinateBaseline, withWidthDiff: widthDiff)
}
mutating func expandWidth(by widthDiff: Float, from baseline: Line.Horizontal) {
self.size.width += widthDiff
self.origin.x += self.geometryOriginXDiff(fromCoordinateBaseline: baseline, withWidthDiff: widthDiff)
}
mutating func expandHeight(to heightGoal: Float, from baseline: Line.Vertical) {
let heightDiff = heightGoal - self.height
self.size.height = heightGoal
self.origin.y += self.geometryOriginYDiff(fromCoordinateBaseline: baseline, withHeightDiff: heightDiff)
}
mutating func expandHeight(by heightDiff: Float, from baseline: Line.Vertical) {
self.size.height += heightDiff
self.origin.y += self.geometryOriginYDiff(fromCoordinateBaseline: baseline, withHeightDiff: heightDiff)
}
mutating func expandSize(to sizeGoal: Size, from basepoint: Point) {
let sizeDiff = sizeGoal - self.size
self.size = sizeGoal
self.origin = self.geometryOriginDiff(fromCoordinateBasePoint: basepoint, withSizeDiff: sizeDiff)
}
mutating func expandSize(by sizeDiff: Size, from basepoint: Point) {
self.size += sizeDiff
self.origin += self.geometryOriginDiff(fromCoordinateBasePoint: basepoint, withSizeDiff: sizeDiff)
}
}
extension Rect {
private func geometryOriginXDiff(fromCoordinateBaseline line: Line.Horizontal, withWidthDiff diff: Float) -> Float {
return 0 - (diff * line.value)
}
private func geometryOriginYDiff(fromCoordinateBaseline line: Line.Vertical, withHeightDiff diff: Float) -> Float {
return 0 - (diff * line.value)
}
private func geometryOriginDiff(fromCoordinateBasePoint point: Point, withSizeDiff diff: Size) -> Point {
let x = 0 - (diff.width * point.x)
let y = 0 - (diff.height * point.y)
return .init(x: x, y: y)
}
}
extension Rect: Equatable {
public static func == (lhs: Rect, rhs: Rect) -> Bool {
return lhs.origin == rhs.origin && lhs.size == rhs.size
}
}
extension Rect: CustomStringConvertible {
public var description: String {
return "(origin: \(self.origin), size: \(self.size))"
}
}
| apache-2.0 | 0746b4ecea4d2f609a98adde6a7088c7 | 28.1 | 507 | 0.688736 | 3.364594 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Extension/Sequence.swift | 1 | 750 | //
// Sequence.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 17..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
extension Sequence {
//ex. locations.sorted(by: {$0.county.compare($1.county)}
typealias ClosureCompare = (Iterator.Element, Iterator.Element) -> ComparisonResult
func sorted(by comparisons: ClosureCompare...) -> [Iterator.Element] {
return self.sorted {
e1, e2 in
for comparison in comparisons {
let comparisonResult = comparison(e1, e2)
guard comparisonResult == .orderedSame
else { return comparisonResult == .orderedAscending}
}
return false
}
}
}
| mit | d3352a688392324b2cc22d5cd448037b | 28.64 | 87 | 0.60054 | 4.463855 | false | false | false | false |
luispadron/UICircularProgressRing | Legacy/UICircularRing.swift | 1 | 18387 | //
// UICircularRing.swift
// UICircularProgressRing
//
// Copyright (c) 2019 Luis Padron
//
// 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
/**
# UICircularRing
This is the base class of `UICircularProgressRing` and `UICircularTimerRing`.
You should not instantiate this class, instead use one of the concrete classes provided
or subclass and make your own.
This is the UIView subclass that creates and handles everything
to do with the circular ring.
This class has a custom CAShapeLayer (`UICircularRingLayer`) which
handels the drawing and animating of the view
## Author
Luis Padron
*/
@IBDesignable open class UICircularRing: UIView {
// MARK: Circle Properties
/**
Whether or not the progress ring should be a full circle.
What this means is that the outer ring will always go from 0 - 360 degrees and
the inner ring will be calculated accordingly depending on current value.
## Important ##
Default = true
When this property is true any value set for `endAngle` will be ignored.
## Author
Luis Padron
*/
@IBInspectable open var fullCircle: Bool = true {
didSet { ringLayer.setNeedsDisplay() }
}
// MARK: View Style
/**
The style of the progress ring.
Type: `UICircularRingStyle`
The five styles include `inside`, `ontop`, `dashed`, `dotted`, and `gradient`
## Important ##
Default = UICircularRingStyle.inside
## Author
Luis Padron
*/
open var style: UICircularRingStyle = .inside {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The options for a gradient ring.
If this is non-`nil` then a gradient style will be applied.
## Important ##
Default = `nil`
*/
open var gradientOptions: UICircularRingGradientOptions? = nil {
didSet { ringLayer.setNeedsDisplay() }
}
/**
A toggle for showing or hiding the value label.
If false the current value will not be shown.
## Important ##
Default = true
## Author
Luis Padron
*/
@IBInspectable public var shouldShowValueText: Bool = true {
didSet { ringLayer.setNeedsDisplay() }
}
/**
A toggle for showing or hiding the value knob when current value == minimum value.
If false the value knob will not be shown when current value == minimum value.
## Important ##
Default = false
## Author
Tom Knapen
*/
@IBInspectable public var shouldDrawMinValueKnob: Bool = false {
didSet { ringLayer.setNeedsDisplay() }
}
/**
Style for the value knob, default is `nil`.
## Important ##
If this is `nil`, no value knob is shown.
*/
open var valueKnobStyle: UICircularRingValueKnobStyle? {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The start angle for the entire progress ring view.
Please note that Cocoa Touch uses a clockwise rotating unit circle.
I.e: 90 degrees is at the bottom and 270 degrees is at the top
## Important ##
Default = 0 (degrees)
Values should be in degrees (they're converted to radians internally)
## Author
Luis Padron
*/
@IBInspectable open var startAngle: CGFloat = 0 {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The end angle for the entire progress ring
Please note that Cocoa Touch uses a clockwise rotating unit circle.
I.e: 90 degrees is at the bottom and 270 degrees is at the top
## Important ##
Default = 360 (degrees)
Values should be in degrees (they're converted to radians internally)
## Author
Luis Padron
*/
@IBInspectable open var endAngle: CGFloat = 360 {
didSet { ringLayer.setNeedsDisplay() }
}
/**
Determines if the progress ring should animate in reverse
## Important ##
Default = false
*/
open var isReverse: Bool = false {
didSet { ringLayer.isReverse = isReverse }
}
// MARK: Outer Ring properties
/**
The width of the outer ring for the progres bar
## Important ##
Default = 10.0
## Author
Luis Padron
*/
@IBInspectable open var outerRingWidth: CGFloat = 10.0 {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The color for the outer ring
## Important ##
Default = UIColor.gray
## Author
Luis Padron
*/
@IBInspectable open var outerRingColor: UIColor = UIColor.gray {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The style for the tip/cap of the outer ring
Type: `CGLineCap`
## Important ##
Default = CGLineCap.butt
This is only noticible when ring is not a full circle.
## Author
Luis Padron
*/
open var outerCapStyle: CGLineCap = .butt {
didSet { ringLayer.setNeedsDisplay() }
}
// MARK: Inner Ring properties
/**
The width of the inner ring for the progres bar
## Important ##
Default = 5.0
## Author
Luis Padron
*/
@IBInspectable open var innerRingWidth: CGFloat = 5.0 {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The color of the inner ring for the progres bar
## Important ##
Default = UIColor.blue
## Author
Luis Padron
*/
@IBInspectable open var innerRingColor: UIColor = UIColor.blue {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The spacing between the outer ring and inner ring
## Important ##
This only applies when using `ringStyle` = `.inside`
Default = 1
## Author
Luis Padron
*/
@IBInspectable open var innerRingSpacing: CGFloat = 1 {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The style for the tip/cap of the inner ring
Type: `CGLineCap`
## Important ##
Default = CGLineCap.round
## Author
Luis Padron
*/
open var innerCapStyle: CGLineCap = .round {
didSet { ringLayer.setNeedsDisplay() }
}
// MARK: Label
/**
The text color for the value label field
## Important ##
Default = UIColor.black
## Author
Luis Padron
*/
@IBInspectable open var fontColor: UIColor = UIColor.black {
didSet { ringLayer.setNeedsDisplay() }
}
/**
The font to be used for the progress indicator.
All font attributes are specified here except for font color, which is done
using `fontColor`.
## Important ##
Default = UIFont.systemFont(ofSize: 18)
## Author
Luis Padron
*/
@IBInspectable open var font: UIFont = UIFont.systemFont(ofSize: 18) {
didSet { ringLayer.setNeedsDisplay() }
}
/**
This returns whether or not the ring is currently animating
## Important ##
Get only property
## Author
Luis Padron
*/
open var isAnimating: Bool {
return ringLayer.animation(forKey: .value) != nil
}
/**
The direction the circle is drawn in
Example: true -> clockwise
## Important ##
Default = true (draw the circle clockwise)
## Author
Pete Walker
*/
@IBInspectable open var isClockwise: Bool = true {
didSet { ringLayer.setNeedsDisplay() }
}
/**
Typealias for animateProperties(duration:animations:completion:) fucntion completion
*/
public typealias PropertyAnimationCompletion = (() -> Void)
// MARK: Private / internal
/**
Set the ring layer to the default layer, cated as custom layer
*/
var ringLayer: UICircularRingLayer {
// swiftlint:disable:next force_cast
return layer as! UICircularRingLayer
}
/// This variable stores how long remains on the timer when it's paused
private var pausedTimeRemaining: TimeInterval = 0
/// Used to determine when the animation was paused
private var animationPauseTime: CFTimeInterval?
/// This stores the animation when the timer is paused. We use this variable to continue the animation where it left off.
/// See https://stackoverflow.com/questions/7568567/restoring-animation-where-it-left-off-when-app-resumes-from-background
var snapshottedAnimation: CAAnimation?
/// The completion timer, also indicates whether or not the view is animating
var animationCompletionTimer: Timer?
typealias AnimationCompletion = () -> Void
// MARK: Methods
/**
Overrides the default layer with the custom UICircularRingLayer class
*/
override open class var layerClass: AnyClass {
return UICircularRingLayer.self
}
/**
Overriden public init to initialize the layer and view
*/
override public init(frame: CGRect) {
super.init(frame: frame)
// Call the internal initializer
initialize()
}
/**
Overriden public init to initialize the layer and view
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Call the internal initializer
initialize()
}
/**
This method initializes the custom CALayer to the default values
*/
func initialize() {
// This view will become the value delegate of the layer, which will call the updateValue method when needed
ringLayer.ring = self
// Helps with pixelation and blurriness on retina devices
ringLayer.contentsScale = UIScreen.main.scale
ringLayer.shouldRasterize = true
ringLayer.rasterizationScale = UIScreen.main.scale * 2
ringLayer.masksToBounds = false
backgroundColor = UIColor.clear
ringLayer.backgroundColor = UIColor.clear.cgColor
NotificationCenter.default.addObserver(self,
selector: #selector(restoreAnimation),
name: UIApplication.willEnterForegroundNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(snapshotAnimation),
name: UIApplication.willResignActiveNotification,
object: nil)
}
/**
Overriden because of custom layer drawing in UICircularRingLayer
*/
open override func draw(_ rect: CGRect) {
super.draw(rect)
}
// MARK: Internal API
/**
These methods are called from the layer class in order to notify
this class about changes to the value and label display.
In this base class they do nothing.
*/
func didUpdateValue(newValue: CGFloat) { }
func willDisplayLabel(label: UILabel) { }
/**
These functions are here to allow reuse between subclasses.
They handle starting, pausing and resetting an animation of the ring.
*/
func startAnimation(duration: TimeInterval, completion: @escaping AnimationCompletion) {
if isAnimating {
animationPauseTime = nil
}
ringLayer.timeOffset = 0
ringLayer.beginTime = 0
ringLayer.speed = 1
ringLayer.animated = duration > 0
ringLayer.animationDuration = duration
// Check if a completion timer is still active and if so stop it
animationCompletionTimer?.invalidate()
animationCompletionTimer = Timer.scheduledTimer(timeInterval: duration,
target: self,
selector: #selector(self.animationDidComplete),
userInfo: completion,
repeats: false)
}
func pauseAnimation() {
guard isAnimating else {
#if DEBUG
print("""
UICircularProgressRing: Progress was paused without having been started.
This has no effect but may indicate that you're unnecessarily calling this method.
""")
#endif
return
}
snapshotAnimation()
let pauseTime = ringLayer.convertTime(CACurrentMediaTime(), from: nil)
animationPauseTime = pauseTime
ringLayer.speed = 0.0
ringLayer.timeOffset = pauseTime
if let fireTime = animationCompletionTimer?.fireDate {
pausedTimeRemaining = fireTime.timeIntervalSince(Date())
} else {
pausedTimeRemaining = 0
}
animationCompletionTimer?.invalidate()
animationCompletionTimer = nil
}
func continueAnimation(completion: @escaping AnimationCompletion) {
guard let pauseTime = animationPauseTime else {
#if DEBUG
print("""
UICircularRing: Progress was continued without having been paused.
This has no effect but may indicate that you're unnecessarily calling this method.
""")
#endif
return
}
restoreAnimation()
ringLayer.speed = 1.0
ringLayer.timeOffset = 0.0
ringLayer.beginTime = 0.0
let timeSincePause = ringLayer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime
ringLayer.beginTime = timeSincePause
animationCompletionTimer?.invalidate()
animationCompletionTimer = Timer.scheduledTimer(timeInterval: pausedTimeRemaining,
target: self,
selector: #selector(animationDidComplete),
userInfo: completion,
repeats: false)
animationPauseTime = nil
}
func resetAnimation() {
ringLayer.animated = false
ringLayer.removeAnimation(forKey: .value)
snapshottedAnimation = nil
// Stop the timer and thus make the completion method not get fired
animationCompletionTimer?.invalidate()
animationCompletionTimer = nil
animationPauseTime = nil
}
// MARK: API
/**
This function allows animation of the animatable properties of the `UICircularRing`.
These properties include `innerRingColor, innerRingWidth, outerRingColor, outerRingWidth, innerRingSpacing, fontColor`.
Simply call this function and inside of the animation block change the animatable properties as you would in any `UView`
animation block.
The completion block is called when all animations finish.
*/
open func animateProperties(duration: TimeInterval, animations: () -> Void) {
animateProperties(duration: duration, animations: animations, completion: nil)
}
/**
This function allows animation of the animatable properties of the `UICircularRing`.
These properties include `innerRingColor, innerRingWidth, outerRingColor, outerRingWidth, innerRingSpacing, fontColor`.
Simply call this function and inside of the animation block change the animatable properties as you would in any `UView`
animation block.
The completion block is called when all animations finish.
*/
open func animateProperties(duration: TimeInterval, animations: () -> Void,
completion: PropertyAnimationCompletion? = nil) {
ringLayer.shouldAnimateProperties = true
ringLayer.propertyAnimationDuration = duration
CATransaction.begin()
CATransaction.setCompletionBlock {
// Reset and call completion
self.ringLayer.shouldAnimateProperties = false
self.ringLayer.propertyAnimationDuration = 0.0
completion?()
}
// Commit and perform animations
animations()
CATransaction.commit()
}
}
// MARK: Helpers
extension UICircularRing {
/**
This method is called when the application goes into the background or when the
ProgressRing is paused using the pauseProgress method.
This is necessary for the animation to properly pick up where it left off.
Triggered by UIApplicationWillResignActive.
## Author
Nicolai Cornelis
*/
@objc func snapshotAnimation() {
guard let animation = ringLayer.animation(forKey: .value) else { return }
snapshottedAnimation = animation
}
/**
This method is called when the application comes back into the foreground or
when the ProgressRing is resumed using the continueProgress method.
This is necessary for the animation to properly pick up where it left off.
Triggered by UIApplicationWillEnterForeground.
## Author
Nicolai Cornelis
*/
@objc func restoreAnimation() {
guard let animation = snapshottedAnimation else { return }
ringLayer.add(animation, forKey: AnimationKeys.value.rawValue)
}
/// Called when the animation timer is complete
@objc func animationDidComplete(withTimer timer: Timer) {
(timer.userInfo as? AnimationCompletion)?()
}
}
extension UICircularRing {
/// Helper enum for animation key
enum AnimationKeys: String {
case value
}
}
| mit | b88f1a1ca0190507ab28e76aac182973 | 28.047393 | 126 | 0.631968 | 5.377888 | false | false | false | false |
danielmartin/swift | test/IRGen/subclass.swift | 2 | 2681 | // RUN: %target-swift-frontend -enable-objc-interop -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK-DAG: %swift.refcounted = type {
// CHECK-DAG: [[TYPE:%swift.type]] = type
// CHECK-DAG: [[OBJC_CLASS:%objc_class]] = type {
// CHECK-DAG: [[OPAQUE:%swift.opaque]] = type
// CHECK-DAG: [[A:%T8subclass1AC]] = type <{ [[REF:%swift.refcounted]], %TSi, %TSi }>
// CHECK-DAG: [[INT:%TSi]] = type <{ i64 }>
// CHECK-DAG: [[B:%T8subclass1BC]] = type <{ [[REF]], [[INT]], [[INT]], [[INT]] }>
// CHECK: @_DATA__TtC8subclass1A = private constant {{.* } }}{
// CHECK: @"$s8subclass1ACMf" = internal global [[A_METADATA:<{.* }>]] <{
// CHECK-SAME: void ([[A]]*)* @"$s8subclass1ACfD",
// CHECK-SAME: i8** @"$sBoWV",
// CHECK-SAME: i64 ptrtoint ([[OBJC_CLASS]]* @"$s8subclass1ACMm" to i64),
// CHECK-SAME: [[OBJC_CLASS]]* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: [[OPAQUE]]* @_objc_empty_cache,
// CHECK-SAME: [[OPAQUE]]* null,
// CHECK-SAME: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1A to i64), i64 1),
// CHECK-SAME: i64 ([[A]]*)* @"$s8subclass1AC1fSiyF",
// CHECK-SAME: [[A]]* ([[TYPE]]*)* @"$s8subclass1AC1gACyFZ"
// CHECK-SAME: }>
// CHECK: @_DATA__TtC8subclass1B = private constant {{.* } }}{
// CHECK: @"$s8subclass1BCMf" = internal global <{ {{.*}} }> <{
// CHECK-SAME: void ([[B]]*)* @"$s8subclass1BCfD",
// CHECK-SAME: i8** @"$sBoWV",
// CHECK-SAME: i64 ptrtoint ([[OBJC_CLASS]]* @"$s8subclass1BCMm" to i64),
// CHECK-SAME: [[TYPE]]* {{.*}} @"$s8subclass1ACMf",
// CHECK-SAME: [[OPAQUE]]* @_objc_empty_cache,
// CHECK-SAME: [[OPAQUE]]* null,
// CHECK-SAME: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1B to i64), i64 1),
// CHECK-SAME: i64 ([[B]]*)* @"$s8subclass1BC1fSiyF",
// CHECK-SAME: [[A]]* ([[TYPE]]*)* @"$s8subclass1AC1gACyFZ"
// CHECK-SAME: }>
// CHECK: @objc_classes = internal global [2 x i8*] [i8* {{.*}} @"$s8subclass1ACN" {{.*}}, i8* {{.*}} @"$s8subclass1BCN" {{.*}}]
class A {
var x = 0
var y = 0
func f() -> Int { return x }
class func g() -> A { return A() }
init() { }
}
class B : A {
var z : Int = 10
override func f() -> Int { return z }
}
class G<T> : A {
}
// Ensure that downcasts to generic types instantiate generic metadata instead
// of trying to reference global metadata. <rdar://problem/14265663>
// CHECK: define hidden swiftcc %T8subclass1GCySiG* @"$s8subclass9a_to_gint1aAA1GCySiGAA1AC_tF"(%T8subclass1AC*) {{.*}} {
func a_to_gint(a: A) -> G<Int> {
// CHECK: call swiftcc %swift.metadata_response @"$s8subclass1GCySiGMa"(i64 0)
// CHECK: call i8* @swift_dynamicCastClassUnconditional
return a as! G<Int>
}
// CHECK: }
| apache-2.0 | c1c23a680245a96da9dd54676e1316da | 40.246154 | 128 | 0.590078 | 2.855165 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/BaseTest/BaseTest/TestPage/RayHealthViewController.swift | 1 | 2276 | //
// RayHealthViewController.swift
// BaseTest
//
// Created by wuyp on 2017/6/27.
// Copyright © 2017年 raymond. All rights reserved.
//
import UIKit
import Common
class RayHealthViewController: UIViewController {
private var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = "测试页面"
self.view.backgroundColor = .purple
initialTabView()
}
//MARK: init subviews
func initialTabView() {
tableView = UITableView(frame: self.view.bounds, style: .grouped)
tableView.height -= 64
tableView.delegate = self
tableView.dataSource = self
tableView.isNeedDefaultNoDataView = true
self.view.addSubview(tableView)
}
//Mark: Network
//MARK: - lazy
fileprivate lazy var dataSource: [String] = {
var source: [String] = []
for i in 0...10 {
source.append("Row\(i)")
}
return source
}()
}
// MARK:- tableview delegate & datasource
extension RayHealthViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
}
cell!.textLabel?.text = dataSource[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
| apache-2.0 | 1d253fbe381b878789459f06dd395f46 | 24.738636 | 100 | 0.615011 | 5.124434 | false | false | false | false |
CodePath2017Group4/travel-app | RoadTripPlanner/CommentsViewController.swift | 1 | 5835 | //
// CommentsViewController.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/14/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
class CommentsViewController: UIViewController {
@IBOutlet weak var composeTextView: UITextView!
@IBOutlet var mainPushUpView: UIView!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var ScreeName: UILabel!
@IBOutlet weak var userName: UILabel!
fileprivate var bottomCounterLabel: UILabel!
fileprivate var postButton: UIButton!
fileprivate var isReadyToPost = false
var initialY: CGFloat!
var offset: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
initialY = mainPushUpView.frame.origin.y
offset = -50
NotificationCenter.default.addObserver(forName: Notification.Name.UIKeyboardWillShow, object: nil, queue: OperationQueue.main) { (notification: Notification) in
self.keyboardWillShow()
}
setupNavbar()
self.automaticallyAdjustsScrollViewInsets = false
composeTextView.placeholder = "What's happening?"
composeTextView.delegate = self
setupCustomBottomBar()
setCountdownLabels(left: 140)
setPostButton(ready: true)
userName.isHidden = true
ScreeName.isHidden = true
keyboardWillShow()
}
func keyboardWillShow() {
mainPushUpView.frame.origin.y = initialY + offset
}
func setupNavbar() {
// let cancelImageView = UIImageView(image: UIImage(named: "cancel"))
// cancelImageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let profileImage = UIImage(named: "profile")
let profileImageView = UIImageView(image: profileImage)
profileImageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
profileImageView.layer.cornerRadius = (profileImageView.frame.size.width)/2
profileImageView.clipsToBounds = true
let leftbarButton = UIBarButtonItem.init(customView: profileImageView)
self.navigationItem.leftBarButtonItem = leftbarButton
self.navigationController?.navigationBar.isHidden = false
}
func setupCustomBottomBar() {
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 50))
customView.backgroundColor = UIColor.white
customView.layer.borderColor = UIColor(red: 170/255, green: 184/255, blue: 194/255, alpha: 1).cgColor
customView.layer.borderWidth = 0.3
composeTextView.inputAccessoryView = customView
self.view.addSubview(composeTextView)
let screenWidth = UIScreen.main.bounds.width
bottomCounterLabel = UILabel()
bottomCounterLabel.frame = CGRect(x: screenWidth - 120, y: 0, width: 30, height: 50)
bottomCounterLabel.font = UIFont(name: "HelveticaNeue-Light", size: 16)
setCountdownLabels(left: 140)
customView.addSubview(bottomCounterLabel)
postButton = UIButton()
postButton.frame = CGRect(x: screenWidth - 80, y: 10, width: 70, height: 30)
postButton.setTitle("Post", for: .normal)
postButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 16)
postButton.layer.cornerRadius = postButton.frame.height / 2
postButton.clipsToBounds = true
postButton.layer.masksToBounds = true
setPostButton(ready: isReadyToPost)
customView.addSubview(postButton)
postButton.addTarget(self, action: #selector(sendTweet), for: .touchUpInside)
}
@IBAction func onCancelButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
func cancelTapped() {
composeTextView.resignFirstResponder()
self.dismiss(animated: true, completion: nil)
}
func setCountdownLabels(left: Int) {
bottomCounterLabel.text = "\(left)"
if (left > 20) {
bottomCounterLabel.textColor = UIColor(red: 101/255, green: 119/255, blue: 134/255, alpha: 1)
} else {
bottomCounterLabel.textColor = UIColor.red
}
}
func setPostButton(ready: Bool) {
postButton.setTitleColor(UIColor.white, for: .normal)
postButton.layer.borderWidth = 0
isReadyToPost = ready
postButton.isUserInteractionEnabled = ready
if (!ready) {
postButton.backgroundColor = UIColor(red: 29/255, green: 161/255, blue: 242/255, alpha: 0.5)
} else {
postButton.backgroundColor = UIColor(red: 29/255, green: 161/255, blue: 242/255, alpha: 1)
}
}
func sendTweet() {
composeTextView.resignFirstResponder()
}
}
// MARK: - Text View delegate methods
extension CommentsViewController : UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let currentCount = textView.text.characters.count
if (currentCount > 0) {
textView.placeholder = ""
}
else{
textView.placeholder = "What's happening?"
}
let charactersLeft = 140 - currentCount
setCountdownLabels(left: charactersLeft)
if (isReadyToPost) {
if (charactersLeft < 0 || charactersLeft > 139) {
setPostButton(ready: false)
}
} else {
if (charactersLeft < 140 && charactersLeft > -1) {
setPostButton(ready: true)
}
}
}
}
| mit | 96c18b9e3b74f6d233eda345036d46e7 | 30.031915 | 168 | 0.605417 | 5.02931 | false | false | false | false |
gvzq/iOS-Twitter | Twitter/UserTweetCell.swift | 1 | 4351 | //
// UserTweetCell.swift
// Twitter
//
// Created by Gerardo Vazquez on 2/24/16.
// Copyright © 2016 Gerardo Vazquez. All rights reserved.
//
import UIKit
class UserTweetCell: UITableViewCell {
@IBOutlet weak var userProfileImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBAction func onFavorite(sender: AnyObject) {
if (tweet.favorited!) {
TwitterClient.sharedInstance.destroyFavorite(tweet.id!)
tweet.favouritesCount!--
tweet.favorited = false
favoriteButton.setImage(UIImage(named: "favorite"), forState: .Normal)
favoriteCountLabel.textColor = UIColor.grayColor()
} else {
TwitterClient.sharedInstance.createFavorite(tweet.id!)
tweet.favouritesCount!++
tweet.favorited = true
favoriteButton.setImage(UIImage(named: "favorite_on"), forState: .Normal)
favoriteCountLabel.textColor = UIColor.redColor()
}
favoriteCountLabel.text = "\(tweet.favouritesCount!)"
}
@IBAction func onRetweet(sender: AnyObject) {
if (tweet.retweeted!) {
TwitterClient.sharedInstance.unretweet(tweet.id!)
tweet.retweetCount!--
tweet.retweeted = false
retweetButton.setImage(UIImage(named: "retweet"), forState: .Normal)
retweetCountLabel.textColor = UIColor.grayColor()
} else {
TwitterClient.sharedInstance.retweet(tweet.id!)
tweet.retweetCount!++
tweet.retweeted = true
retweetButton.setImage(UIImage(named: "retweet_on"), forState: .Normal)
retweetCountLabel.textColor = UIColor(red:0.1, green:0.72, blue:0.6, alpha:1.0)
}
retweetCountLabel.text = "\(tweet.retweetCount!)"
}
var tweet: Tweet! {
didSet {
userProfileImageView.setImageWithURL(NSURL(string: (tweet.user?.profileImageUrl)!)!)
userNameLabel.text = tweet.user?.name
tweetTextLabel.text = tweet.text
timeLabel.text = tweet.createdAtString
let hourDifference = NSCalendar.currentCalendar().components(.Hour, fromDate: tweet.createdAt!, toDate: NSDate(), options: []).hour
let minDifference = NSCalendar.currentCalendar().components(.Minute, fromDate: tweet.createdAt!, toDate: NSDate(), options: []).minute
if (hourDifference == 0) {
timeLabel.text = "\(minDifference)m"
} else if (hourDifference <= 24) {
timeLabel.text = "\(hourDifference)h"
} else {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
timeLabel.text = dateFormatter.stringFromDate(tweet.createdAt!)
}
favoriteCountLabel.text = "\(tweet.favouritesCount!)"
retweetCountLabel.text = "\(tweet.retweetCount!)"
if (tweet.favorited!) {
favoriteButton.setImage(UIImage(named: "favorite_on"), forState: .Normal)
favoriteCountLabel.textColor = UIColor.redColor()
} else {
favoriteButton.setImage(UIImage(named: "favorite"), forState: .Normal)
favoriteCountLabel.textColor = UIColor.grayColor()
}
if (tweet.retweeted!) {
retweetButton.setImage(UIImage(named: "retweet_on"), forState: .Normal)
retweetCountLabel.textColor = UIColor(red:0.1, green:0.72, blue:0.6, alpha:1.0)
} else {
retweetButton.setImage(UIImage(named: "retweet"), forState: .Normal)
retweetCountLabel.textColor = UIColor.grayColor()
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.layoutMargins = UIEdgeInsetsZero
self.preservesSuperviewLayoutMargins = false
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| apache-2.0 | b406bba354fe9a472d97b5a17df36cee | 42.069307 | 147 | 0.621609 | 5.129717 | false | false | false | false |
enstulen/ARKitAnimation | Pods/SwiftCharts/SwiftCharts/Convenience/BarsChart.swift | 1 | 3676 | //
// BarsChart.swift
// Examples
//
// Created by ischuetz on 19/07/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class BarsChartConfig: ChartConfig {
open let valsAxisConfig: ChartAxisConfig
open let xAxisLabelSettings: ChartLabelSettings
open let yAxisLabelSettings: ChartLabelSettings
public init(chartSettings: ChartSettings = ChartSettings(), valsAxisConfig: ChartAxisConfig, xAxisLabelSettings: ChartLabelSettings = ChartLabelSettings(), yAxisLabelSettings: ChartLabelSettings = ChartLabelSettings(), guidelinesConfig: GuidelinesConfig = GuidelinesConfig()) {
self.valsAxisConfig = valsAxisConfig
self.xAxisLabelSettings = xAxisLabelSettings
self.yAxisLabelSettings = yAxisLabelSettings
super.init(chartSettings: chartSettings, guidelinesConfig: guidelinesConfig)
}
}
open class BarsChart: Chart {
public init(frame: CGRect, chartConfig: BarsChartConfig, xTitle: String, yTitle: String, bars barModels: [(String, Double)], color: UIColor, barWidth: CGFloat, animDuration: Float = 0.5, animDelay: Float = 0.5, horizontal: Bool = false) {
let zero = ChartAxisValueDouble(0)
let bars: [ChartBarModel] = barModels.enumerated().map {let (index, barModel) = $0;
return ChartBarModel(constant: ChartAxisValueDouble(index), axisValue1: zero, axisValue2: ChartAxisValueDouble(barModel.1), bgColor: color)
}
let valAxisValues = stride(from: chartConfig.valsAxisConfig.from, through: chartConfig.valsAxisConfig.to, by: chartConfig.valsAxisConfig.by).map{ChartAxisValueDouble($0, labelSettings : chartConfig.xAxisLabelSettings)}
let labelAxisValues = [ChartAxisValueString(order: -1)] + barModels.enumerated().map{ let (index, tuple) = $0; return ChartAxisValueString(tuple.0, order: index, labelSettings : chartConfig.xAxisLabelSettings)} + [ChartAxisValueString(order: barModels.count)]
let (xValues, yValues): ([ChartAxisValue], [ChartAxisValue]) = horizontal ? (valAxisValues, labelAxisValues) : (labelAxisValues, valAxisValues)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: xTitle, settings: chartConfig.xAxisLabelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: yTitle, settings: chartConfig.xAxisLabelSettings.defaultVertical()))
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartConfig.chartSettings, chartFrame: frame, xModel: xModel, yModel: yModel)
let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame)
let barViewSettings = ChartBarViewSettings(animDuration: animDuration, animDelay: animDelay)
let barsLayer: ChartLayer = ChartBarsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, bars: bars, horizontal: horizontal, barWidth: barWidth, settings: barViewSettings)
let guidelinesLayer = GuidelinesDefaultLayerGenerator.generateOpt(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, guidelinesConfig: chartConfig.guidelinesConfig)
let view = ChartBaseView(frame: frame)
let layers: [ChartLayer] = [xAxisLayer, yAxisLayer] + (guidelinesLayer.map{[$0]} ?? []) + [barsLayer]
super.init(
view: view,
innerFrame: innerFrame,
settings: chartConfig.chartSettings,
layers: layers
)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 524418d2096578b70793a91b20afab10 | 56.4375 | 281 | 0.724701 | 5.304473 | false | true | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift | 19 | 21598 | //
// HorizontalBarChartRenderer.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 HorizontalBarChartRenderer: BarChartRenderer
{
fileprivate class Buffer
{
var rects = [CGRect]()
}
public override init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler)
}
// [CGRect] per dataset
fileprivate var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard let
dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let bottom = CGFloat(x - barWidthHalf)
let top = CGFloat(x + barWidthHalf)
var right = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var left = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if right > 0
{
right *= CGFloat(phaseY)
}
else
{
left *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let bottom = CGFloat(x - barWidthHalf)
let top = CGFloat(x + barWidthHalf)
var right = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var left = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
right *= CGFloat(phaseY)
left *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
fileprivate var _barShadowRectBuffer: CGRect = CGRect()
open override func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard let
dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard
let animator = animator,
let barData = dataProvider.barData
else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.y = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.height = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsTop(_barShadowRectBuffer.origin.y + _barShadowRectBuffer.size.height)
{
break
}
if !viewPortHandler.isInBoundsBottom(_barShadowRectBuffer.origin.y)
{
continue
}
_barShadowRectBuffer.origin.x = viewPortHandler.contentLeft
_barShadowRectBuffer.size.width = viewPortHandler.contentWidth
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
break
}
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
continue
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
}
context.restoreGState()
}
open override func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let top = x - barWidthHalf
let bottom = x + barWidthHalf
let left = y1
let right = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixelHorizontal(&rect, phaseY: animator?.phaseY ?? 1.0)
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
var dataSets = barData.dataSets
let textAlign = NSTextAlignment.left
let valueOffsetPlus: CGFloat = 5.0
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let valueFont = dataSet.valueFont
let yOffset = -valueFont.lineHeight / 2.0
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let buffer = _buffers[dataSetIndex]
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let y = rect.origin.y + rect.size.height / 2.0
if !viewPortHandler.isInBoundsTop(rect.origin.y)
{
break
}
if !viewPortHandler.isInBoundsX(rect.origin.x)
{
continue
}
if !viewPortHandler.isInBoundsBottom(rect.origin.y)
{
continue
}
let val = e.y
let valueText = formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler)
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if isInverted
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: (rect.origin.x + rect.size.width)
+ (val >= 0.0 ? posOffset : negOffset),
yPos: y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if each value of a potential stack should be drawn
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let rect = buffer.rects[bufferIndex]
let vals = e.yValues
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsTop(rect.origin.y)
{
break
}
if !viewPortHandler.isInBoundsX(rect.origin.x)
{
continue
}
if !viewPortHandler.isInBoundsBottom(rect.origin.y)
{
continue
}
let val = e.y
let valueText = formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler)
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if isInverted
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: (rect.origin.x + rect.size.width)
+ (val >= 0.0 ? posOffset : negOffset),
yPos: rect.origin.y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(index))
}
else
{
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: CGFloat(y * phaseY), y: 0.0))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let val = vals[k]
let valueText = formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler)
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if isInverted
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
let x = transformed[k].x + (val >= 0 ? posOffset : negOffset)
let y = rect.origin.y + rect.size.height / 2.0
if (!viewPortHandler.isInBoundsTop(y))
{
break
}
if (!viewPortHandler.isInBoundsX(x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(index))
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
open override func isDrawingValuesAllowed(dataProvider: ChartDataProvider?) -> Bool
{
guard let data = dataProvider?.data
else { return false }
return data.entryCount < Int(CGFloat(dataProvider?.maxVisibleCount ?? 0) * (viewPortHandler?.scaleY ?? 1.0))
}
/// Sets the drawing position of the highlight object based on the riven bar-rect.
internal override func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midY, y: barRect.origin.x + barRect.size.width)
}
}
| mit | 96ab3dce451e1beca1dca2dec1a6eec7 | 37.98556 | 129 | 0.41226 | 6.865226 | false | false | false | false |
citrusbyte/Healthy-Baby | M2XDemo/ProfileTableViewController.swift | 1 | 2440 | //
// ProfileTableViewController.swift
// M2XDemo
//
// Created by Luis Floreani on 1/2/15.
// Copyright (c) 2015 citrusbyte.com. All rights reserved.
//
import Foundation
class ProfileTableViewController: UITableViewController {
@IBOutlet var nameLabel: UITextField!
@IBOutlet var dueLabel: UILabel!
@IBOutlet var momHeight: UITextField!
@IBOutlet var momWeight: UITextField!
@IBOutlet var boyCell: UITableViewCell!
@IBOutlet var girlCell: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
boyCell.tintColor = Colors.profileColor
girlCell.tintColor = Colors.profileColor
var formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
dueLabel.text = "\(formatter.stringFromDate(NSDate().dateByAddingMonths(2)))"
var defaults = NSUserDefaults.standardUserDefaults()
let sexVal: AnyObject? = defaults.valueForKey("sex")
var sex = 0
if let val = sexVal as? Int {
sex = val
}
boyCell.accessoryType = sex == 0 ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
girlCell.accessoryType = sex == 1 ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
nameLabel.text = defaults.valueForKey("name") as? String
momHeight.text = defaults.valueForKey("height") as? String
momWeight.text = defaults.valueForKey("weight") as? String
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(boyCell.accessoryType == UITableViewCellAccessoryType.Checkmark ? 0 : 1, forKey: "sex")
defaults.setValue(nameLabel.text, forKey: "name")
defaults.setValue(momHeight.text, forKey: "height")
defaults.setValue(momWeight.text, forKey: "weight")
defaults.synchronize()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
boyCell.accessoryType = indexPath.row == 0 ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
girlCell.accessoryType = indexPath.row == 1 ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
}
}
} | mit | c050ada0214a784ec08aedfa3d4a3078 | 37.746032 | 132 | 0.685656 | 5.202559 | false | false | false | false |
brentdax/swift | test/Driver/Dependencies/fail-simple.swift | 36 | 1217 | /// bad ==> main | bad --> other
// RUN: rm -rf %t && cp -r %S/Inputs/fail-simple/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-FIRST: Handled other.swift
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-SECOND: Handled bad.swift
// CHECK-SECOND-NOT: Handled main.swift
// CHECK-SECOND-NOT: Handled other.swift
// CHECK-RECORD-DAG: "./bad.swift": !dirty [
// CHECK-RECORD-DAG: "./main.swift": !dirty [
// CHECK-RECORD-DAG: "./other.swift": !private [
| apache-2.0 | 86f9d12c79712c66001e1ae8e3d6a628 | 51.913043 | 292 | 0.698439 | 3.065491 | false | false | false | false |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 3.Layer Animations的进阶使用/5.ReplicatingAnimations/ReplicatingAnimations/ViewController.swift | 1 | 4153 | //
// ViewController.swift
// ReplicatingAnimations
//
// Created by Dariel on 16/6/26.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.darkGrayColor()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
dotAnim()
}
func dotAnim() {
let replicator = CAReplicatorLayer()
let dot = CALayer()
let dotLength : CGFloat = 6.0
let dotOffset : CGFloat = 8.0
replicator.frame = view.bounds
view.layer.addSublayer(replicator)
dot.frame = CGRect(x: replicator.frame.size.width - dotLength, y: replicator.position.y, width: dotLength, height: dotLength)
dot.backgroundColor = UIColor.lightGrayColor().CGColor
dot.borderColor = UIColor(white: 1.0, alpha: 1.0).CGColor
dot.borderWidth = 0.5
dot.cornerRadius = 1.5
replicator.addSublayer(dot)
// 进行复制
replicator.instanceCount = Int(view.frame.size.width / dotOffset)
replicator.instanceTransform = CATransform3DMakeTranslation(-dotOffset, 0.0, 0.0)
// let move = CABasicAnimation(keyPath: "position.y")
// move.fromValue = dot.position.y
// move.toValue = dot.position.y - 50.0
// move.duration = 1.0
// move.repeatCount = 10
// dot.addAnimation(move, forKey: nil)
replicator.instanceDelay = 0.02
let scale = CABasicAnimation(keyPath: "transform")
scale.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
scale.toValue = NSValue(CATransform3D: CATransform3DMakeScale(1.4, 15, 1.0))
scale.duration = 0.33
scale.repeatCount = Float.infinity
scale.autoreverses = true
scale.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(scale, forKey: "dotScale")
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 1.0
fade.toValue = 0.2
fade.duration = 0.33
fade.beginTime = CACurrentMediaTime() + 0.33
fade.repeatCount = Float.infinity
fade.autoreverses = true
fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(fade, forKey: "dotOpacity")
let tint = CABasicAnimation(keyPath: "backgroundColor")
tint.fromValue = UIColor.magentaColor().CGColor
tint.toValue = UIColor.cyanColor().CGColor
tint.duration = 0.66
tint.beginTime = CACurrentMediaTime() + 0.28
tint.fillMode = kCAFillModeBackwards
tint.repeatCount = Float.infinity
tint.autoreverses = true
tint.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(tint, forKey: "dotColor")
let initialRotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
initialRotation.fromValue = 0.0
initialRotation.toValue = 0.01
initialRotation.duration = 0.33
initialRotation.removedOnCompletion = false
initialRotation.fillMode = kCAFillModeForwards
initialRotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
replicator.addAnimation(initialRotation, forKey: "initialRotation")
let rotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
rotation.fromValue = 0.01
rotation.toValue = -0.01
rotation.duration = 0.99
rotation.beginTime = CACurrentMediaTime() + 0.33
rotation.repeatCount = Float.infinity
rotation.autoreverses = true
rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
replicator.addAnimation(rotation, forKey: "replicatorRotation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | a02da54f8a10485571b53d32ffdfc1eb | 32.95082 | 133 | 0.652342 | 5.045067 | false | false | false | false |
tkremenek/swift | validation-test/Reflection/reflect_Optional_Any.swift | 13 | 12969 | // validation-test/Reflection/reflect_Optional_Any.swift
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Optional_Any
// RUN: %target-codesign %t/reflect_Optional_Any
// RUN: %target-run %target-swift-reflection-test %t/reflect_Optional_Any | %FileCheck %s --check-prefix=CHECK-%target-ptrsize %add_num_extra_inhabitants
// REQUIRES: reflection_test_support
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
struct TwentyFourByteStruct {
let a: Int64
let b: Int64
let c: Int64
}
// ================================================================
let optionalAnyNonNil: Any? = TwentyFourByteStruct(a: 7, b: 8, c: 9)
reflect(enum: optionalAnyNonNil)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))
// CHECK-64: (case name=none index=1))
// CHECK-64: Mangled name: $sypSg
// CHECK-64: Demangled name: Swift.Optional<Any>
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=some index=0
// CHECK-64: (protocol_composition)
// CHECK-64: )
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))
// CHECK-32: (case name=none index=1))
// CHECK-32: Mangled name: $sypSg
// CHECK-32: Demangled name: Swift.Optional<Any>
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=some index=0
// CHECK-32: (protocol_composition)
// CHECK-32: )
// ================================================================
let optionalAnyNil: Any? = nil
reflect(enum: optionalAnyNil)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))
// CHECK-64: (case name=none index=1))
// CHECK-64: Mangled name: $sypSg
// CHECK-64: Demangled name: Swift.Optional<Any>
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=none index=1)
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))
// CHECK-32: (case name=none index=1))
// CHECK-32: Mangled name: $sypSg
// CHECK-32: Demangled name: Swift.Optional<Any>
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=none index=1)
// ================================================================
let optionalOptionalAnyNil: Any?? = nil
reflect(enum: optionalOptionalAnyNil)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition)))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))
// CHECK-64: Mangled name: $sypSgSg
// CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=none index=1)
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition)))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))
// CHECK-32: Mangled name: $sypSgSg
// CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=none index=1)
// ================================================================
let optionalOptionalAnySomeNil: Any?? = .some(nil)
reflect(enum: optionalOptionalAnySomeNil)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition)))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))
// CHECK-64: Mangled name: $sypSgSg
// CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=some index=0
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition))
// CHECK-64: )
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition)))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))
// CHECK-32: Mangled name: $sypSgSg
// CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=some index=0
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition))
// CHECK-32: )
// ================================================================
let optionalOptionalAnyNonNil: Any?? = .some(.some(7))
reflect(enum: optionalOptionalAnyNonNil)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition)))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))
// CHECK-64: Mangled name: $sypSgSg
// CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=some index=0
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (protocol_composition))
// CHECK-64: )
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition)))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))
// CHECK-32: Mangled name: $sypSgSg
// CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>>
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=some index=0
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (protocol_composition))
// CHECK-32: )
// ================================================================
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 7f4c644602b0fd08b7fa70fa4986b159 | 43.262799 | 153 | 0.676691 | 3.235778 | false | false | false | false |
away4m/Vendors | Vendors/Extensions/URL.swift | 1 | 2745 | //
// URL.swift
// Vendors
//
// Created by ALI KIRAN on 2/19/18.
//
import Foundation
// MARK: - Properties
public extension URL {
/// SwifterSwift: Dictionary of the URL's query parameters
public var queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else { return nil }
var items: [String: String] = [:]
for queryItem in queryItems {
items[queryItem.name] = queryItem.value
}
return items
}
}
// MARK: - Methods
public extension URL {
/// SwifterSwift: URL with appending query parameters.
///
/// - Parameter parameters: parameters dictionary.
/// - Returns: URL with appending given query parameters.
public func appendingQueryParameters(_ parameters: [String: String]) -> URL {
var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
var items = urlComponents.queryItems ?? []
items += parameters.map({ URLQueryItem(name: $0, value: $1) })
urlComponents.queryItems = items
return urlComponents.url!
}
/// SwifterSwift: Append query parameters to URL.
///
/// - Parameter parameters: parameters dictionary.
public mutating func appendQueryParameters(_ parameters: [String: String]) {
self = appendingQueryParameters(parameters)
}
/// Creates a URL initialized to the given string value.
public init(stringLiteral value: StringLiteralType) {
guard let url = URL(string: value) else { fatalError("Could not create URL from: \(value)") }
self = url
}
/// Creates a URL initialized to the given value.
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
guard let url = URL(string: value) else { fatalError("Could not create URL from: \(value)") }
self = url
}
/// Creates a URL initialized to the given value.
public init(unicodeScalarLiteral value: StringLiteralType) {
guard let url = URL(string: value) else { fatalError("Could not create URL from: \(value)") }
self = url
}
public func httpsURL() -> URL {
guard scheme != "https" else {
return self
}
let str = absoluteString.replacingOccurrences(of: "http://", with: "https://")
return URL(string: str)!
}
}
/**
Append a path component to a url. Equivalent to `lhs.appendingPathComponent(rhs)`.
- parameter lhs: The url.
- parameter rhs: The path component to append.
- returns: The original url with the appended path component.
*/
public func + (lhs: URL, rhs: String) -> URL {
return lhs.appendingPathComponent(rhs)
}
| mit | 9c50fdd52271ac5356ec43bc0baaca7a | 30.551724 | 147 | 0.65173 | 4.629005 | false | false | false | false |
nixzhu/SuperPreview | SuperPreview/PhotoViewController.swift | 1 | 4542 | //
// PhotoViewController.swift
// SuperPreview
//
// Created by NIX on 2016/11/28.
// Copyright © 2016年 nixWork. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController {
let photo: Photo
var mode: PhotoDisplayMode
lazy var scalingImageView: ScalingImageView = {
let view = ScalingImageView(frame: self.view.bounds)
view.delegate = self
view.mode = mode
return view
}()
private lazy var loadingView: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .white)
view.hidesWhenStopped = true
return view
}()
lazy var doubleTapGestureRecognizer: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer()
tap.addTarget(self, action: #selector(PhotoViewController.didDoubleTap(_:)))
tap.numberOfTapsRequired = 2
return tap
}()
private lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let longPress = UILongPressGestureRecognizer()
longPress.addTarget(self, action: #selector(PhotoViewController.didLongPress(_:)))
return longPress
}()
deinit {
scalingImageView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
// MARK: Init
init(photo: Photo, photoDisplayMode: PhotoDisplayMode) {
self.photo = photo
self.mode = photoDisplayMode
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Life Circle
override func viewDidLoad() {
super.viewDidLoad()
scalingImageView.frame = view.bounds
scalingImageView.image = photo.image
view.addSubview(scalingImageView)
photo.updatedImage = { [weak self] image in
self?.scalingImageView.image = image
if image != nil {
self?.loadingView.stopAnimating()
}
}
if photo.image == nil {
loadingView.startAnimating()
}
view.addSubview(loadingView)
view.addGestureRecognizer(doubleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scalingImageView.frame = view.bounds
loadingView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
}
// MARK: Selectors
@objc private func didDoubleTap(_ sender: UITapGestureRecognizer) {
let scrollViewSize = scalingImageView.bounds.size
var pointInView = sender.location(in: scalingImageView.imageView)
var newZoomScale = min(scalingImageView.maximumZoomScale, scalingImageView.minimumZoomScale * 2)
if let imageSize = scalingImageView.imageView.image?.size, (imageSize.height / imageSize.width) > (scrollViewSize.height / scrollViewSize.width) {
pointInView.x = scalingImageView.imageView.bounds.width / 2
let widthScale = scrollViewSize.width / imageSize.width
newZoomScale = widthScale
}
let isZoomIn = (scalingImageView.zoomScale >= newZoomScale) || (abs(scalingImageView.zoomScale - newZoomScale) <= 0.01)
if isZoomIn {
newZoomScale = scalingImageView.minimumZoomScale
}
scalingImageView.isDirectionalLockEnabled = !isZoomIn
let width = scrollViewSize.width / newZoomScale
let height = scrollViewSize.height / newZoomScale
let originX = pointInView.x - (width / 2)
let originY = pointInView.y - (height / 2)
let rectToZoomTo = CGRect(x: originX, y: originY, width: width, height: height)
scalingImageView.zoom(to: rectToZoomTo, animated: true)
}
@objc private func didLongPress(_ sender: UILongPressGestureRecognizer) {
// TODO: didLongPress
}
}
// MARK: - UIScrollViewDelegate
extension PhotoViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scalingImageView.imageView
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.panGestureRecognizer.isEnabled = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, withView view: UIView?) {
if scrollView.zoomScale == scrollView.minimumZoomScale {
scrollView.panGestureRecognizer.isEnabled = false
}
}
}
| mit | 896679b3cea02fb7e747b26a3b549add | 32.375 | 154 | 0.670632 | 5.390736 | false | false | false | false |
libiao88/iOS-Study-Demo | [转]GCD用法学习_swift版/GooglyPuff/PhotoDetailViewController.swift | 15 | 6581 | //
// PhotoDetailViewController.swift
// GooglyPuff
//
// Created by Bjørn Olav Ruud on 06.08.14.
// Copyright (c) 2014 raywenderlich.com. All rights reserved.
//
import UIKit
private let RetinaToEyeScaleFactor: CGFloat = 0.5
private let FaceBoundsToEyeScaleFactor: CGFloat = 4.0
class PhotoDetailViewController: UIViewController {
@IBOutlet var photoScrollView: UIScrollView!
@IBOutlet var photoImageView: UIImageView!
var image: UIImage!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
assert(image != nil, "Image not set; required to use view controller")
photoImageView.image = image
// Resize if neccessary to ensure it's not pixelated
if image.size.height <= photoImageView.bounds.size.height &&
image.size.width <= photoImageView.bounds.size.width {
photoImageView.contentMode = .Center
}
// 何时使用何种队列类型快速指南: – 自定义顺序队列:当你想顺序执行后台任务并追踪它时,这是一个很好的选择。因为同时只有一个任务在执行,因此消除了资源竞争。注意如果需要从方法中获取数据,你必须内置另一个闭包来得到它或者考虑使用dispatch_sync。 – 主队列(顺序):当并发队列中的任务完成需要更新UI的时候,这是一个通常的选择。为达此目的,需要在一个闭包中嵌入另一个闭包。同时,如果在主队列中调用dispatch_async来返回主队列,能保证新的任务会在当前方法完成后再执行。 – 并发队列:通常用来执行与UI无关的后台任务。
// dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
// let overlayImage = self.faceOverlayImageFromImage(self.image)//耗时的动作在全局队列里完成。
// dispatch_async(dispatch_get_main_queue()) { // 2
// self.fadeInNewImage(overlayImage) // 3完成以后在主线程更新
// }
// }
//和上面一样,只是调用自定义方法来完成队列的创建
dispatch_async(GlobalUserInitiatedQueue) {
let overlayImage = self.faceOverlayImageFromImage(self.image)
dispatch_async(GlobalMainQueue) {
self.fadeInNewImage(overlayImage)
}
}
}
}
// MARK: - Private Methods
private extension PhotoDetailViewController {
func faceOverlayImageFromImage(image: UIImage) -> UIImage {
let detector = CIDetector(ofType: CIDetectorTypeFace,
context: nil,
options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
// Get features from the image
let newImage = CIImage(CGImage: image.CGImage)
let features = detector.featuresInImage(newImage) as [CIFaceFeature]!
UIGraphicsBeginImageContext(image.size)
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
// Draws this in the upper left coordinate system
image.drawInRect(imageRect, blendMode: kCGBlendModeNormal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
for faceFeature in features {
let faceRect = faceFeature.bounds
CGContextSaveGState(context)
// CI and CG work in different coordinate systems, we should translate to
// the correct one so we don't get mixed up when calculating the face position.
CGContextTranslateCTM(context, 0.0, imageRect.size.height)
CGContextScaleCTM(context, 1.0, -1.0)
if faceFeature.hasLeftEyePosition {
let leftEyePosition = faceFeature.leftEyePosition
let eyeWidth = faceRect.size.width / FaceBoundsToEyeScaleFactor
let eyeHeight = faceRect.size.height / FaceBoundsToEyeScaleFactor
let eyeRect = CGRect(x: leftEyePosition.x - eyeWidth / 2.0,
y: leftEyePosition.y - eyeHeight / 2.0,
width: eyeWidth,
height: eyeHeight)
drawEyeBallForFrame(eyeRect)
}
if faceFeature.hasRightEyePosition {
let leftEyePosition = faceFeature.rightEyePosition
let eyeWidth = faceRect.size.width / FaceBoundsToEyeScaleFactor
let eyeHeight = faceRect.size.height / FaceBoundsToEyeScaleFactor
let eyeRect = CGRect(x: leftEyePosition.x - eyeWidth / 2.0,
y: leftEyePosition.y - eyeHeight / 2.0,
width: eyeWidth,
height: eyeHeight)
drawEyeBallForFrame(eyeRect)
}
CGContextRestoreGState(context);
}
let overlayImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return overlayImage
}
func faceRotationInRadians(leftEyePoint startPoint: CGPoint, rightEyePoint endPoint: CGPoint) -> CGFloat {
let deltaX = endPoint.x - startPoint.x
let deltaY = endPoint.y - startPoint.y
let angleInRadians = CGFloat(atan2f(Float(deltaY), Float(deltaX)))
return angleInRadians;
}
func drawEyeBallForFrame(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextAddEllipseInRect(context, rect)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillPath(context)
var x: CGFloat
var y: CGFloat
var eyeSizeWidth: CGFloat
var eyeSizeHeight: CGFloat
eyeSizeWidth = rect.size.width * RetinaToEyeScaleFactor
eyeSizeHeight = rect.size.height * RetinaToEyeScaleFactor
x = CGFloat(arc4random_uniform(UInt32(rect.size.width - eyeSizeWidth)))
y = CGFloat(arc4random_uniform(UInt32(rect.size.height - eyeSizeHeight)))
x += rect.origin.x
y += rect.origin.y
let eyeSize = min(eyeSizeWidth, eyeSizeHeight)
let eyeBallRect = CGRect(x: x, y: y, width: eyeSize, height: eyeSize)
CGContextAddEllipseInRect(context, eyeBallRect)
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextFillPath(context)
}
func fadeInNewImage(newImage: UIImage) {
let tmpImageView = UIImageView(image: newImage)
tmpImageView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
tmpImageView.contentMode = photoImageView.contentMode
tmpImageView.frame = photoImageView.bounds
tmpImageView.alpha = 0.0
photoImageView.addSubview(tmpImageView)
UIView.animateWithDuration(0.75, animations: {
tmpImageView.alpha = 1.0
}, completion: {
finished in
self.photoImageView.image = newImage
tmpImageView.removeFromSuperview()
})
}
}
// MARK: - UIScrollViewDelegate
extension PhotoDetailViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
return photoImageView
}
}
| apache-2.0 | 17679e4ea488d48c0445e2567f2a745d | 34.435294 | 274 | 0.717629 | 4.312097 | false | false | false | false |
everlof/RestKit-n-Django-Sample | Project_iOS/Cite/AddQuoteViewController.swift | 1 | 3118 | //
// AddQuoteViewController.swift
// Cite
//
// Created by David Everlöf on 09/08/16.
//
//
import Foundation
import UIKit
class AddQuoteViewController: ViewController,
UITextViewDelegate
{
var context: NSManagedObjectContext! = nil
var newQuote: Quote! = nil
let textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
context = RKObjectManager.sharedManager().managedObjectStore.newChildManagedObjectContextWithConcurrencyType(.PrivateQueueConcurrencyType, tracksChanges: false)
newQuote = context.insertNewObjectForEntityForName(String(Quote)) as! Quote
self.navigationItem.title = "New Quote"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Publish",
style: .Plain,
target: self,
action: #selector(publish)
)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
view.addSubview(textView)
textView.backgroundColor = UIColor.lightGrayColor()
NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: textView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: textView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: textView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.5, constant: 0.0).active = true
}
func publish() {
// All modifications must be performed on the correct thread
// which we accomplish by using `performBlock(AndWait)`
self.context.performBlockAndWait({
if let user = appDelegate().loginManager.loggedInUserInContext(self.context) {
// Set the attributes
self.newQuote.quote = self.textView.attributedText.string
self.newQuote.owner = user
// Just set this to something - right now we dont wanna create a textfield for it..
self.newQuote.author = "unKnown"
// Now create the object remotely as well, and it will be inserted into
// the contexts that are used by the rest of the app
RKObjectManager.sharedManager().postObject(self.newQuote, path: nil, parameters: nil, success: {
reqOp, mapResult in
dispatch_async(dispatch_get_main_queue(), {
self.navigationController?.popViewControllerAnimated(true)
})
}, failure: {
reqOp, err in
print("Fail!")
})
}
})
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
return true
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
return true
}
func textViewDidChange(textView: UITextView) {
let hashTags = textView.resolveHashTags()
if hashTags.count > 0 {
print("Hashtags: \n\(hashTags)")
}
}
} | mit | 3802011209065988dd84934a33d91967 | 32.891304 | 164 | 0.678216 | 4.597345 | false | false | false | false |
Keanyuan/SwiftContact | SwiftContent/SwiftContent/Classes/PhotoBrower/LLPhotoBrowser/LLBrowserViewController.swift | 1 | 18787 | //
// LLBrowserViewController.swift
// LLPhotoBrowser
//
// Created by LvJianfeng on 2017/4/14.
// Copyright © 2017年 LvJianfeng. All rights reserved.
//
import UIKit
public typealias LLDidActionSheetAction = (NSInteger, UIImageView, String?) -> Void
let k_LL_ScreenWidth = UIScreen.main.bounds.size.width
let k_LL_ScreenHeight = UIScreen.main.bounds.size.height
let k_LL_QRCodeTitle = "识别图中二维码"
/// Image Object
open class LLBrowserModel: NSObject {
// Data
open var data: Any? = nil {
didSet {
if data is UIImage {
image = data as? UIImage
}else if data is String {
if (data as! String).hasPrefix("http") {
imageURL = data as? String
}else{
image = UIImage.init(named: data as! String)
}
}else{
image = LLAssetManager.image("ll_placeholder")
}
}
}
// URL
open var imageURL: String? = nil
// Image
open var image: UIImage? = nil
// Source Image
open var sourceImageView: UIImageView? = nil
}
/// Browser View Controller
open class LLBrowserViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout ,UIViewControllerTransitioningDelegate {
/// Device
fileprivate var isRotate: Bool = false
/// First Open
open var isFirstOpen: Bool = false
/// Ratio
fileprivate var isEqualRatio: Bool = false
/// UIImage Or URL
fileprivate var photoArray: [LLBrowserModel]?
/// Current Index
fileprivate var currentIndex: NSInteger = 0
/// ActionSheet Title Array
fileprivate var sheetTitileArray: [String]? = []
/// Show Current Index Label
fileprivate var currentIndexLabel: UILabel?
/// Vertical Big Rect Array
fileprivate var verticalBigRectArray: [NSValue]?
/// Horizontal Big Rect Array
fileprivate var horizontalBigRectArray: [NSValue]?
/// UIDeviceOrientation
fileprivate var currentOrientation: UIDeviceOrientation?
/// Can Use QRCode Default false
fileprivate var isOpenQRCodeCheck: Bool = false
/// Collection View
open var collectView: UICollectionView?
/// Background View
fileprivate var backView: UIView?
/// Remind View
open var remindView: LLRemindView?
/// Action Sheet
open var browserActionSheet: LLBrowserActionSheet?
/// Action Sheet Did
open var didActionSheetSelected: LLDidActionSheetAction?
/// Screen Width
open var screenWidth = UIScreen.main.bounds.size.width
/// Screen Height
open var screenHeight = UIScreen.main.bounds.size.height
/// Space
fileprivate let browserSpace: CGFloat = 20.0
/// Custom ActionSheet Style
/// Background Color
open var actionSheetBackgroundColor: UIColor?
/// Cell Height default 44.0
open var actionSheetCellHeight: CGFloat? = 44.0
/// Cell Background Color default white
open var actionSheetCellBackgroundColor: UIColor? = UIColor.white
/// Title Font default UIFont.systemFont(ofSize: 15.0)
open var actionSheetTitleFont: UIFont? = UIFont.systemFont(ofSize: 15.0)
/// Title Color default black
open var actionSheetTitleTextColor: UIColor? = UIColor.black
/// Cancel Color default black
open var actionSheetCancelTextColor: UIColor? = UIColor.black
/// Cancel Title default 取消
open var actionSheetCancelTitle: String? = "取消"
/// Line Color default 212.0 212.0 212.0
open var actionSheetLineColor: UIColor? = UIColor.init(red: 212.0/255.0, green: 212.0/255.0, blue: 212.0/255.0, alpha: 1.0)
/// Init With Data
public init(photoArray: [LLBrowserModel], currentIndex: NSInteger, sheetTitileArray: [String]? = nil, isOpenQRCodeCheck: Bool = false, didActionSheet: LLDidActionSheetAction? = nil) {
self.photoArray = photoArray
self.currentIndex = currentIndex
self.sheetTitileArray = sheetTitileArray
self.isEqualRatio = true
self.isFirstOpen = true
self.isOpenQRCodeCheck = isOpenQRCodeCheck
self.screenWidth = k_LL_ScreenWidth
self.screenHeight = k_LL_ScreenHeight
self.currentOrientation = UIDeviceOrientation.portrait
self.verticalBigRectArray = []
self.horizontalBigRectArray = []
self.didActionSheetSelected = didActionSheet
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Dealloc
deinit {
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
// Show ViewController
open func presentBrowserViewController() {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
// Present
rootViewController?.present(self, animated: false, completion: nil)
}
// View Did Load
override open func viewDidLoad() {
super.viewDidLoad()
// PresentationStyle
modalPresentationStyle = .overCurrentContext
// Init Data
initData()
createBrowserView()
}
// Init Data
func initData() {
for browserModel in photoArray! {
var vRect = CGRect.zero
var hRect = CGRect.zero
// Scale
if isEqualRatio {
if let sourceImageView = browserModel.sourceImageView, sourceImageView.image != nil {
vRect = (sourceImageView.image?.getBigImageSizeWithScreenWidth(w: k_LL_ScreenWidth, h: k_LL_ScreenHeight))!
hRect = (sourceImageView.image?.getBigImageSizeWithScreenWidth(w: k_LL_ScreenHeight, h: k_LL_ScreenWidth))!
}
}
let vValue = NSValue.init(cgRect: vRect)
verticalBigRectArray?.append(vValue)
let hValue = NSValue.init(cgRect: hRect)
horizontalBigRectArray?.append(hValue)
}
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// Get Rect In Window
func getFrameInWindow(view: UIView) -> CGRect{
return (view.superview?.convert(view.frame, to: UIApplication.shared.keyWindow?.rootViewController?.view))!
}
// Create
func createBrowserView() {
view.backgroundColor = UIColor.black
// Back View
backView = UIView.init(frame: self.view.bounds)
backView?.backgroundColor = UIColor.clear
view.addSubview(backView!)
let flowLayout = UICollectionViewFlowLayout.init()
flowLayout.minimumLineSpacing = 0
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
// Cell Item Spacing
flowLayout.minimumInteritemSpacing = 0
// Row Spacing
flowLayout.minimumLineSpacing = 0
collectView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth + browserSpace, height: screenHeight), collectionViewLayout: flowLayout)
collectView?.delegate = self
collectView?.dataSource = self
collectView?.isPagingEnabled = true
collectView?.bounces = false
collectView?.showsVerticalScrollIndicator = false
collectView?.showsHorizontalScrollIndicator = false
collectView?.backgroundColor = UIColor.black
collectView?.register(LLBrowserCollectionViewCell.self, forCellWithReuseIdentifier: "LLBrowserCollectionViewCell")
collectView?.contentOffset = CGPoint.init(x: CGFloat(currentIndex) * (screenWidth + browserSpace), y: 0)
backView?.addSubview(collectView!)
currentIndexLabel = UILabel.init()
currentIndexLabel?.textColor = UIColor.white
currentIndexLabel?.frame = CGRect.init(x: 0, y: screenHeight - 50, width: screenWidth, height: 50)
currentIndexLabel?.text = "\(currentIndex + 1)/\((photoArray?.count)!)"
currentIndexLabel?.textAlignment = .center
backView?.addSubview(currentIndexLabel!)
remindView = LLRemindView.init(frame: (backView?.bounds)!)
backView?.addSubview(remindView!)
}
// MARK: UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (photoArray?.count)!
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LLBrowserCollectionViewCell", for: indexPath) as! LLBrowserCollectionViewCell
let imageItem = photoArray?[indexPath.row]
// Reset scale
cell.zoomScrollView?.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight)
cell.zoomScrollView?.zoomScale = 1.0
// Reset contentSize of scale before
cell.zoomScrollView?.contentSize = CGSize.init(width: screenWidth, height: screenHeight)
if let sourceImageView = imageItem?.sourceImageView {
cell.zoomScrollView?.zoomImageView?.contentMode = sourceImageView.contentMode
cell.zoomScrollView?.zoomImageView?.clipsToBounds = sourceImageView.clipsToBounds
}
cell.loadingView?.ll_updateFrameInSuperviewCenterWithSize(size: CGSize.init(width: 30, height: 30))
var imageRect = verticalBigRectArray?[indexPath.row].cgRectValue
if currentOrientation != UIDeviceOrientation.portrait {
imageRect = horizontalBigRectArray?[indexPath.row].cgRectValue
}
loadBrowserImagerWithModel(item: imageItem!, cell: cell, imageFrame: imageRect!)
cell.tapClick { [weak self] (cell) in
self?.tap(cell: cell)
}
cell.longPress { [weak self] (cell) in
self?.longPress(cell: cell)
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: screenWidth + browserSpace, height: screenHeight)
}
// MARK: UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
open func loadBrowserImagerWithModel(item: LLBrowserModel, cell: LLBrowserCollectionViewCell, imageFrame: CGRect) {
}
// MARK: UIScrollViewDeletate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !isRotate {
currentIndex = NSInteger(scrollView.contentOffset.x / (screenWidth + browserSpace))
currentIndexLabel?.text = "\(currentIndex + 1)/\((photoArray?.count)!)"
}
isRotate = false
}
// Device Change
func deviceOrientationDidChange(notification: NSNotification) {
let orientation = UIDevice.current.orientation
if orientation == .portrait || orientation == .landscapeLeft || orientation == .landscapeRight {
isRotate = true
currentOrientation = orientation
if currentOrientation == UIDeviceOrientation.portrait {
screenWidth = k_LL_ScreenWidth
screenHeight = k_LL_ScreenHeight
UIView.animate(withDuration: 0.5, animations: {
self.backView?.transform = CGAffineTransform(rotationAngle: 0)
})
}else{
screenWidth = k_LL_ScreenHeight
screenHeight = k_LL_ScreenWidth
if currentOrientation == .landscapeLeft {
UIView.animate(withDuration: 0.5, animations: {
self.backView?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
})
}else{
UIView.animate(withDuration: 0.5, animations: {
self.backView?.transform = CGAffineTransform(rotationAngle:CGFloat(-Double.pi / 2))
})
}
}
backView?.frame = CGRect.init(x: 0, y: 0, width: k_LL_ScreenWidth, height: k_LL_ScreenHeight)
currentIndexLabel?.frame = CGRect.init(x: 0, y: screenHeight - 50, width: screenWidth, height: 50)
remindView?.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight)
if let _ = browserActionSheet {
browserActionSheet?.updateFrameByTransform()
}
collectView?.collectionViewLayout.invalidateLayout()
collectView?.frame = CGRect.init(x: 0, y: 0, width: screenWidth + browserSpace, height: screenHeight)
collectView?.contentOffset = CGPoint.init(x: (screenWidth + browserSpace) * CGFloat(currentIndex), y: 0)
collectView?.reloadData()
}
}
// MARK: Status Bar
override open var prefersStatusBarHidden: Bool {
if !(collectView?.isUserInteractionEnabled)! {
return false
}
return true
}
// MARK: Tap
func tap(cell: LLBrowserCollectionViewCell) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
view.backgroundColor = UIColor.clear
// Background Color
collectView?.backgroundColor = UIColor.clear
collectView?.isUserInteractionEnabled = false
// Status Bar
setNeedsStatusBarAppearanceUpdate()
let cellArray = collectView?.visibleCells
for lcell in cellArray! {
(lcell as! LLBrowserCollectionViewCell).loadingView?.stopAnimating()
}
currentIndexLabel?.removeFromSuperview()
currentIndexLabel = nil
let indexPath = collectView?.indexPath(for: cell)
cell.zoomScrollView?.zoomScale = 1.0
let item = photoArray?[(indexPath?.row)!]
if let smallImageView = item?.sourceImageView {
var rect = getFrameInWindow(view: smallImageView)
var transform = CGAffineTransform(rotationAngle: 0)
if currentOrientation == .landscapeLeft {
transform = CGAffineTransform(rotationAngle:CGFloat(-Double.pi / 2))
rect = CGRect.init(x: rect.origin.y, y: k_LL_ScreenWidth - rect.size.width - rect.origin.x, width: rect.size.height, height: rect.size.width)
}else if currentOrientation == .landscapeRight{
transform = CGAffineTransform(rotationAngle:CGFloat(Double.pi / 2))
rect = CGRect.init(x: k_LL_ScreenHeight - rect.size.height - rect.origin.y, y: rect.origin.x, width: rect.size.height, height: rect.size.width)
}
UIView.animate(withDuration: 0.3, animations: {
cell.zoomScrollView?.zoomImageView?.transform = transform
cell.zoomScrollView?.zoomImageView?.frame = rect
}, completion: { (finished) in
self.dismiss(animated: false, completion: nil)
})
}else{
UIView.animate(withDuration: 0.1, animations: {
self.view.alpha = 0.0
}, completion: { (finished) in
self.dismiss(animated: false, completion: nil)
})
}
}
// MARK: Long Press
func longPress(cell: LLBrowserCollectionViewCell) {
if let _ = browserActionSheet {
browserActionSheet?.removeFromSuperview()
browserActionSheet = nil
}
var qrcodeString: String? = nil
if isOpenQRCodeCheck {
/// 没有使用异步,是因为不确定sheetTitileArray是否使用,如果没有使用,弹出来的仅先显示取消,显得太突兀了。
/// 如有需求或者疑问可以issues
qrcodeString = findAvailableQRCode(imageView: (cell.zoomScrollView?.zoomImageView)!)
if let _ = qrcodeString {
if !(sheetTitileArray?.contains(k_LL_QRCodeTitle))! {
sheetTitileArray?.append(k_LL_QRCodeTitle)
}
}else{
if (sheetTitileArray?.contains(k_LL_QRCodeTitle))! {
sheetTitileArray?.remove(at: (sheetTitileArray?.index(of: k_LL_QRCodeTitle))!)
}
}
}
guard let titleArray = sheetTitileArray, titleArray.count > 0 else {
return
}
guard let _ = didActionSheetSelected else {
print("注意注意:既然存在ActionSheetTitle,就必须实现点击哦~~~~")
return
}
browserActionSheet = LLBrowserActionSheet.init(titleArray: sheetTitileArray!, cancelTitle: actionSheetCancelTitle!, cellHeight: actionSheetCellHeight!,backgroundColor: actionSheetBackgroundColor, cellBackgroundColor: actionSheetCellBackgroundColor!, titleFont: actionSheetTitleFont!, titleTextColor: actionSheetTitleTextColor!, cancelTextColor: actionSheetCancelTextColor!, lineColor: actionSheetLineColor!, didSelectedCell:
{ [weak self] (index) in
self?.didActionSheetSelected!(index, (cell.zoomScrollView?.zoomImageView)!, qrcodeString)
})
browserActionSheet?.show(backView!)
}
// MARK: Show Remind View
func show(_ content: String? = nil) {
remindView?.show(content)
self.perform(#selector(hide), with: nil, afterDelay: 1.2)
}
func showError(_ content: String? = nil) {
remindView?.showError(content)
self.perform(#selector(hide), with: nil, afterDelay: 1.2)
}
func hide() {
remindView?.hide()
}
// MARK: CIDetector
func findAvailableQRCode(imageView: UIImageView) -> String? {
let detector: CIDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])!
let ciImage: CIImage = CIImage.init(image: imageView.image!)!
let features = detector.features(in: ciImage)
for feature in features as! [CIQRCodeFeature] {
return feature.messageString ?? nil
}
return nil
}
}
| mit | 0b11d244f84940b6b8f4c16a0e8a02d5 | 39.198704 | 432 | 0.638137 | 5.3071 | false | false | false | false |
AlexRamey/mbird-iOS | iOS Client/PodcastsController/PodcastsCoordinator.swift | 1 | 3329 | //
// PodcastsCoordinator.swift
// iOS Client
//
// Created by Jonathan Witten on 12/9/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
import UIKit
class PodcastsCoordinator: NSObject, Coordinator, PodcastTableViewDelegate, UninstallerDelegate, PodcastDetailHandler, PodcastInfoHandler {
var childCoordinators: [Coordinator] = []
var podcastDetailViewController: PodcastDetailViewController? {
return navigationController.viewControllers.last as? PodcastDetailViewController
}
var rootViewController: UIViewController {
return navigationController
}
let podcastsStore: MBPodcastsStore
let player: PodcastPlayer
var uninstaller: Uninstaller
private lazy var navigationController: UINavigationController = {
return UINavigationController()
}()
init(store: MBPodcastsStore, player: PodcastPlayer) {
self.podcastsStore = store
self.player = player
self.uninstaller = PodcastUninstaller(store: self.podcastsStore, player: self.player)
}
func start() {
let podcastsController = MBPodcastsViewController.instantiateFromStoryboard(uninstaller: uninstaller)
podcastsController.delegate = self
uninstaller.delegate = self
navigationController.pushViewController(podcastsController, animated: true)
}
// MARK: - PodcastTableViewDelegate
// this is also called from the app coordinator when a user taps the now playing bar
func didSelectPodcast(_ podcast: Podcast) {
let detailViewController = PodcastDetailViewController.instantiateFromStoryboard(podcast: podcast, player: player, uninstaller: uninstaller, handler: self)
self.navigationController.pushViewController(detailViewController, animated: true)
}
func filterPodcasts() {
let filterViewController = PodcastsFilterViewController.instantiateFromStoryboard(repository: self.podcastsStore)
self.navigationController.pushViewController(filterViewController, animated: true)
}
// MARK: - UninstallerDelegate
func alertForUninstallItem(completion: @escaping ((UninstallApprovalStatus) -> Void)) {
let alert = UIAlertController(title: "Are you sure you would like to uninstall this podcast?", message: "Doing so will force the playback to end.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ -> Void in completion(.deny) })
alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ -> Void in completion(.approve)})
rootViewController.present(alert, animated: true, completion: nil)
}
// MARK: - PodcastDetailHandler
func dismissDetail() {
navigationController.popViewController(animated: false)
}
// MARK: - PodcastFilterHandler
func viewInfo() {
let infoController = PodcastInfoViewController.instantiateFromStoryboard(repository: podcastsStore, handler: self)
let navController = UINavigationController(rootViewController: infoController)
navigationController.present(navController, animated: true, completion: nil)
}
// MARK: - PodcastInfoHandler
func dismissInfo() {
self.navigationController.dismiss(animated: true, completion: nil)
}
}
| mit | a9d428edf1b08a80a9a0360c252e259a | 41.666667 | 179 | 0.72506 | 5.473684 | false | false | false | false |
luowei/Swift-Samples | iOS10Notification/NotificationUIContent/NotificationViewController.swift | 1 | 2739 | //
// NotificationViewController.swift
// NotificationUIContent
//
// Created by luowei on 2016/11/8.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
import UserNotifications
import UserNotificationsUI
struct NotificationPresentItem {
let url: URL
let title: String
let text: String
}
class NotificationViewController: UIViewController, UNNotificationContentExtension {
var items: [NotificationPresentItem] = []
private var index: Int = 0
@IBOutlet var imageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
}
func didReceive(_ notification: UNNotification) {
let content = notification.request.content
if let items = content.userInfo["items"] as? [[String: AnyObject]] {
for i in 0..<items.count {
let item = items[i]
guard let title = item["title"] as? String, let text = item["text"] as? String else {
continue
}
if i > content.attachments.count - 1 {
continue
}
let url = content.attachments[i].url
let presentItem = NotificationPresentItem(url: url, title: title, text: text)
self.items.append(presentItem)
}
}
updateUI(index: 0)
}
private func updateUI(index: Int) {
let item = items[index]
if item.url.startAccessingSecurityScopedResource() {
let image = UIImage(contentsOfFile: item.url.path)
imageView.image = image
item.url.stopAccessingSecurityScopedResource()
}
titleLabel.text = item.title
textLabel.text = item.text
self.index = index
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "switch" {
let nextIndex: Int
if index == 0 {
nextIndex = 1
} else {
nextIndex = 0
}
updateUI(index: nextIndex)
completion(.doNotDismiss)
} else if response.actionIdentifier == "open" {
completion(.dismissAndForwardAction)
} else if response.actionIdentifier == "dismiss" {
completion(.dismiss)
} else {
completion(.dismissAndForwardAction)
}
}
}
| apache-2.0 | 152e340e75903bcc3850807bb5336076 | 29.065934 | 153 | 0.573465 | 5.29207 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/ParseLiveQuery/Sources/ParseLiveQuery/ObjCCompat.swift | 2 | 13229 | /**
* Copyright (c) 2016-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import Parse
import BoltsSwift
/**
This protocol describes the interface for handling events from a live query client.
You can use this protocol on any custom class of yours, instead of Subscription, if it fits your use case better.
*/
@objc(PFLiveQuerySubscriptionHandling)
public protocol ObjCCompat_SubscriptionHandling {
/**
Tells the handler that an event has been received from the live query server.
- parameter query: The query that the event occurred on.
- parameter event: The event that has been recieved from the server.
- parameter client: The live query client which received this event.
*/
@objc(liveQuery:didRecieveEvent:inClient:)
optional func didRecieveEvent(_ query: PFQuery<PFObject>, event: ObjCCompat.Event, client: Client)
/**
Tells the handler that an error has been received from the live query server.
- parameter query: The query that the error occurred on.
- parameter error: The error that the server has encountered.
- parameter client: The live query client which received this error.
*/
@objc(liveQuery:didEncounterError:inClient:)
optional func didRecieveError(_ query: PFQuery<PFObject>, error: NSError, client: Client)
/**
Tells the handler that a query has been successfully registered with the server.
- note: This may be invoked multiple times if the client disconnects/reconnects.
- parameter query: The query that has been subscribed.
- parameter client: The live query client which subscribed this query.
*/
@objc(liveQuery:didSubscribeInClient:)
optional func didSubscribe(_ query: PFQuery<PFObject>, client: Client)
/**
Tells the handler that a query has been successfully deregistered from the server.
- note: This is not called unless `unregister()` is explicitly called.
- parameter query: The query that has been unsubscribed.
- parameter client: The live query client which unsubscribed this query.
*/
@objc(liveQuery:didUnsubscribeInClient:)
optional func didUnsubscribe(_ query: PFQuery<PFObject>, client: Client)
}
// HACK: Compiler bug causes enums that are declared in structs that are marked as @objc to not actually be emitted by
// the compiler (lolwut?). Moving this to global scope fixes the problem, but we can't change the objc name of an enum
// either, so we pollute the swift namespace here.
// TODO: Fix this eventually.
/**
A type of an update event on a specific object from the live query server.
*/
@objc
public enum PFLiveQueryEventType: Int {
/// The object has been updated, and is now included in the query.
case entered
/// The object has been updated, and is no longer included in the query.
case left
/// The object has been created, and is a part of the query.
case created
/// The object has been updated, and is still a part of the query.
case updated
/// The object has been deleted, and is no longer included in the query.
case deleted
}
/**
This struct wraps up all of our Objective-C compatibility layer. You should never need to touch this if you're using Swift.
*/
public struct ObjCCompat {
fileprivate init() { }
/**
Represents an update on a specific object from the live query server.
*/
@objc(PFLiveQueryEvent)
open class Event: NSObject {
/// Type of the event.
@objc
open let type: PFLiveQueryEventType
/// Object this event is for.
@objc
open let object: PFObject
init(type: PFLiveQueryEventType, object: PFObject) {
self.type = type
self.object = object
}
}
/**
A default implementation of the SubscriptionHandling protocol, using blocks for callbacks.
*/
@objc(PFLiveQuerySubscription)
open class Subscription: NSObject {
public typealias SubscribeHandler = @convention(block) (PFQuery<PFObject>) -> Void
public typealias ErrorHandler = @convention(block) (PFQuery<PFObject>, NSError) -> Void
public typealias EventHandler = @convention(block) (PFQuery<PFObject>, Event) -> Void
public typealias ObjectHandler = @convention(block) (PFQuery<PFObject>, PFObject) -> Void
var subscribeHandlers = [SubscribeHandler]()
var unsubscribeHandlers = [SubscribeHandler]()
var errorHandlers = [ErrorHandler]()
var eventHandlers = [EventHandler]()
/**
Register a callback for when a client succesfully subscribes to a query.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addSubscribeHandler(_ handler: @escaping SubscribeHandler) -> Subscription {
subscribeHandlers.append(handler)
return self
}
/**
Register a callback for when a query has been unsubscribed.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addUnsubscribeHandler(_ handler: @escaping SubscribeHandler) -> Subscription {
unsubscribeHandlers.append(handler)
return self
}
/**
Register a callback for when an error occurs.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addErrorHandler(_ handler: @escaping ErrorHandler) -> Subscription {
errorHandlers.append(handler)
return self
}
/**
Register a callback for when an event occurs.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addEventHandler(_ handler: @escaping EventHandler) -> Subscription {
eventHandlers.append(handler)
return self
}
/**
Register a callback for when an object enters a query.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addEnterHandler(_ handler: @escaping ObjectHandler) -> Subscription {
return addEventHandler { $1.type == .entered ? handler($0, $1.object) : () }
}
/**
Register a callback for when an object leaves a query.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addLeaveHandler(_ handler: @escaping ObjectHandler) -> Subscription {
return addEventHandler { $1.type == .left ? handler($0, $1.object) : () }
}
/**
Register a callback for when an object that matches the query is created.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addCreateHandler(_ handler: @escaping ObjectHandler) -> Subscription {
return addEventHandler { $1.type == .created ? handler($0, $1.object) : () }
}
/**
Register a callback for when an object that matches the query is updated.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addUpdateHandler(_ handler: @escaping ObjectHandler) -> Subscription {
return addEventHandler { $1.type == .updated ? handler($0, $1.object) : () }
}
/**
Register a callback for when an object that matches the query is deleted.
- parameter handler: The callback to register.
- returns: The same subscription, for easy chaining.
*/
open func addDeleteHandler(_ handler: @escaping ObjectHandler) -> Subscription {
return addEventHandler { $1.type == .deleted ? handler($0, $1.object) : () }
}
}
}
extension ObjCCompat.Subscription: ObjCCompat_SubscriptionHandling {
public func didRecieveEvent(_ query: PFQuery<PFObject>, event: ObjCCompat.Event, client: Client) {
eventHandlers.forEach { $0(query, event) }
}
public func didRecieveError(_ query: PFQuery<PFObject>, error: NSError, client: Client) {
errorHandlers.forEach { $0(query, error) }
}
public func didSubscribe(_ query: PFQuery<PFObject>, client: Client) {
subscribeHandlers.forEach { $0(query) }
}
public func didUnsubscribe(_ query: PFQuery<PFObject>, client: Client) {
unsubscribeHandlers.forEach { $0(query) }
}
}
extension Client {
fileprivate class HandlerConverter: SubscriptionHandling {
typealias T = PFObject
fileprivate static var associatedObjectKey: Int = 0
fileprivate weak var handler: ObjCCompat_SubscriptionHandling?
init(handler: ObjCCompat_SubscriptionHandling) {
self.handler = handler
objc_setAssociatedObject(handler, &HandlerConverter.associatedObjectKey, self, .OBJC_ASSOCIATION_RETAIN)
}
fileprivate func didReceive(_ event: Event<T>, forQuery query: PFQuery<T>, inClient client: Client) {
handler?.didRecieveEvent?(query, event: ObjCCompat.Event(event: event), client: client)
}
fileprivate func didEncounter(_ error: Error, forQuery query: PFQuery<T>, inClient client: Client) {
handler?.didRecieveError?(query, error: error as NSError, client: client)
}
fileprivate func didSubscribe(toQuery query: PFQuery<T>, inClient client: Client) {
handler?.didSubscribe?(query, client: client)
}
fileprivate func didUnsubscribe(fromQuery query: PFQuery<T>, inClient client: Client) {
handler?.didUnsubscribe?(query, client: client)
}
}
/**
Registers a query for live updates, using a custom subscription handler.
- parameter query: The query to register for updates.
- parameter handler: A custom subscription handler.
- returns: The subscription that has just been registered.
*/
@objc(subscribeToQuery:withHandler:)
public func _PF_objc_subscribe(
_ query: PFQuery<PFObject>, handler: ObjCCompat_SubscriptionHandling
) -> ObjCCompat_SubscriptionHandling {
let swiftHandler = HandlerConverter(handler: handler)
_ = subscribe(query, handler: swiftHandler)
return handler
}
/**
Registers a query for live updates, using the default subscription handler.
- parameter query: The query to register for updates.
- returns: The subscription that has just been registered.
*/
@objc(subscribeToQuery:)
public func _PF_objc_subscribe(_ query: PFQuery<PFObject>) -> ObjCCompat.Subscription {
let subscription = ObjCCompat.Subscription()
_ = _PF_objc_subscribe(query, handler: subscription)
return subscription
}
/**
Unsubscribes a specific handler from a query.
- parameter query: The query to unsubscribe from.
- parameter handler: The specific handler to unsubscribe from.
*/
@objc(unsubscribeFromQuery:withHandler:)
public func _PF_objc_unsubscribe(_ query: PFQuery<PFObject>, subscriptionHandler: ObjCCompat_SubscriptionHandling) {
unsubscribe { record in
guard let handler = record.subscriptionHandler as? HandlerConverter
else {
return false
}
return record.query == query && handler.handler === subscriptionHandler
}
}
}
// HACK: Another compiler bug - if you have a required initializer with a generic type, the compiler simply refuses to
// emit the entire class altogether. Moving this to an extension for now solves the issue.
extension ObjCCompat.Event {
convenience init<T>(event: ParseLiveQuery.Event<T>) {
let results: (type: PFLiveQueryEventType, object: PFObject) = {
switch event {
case .entered(let object): return (.entered, object)
case .left(let object): return (.left, object)
case .created(let object): return (.created, object)
case .updated(let object): return (.updated, object)
case .deleted(let object): return (.deleted, object)
}
}()
self.init(type: results.type, object: results.object)
}
}
extension PFQuery {
/**
Register this PFQuery for updates with Live Queries.
This uses the shared live query client, and creates a default subscription handler for you.
- returns: The created subscription for observing.
*/
@objc(subscribe)
public func _PF_objc_subscribe() -> ObjCCompat.Subscription {
return Client.shared._PF_objc_subscribe(self as! PFQuery<PFObject>)
}
}
| mit | 99d0b3a17e850ece7304f47befadc83f | 35.849582 | 124 | 0.660141 | 4.950973 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Requests/Notifications/SetUserSetupRequest.swift | 1 | 1221 | //
// SetUserSetupRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/28/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Alamofire
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451711
public struct SetUserSetupRequest: Request {
public let endpoint: ApiEndpoint = .SetUserSetup
public let httpMethod: Alamofire.Method = .POST
public let account: Account
public var parameters: [String : AnyObject] = [:]
public init(withAccount account: Account, triggerOnReply: Bool, triggerOnMention: Bool,
triggerKeywords: [String]) {
self.account = account
self.parameters["triggerOnReply"] = triggerOnReply ? "true" : "false"
self.parameters["triggerOnMention"] = triggerOnMention ? "true" : "false"
if triggerKeywords.count > 0 {
var concatenatedWords = ""
for word in triggerKeywords {
if word == triggerKeywords[0] {
concatenatedWords = word
} else {
concatenatedWords = "\(concatenatedWords),\(word)"
}
}
self.parameters["triggerKeywords"] = concatenatedWords
}
}
}
| mit | 62c16a04de8e19bc093e54fdceba40cf | 31.105263 | 91 | 0.618033 | 4.603774 | false | false | false | false |
Flinesoft/BartyCrouch | Tests/BartyCrouchKitTests/DemoTests/Directory.swift | 1 | 1548 | import Foundation
final class Directory: Codable {
struct File: Codable {
let relativePath: String
let contents: String
init(
baseDirectoryUrl: URL,
relativePath: String
) throws {
self.relativePath = relativePath
self.contents = try String(contentsOf: baseDirectoryUrl.appendingPathComponent(relativePath), encoding: .utf8)
}
func write(into directory: URL) throws {
let fileUrl = directory.appendingPathComponent(relativePath)
let contentsData = contents.data(using: .utf8)!
try FileManager.default.createFile(
atPath: fileUrl.path,
withIntermediateDirectories: true,
contents: contentsData
)
}
}
let files: [File]
init(
files: [File]
) {
self.files = files
}
static func read(fromDirPath directoryPath: String) throws -> Directory {
let enumerator = FileManager.default.enumerator(atPath: directoryPath)!
let baseDirectoryUrl = URL(fileURLWithPath: directoryPath, isDirectory: true)
var files: [File] = []
while let nextObject = enumerator.nextObject() as? String {
guard !nextObject.hasSuffix(".xcuserstate") else { continue }
guard !nextObject.hasSuffix(".DS_Store") else { continue }
guard enumerator.fileAttributes![FileAttributeKey.type] as! String == FileAttributeType.typeRegular.rawValue
else { continue }
let file = try File(baseDirectoryUrl: baseDirectoryUrl, relativePath: nextObject)
files.append(file)
}
return Directory(files: files)
}
}
| mit | 81f65616f6ae464f6de9892329a77850 | 28.769231 | 116 | 0.689922 | 4.748466 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/AppMenuAnimatedImage.swift | 1 | 5914 | //
// AppMenuAnimatedImage.swift
// Telegram
//
// Created by Mikhail Filimonov on 08.12.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import AppKit
import TelegramCore
import Postbox
typealias MenuAnimation = LocalAnimatedSticker
extension MenuAnimation {
var value: (NSColor, ContextMenuItem)-> AppMenuItemImageDrawable {
{ color, item in
return AppMenuAnimatedImage(self, color, item)
}
}
}
struct MenuRemoteAnimation {
fileprivate let context: AccountContext
fileprivate let file: TelegramMediaFile
fileprivate let thumb: LocalAnimatedSticker
fileprivate let bot: Peer
init(_ context: AccountContext, file: TelegramMediaFile, bot: Peer, thumb: LocalAnimatedSticker) {
self.context = context
self.file = file
self.bot = bot
self.thumb = thumb
}
var value: (NSColor, ContextMenuItem)-> AppMenuItemImageDrawable {
{ color, item in
return AppMenuAnimatedRemoteImage(self, color, item)
}
}
}
final class AppMenuAnimatedImage : LottiePlayerView, AppMenuItemImageDrawable {
private let sticker: LocalAnimatedSticker
private let item: ContextMenuItem
init(_ sticker: LocalAnimatedSticker, _ color: NSColor?, _ item: ContextMenuItem) {
self.sticker = sticker
self.item = item
super.init(frame: NSMakeRect(0, 0, 18, 18))
if let data = sticker.data {
var colors:[LottieColor] = []
if let color = color {
colors = [.init(keyPath: "", color: color)]
} else {
colors = []
}
let animation = LottieAnimation(compressed: data, key: LottieAnimationEntryKey.init(key: .bundle(self.sticker.rawValue), size: frame.size), type: .lottie, cachePurpose: .none, playPolicy: .framesCount(1), maximumFps: 60, colors: colors, metalSupport: false)
self.set(animation, reset: true, saveContext: false, animated: false)
}
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init() {
fatalError("init() has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func isEqual(to item: ContextMenuItem) -> Bool {
return self.item.id == item.id
}
func setColor(_ color: NSColor) {
self.setColors([.init(keyPath: "", color: color)])
}
func updateState(_ controlState: ControlState) {
switch controlState {
case .Hover:
if self.animation?.playPolicy == .framesCount(1), self.currentState != .playing {
self.set(self.animation?.withUpdatedPolicy(.once), reset: false)
} else {
self.playAgain()
}
default:
break
}
}
}
final class AppMenuAnimatedRemoteImage : LottiePlayerView, AppMenuItemImageDrawable {
private let sticker: MenuRemoteAnimation
private let item: ContextMenuItem
private let disposable = MetaDisposable()
private let color: NSColor?
init(_ sticker: MenuRemoteAnimation, _ color: NSColor?, _ item: ContextMenuItem) {
self.sticker = sticker
self.item = item
self.color = color
super.init(frame: NSMakeRect(0, 0, 18, 18))
if let reference = PeerReference(sticker.bot) {
_ = fetchedMediaResource(mediaBox: sticker.context.account.postbox.mediaBox, reference: .media(media: .attachBot(peer: reference, media: sticker.file), resource: sticker.file.resource)).start()
}
let signal = sticker.context.account.postbox.mediaBox.resourceData(sticker.file.resource, attemptSynchronously: true) |> deliverOnMainQueue
disposable.set(signal.start(next: { [weak self] data in
if data.complete, let data = try? Data(contentsOf: URL(fileURLWithPath: data.path)) {
self?.apply(data)
} else {
if let data = self?.sticker.thumb.data {
self?.apply(data)
}
}
}))
}
private func apply(_ data: Data) {
var colors:[LottieColor] = []
if let color = color {
colors = [.init(keyPath: "", color: color)]
} else {
colors = []
}
let animation = LottieAnimation(compressed: data, key: LottieAnimationEntryKey(key: .bundle("file_id_\(self.sticker.file.fileId)_\(data.hashValue)"), size: frame.size), type: .lottie, cachePurpose: .none, playPolicy: .framesCount(1), maximumFps: 60, colors: colors, metalSupport: false)
self.set(animation, reset: true, saveContext: false, animated: false)
}
deinit {
disposable.dispose()
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init() {
fatalError("init() has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func isEqual(to item: ContextMenuItem) -> Bool {
return self.item.id == item.id
}
func setColor(_ color: NSColor) {
self.setColors([.init(keyPath: "", color: color)])
}
func updateState(_ controlState: ControlState) {
switch controlState {
case .Hover:
if self.animation?.playPolicy == .framesCount(1) {
self.set(self.animation?.withUpdatedPolicy(.once), reset: false)
} else {
self.playAgain()
}
default:
break
}
}
}
| gpl-2.0 | b7a3d5952ea426646f6a68e9fd22ea8d | 30.452128 | 294 | 0.602909 | 4.734187 | false | false | false | false |
jpsim/Commandant | Tests/CommandantTests/OptionSpec.swift | 3 | 6597 | //
// OptionSpec.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-10-25.
// Copyright (c) 2014 Carthage. All rights reserved.
//
@testable import Commandant
import Foundation
import Nimble
import Quick
import Result
class OptionsProtocolSpec: QuickSpec {
override func spec() {
describe("CommandMode.Arguments") {
func tryArguments(_ arguments: String...) -> Result<TestOptions, CommandantError<NoError>> {
return TestOptions.evaluate(.arguments(ArgumentParser(arguments)))
}
it("should fail if a required argument is missing") {
expect(tryArguments().value).to(beNil())
}
it("should fail if an option is missing a value") {
expect(tryArguments("required", "--intValue").value).to(beNil())
}
it("should succeed without optional arguments") {
let value = tryArguments("required").value
let expected = TestOptions(intValue: 42, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
it("should succeed with some optional arguments") {
let value = tryArguments("required", "--intValue", "3", "--optionalStringValue", "baz", "fuzzbuzz").value
let expected = TestOptions(intValue: 3, stringValue: "foobar", optionalStringValue: "baz", optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
it("should override previous optional arguments") {
let value = tryArguments("required", "--intValue", "3", "--stringValue", "fuzzbuzz", "--intValue", "5", "--stringValue", "bazbuzz").value
let expected = TestOptions(intValue: 5, stringValue: "bazbuzz", optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
it("should enable a boolean flag") {
let value = tryArguments("required", "--enabled", "--intValue", "3", "fuzzbuzz").value
let expected = TestOptions(intValue: 3, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "fuzzbuzz", requiredName: "required", enabled: true, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
it("should re-disable a boolean flag") {
let value = tryArguments("required", "--enabled", "--no-enabled", "--intValue", "3", "fuzzbuzz").value
let expected = TestOptions(intValue: 3, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
it("should enable multiple boolean flags") {
let value = tryArguments("required", "-fg").value
let expected = TestOptions(intValue: 42, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: true, glob: true, arguments: [])
expect(value).to(equal(expected))
}
it("should consume the rest of positional arguments") {
let value = tryArguments("required", "optional", "value1", "value2").value
let expected = TestOptions(intValue: 42, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "optional", requiredName: "required", enabled: false, force: false, glob: false, arguments: [ "value1", "value2" ])
expect(value).to(equal(expected))
}
it("should treat -- as the end of valued options") {
let value = tryArguments("--", "--intValue").value
let expected = TestOptions(intValue: 42, stringValue: "foobar", optionalStringValue: nil, optionalFilename: "filename", requiredName: "--intValue", enabled: false, force: false, glob: false, arguments: [])
expect(value).to(equal(expected))
}
}
describe("CommandMode.Usage") {
it("should return an error containing usage information") {
let error = TestOptions.evaluate(.usage).error
expect(error?.description).to(contain("intValue"))
expect(error?.description).to(contain("stringValue"))
expect(error?.description).to(contain("name you're required to"))
expect(error?.description).to(contain("optionally specify"))
}
}
}
}
struct TestOptions: OptionsProtocol, Equatable {
let intValue: Int
let stringValue: String
let optionalStringValue: String?
let optionalFilename: String
let requiredName: String
let enabled: Bool
let force: Bool
let glob: Bool
let arguments: [String]
typealias ClientError = NoError
static func create(_ a: Int) -> (String) -> (String?) -> (String) -> (String) -> (Bool) -> (Bool) -> (Bool) -> ([String]) -> TestOptions {
return { b in { c in { d in { e in { f in { g in { h in { i in
return self.init(intValue: a, stringValue: b, optionalStringValue: c, optionalFilename: e, requiredName: d, enabled: f, force: g, glob: h, arguments: i)
} } } } } } } }
}
static func evaluate(_ m: CommandMode) -> Result<TestOptions, CommandantError<NoError>> {
return create
<*> m <| Option(key: "intValue", defaultValue: 42, usage: "Some integer value")
<*> m <| Option(key: "stringValue", defaultValue: "foobar", usage: "Some string value")
<*> m <| Option<String?>(key: "optionalStringValue", defaultValue: nil, usage: "Some string value")
<*> m <| Argument(usage: "A name you're required to specify")
<*> m <| Argument(defaultValue: "filename", usage: "A filename that you can optionally specify")
<*> m <| Option(key: "enabled", defaultValue: false, usage: "Whether to be enabled")
<*> m <| Switch(flag: "f", key: "force", usage: "Whether to force")
<*> m <| Switch(flag: "g", key: "glob", usage: "Whether to glob")
<*> m <| Argument(defaultValue: [], usage: "An argument list that consumes the rest of positional arguments")
}
}
func ==(lhs: TestOptions, rhs: TestOptions) -> Bool {
return lhs.intValue == rhs.intValue && lhs.stringValue == rhs.stringValue && lhs.optionalStringValue == rhs.optionalStringValue && lhs.optionalFilename == rhs.optionalFilename && lhs.requiredName == rhs.requiredName && lhs.enabled == rhs.enabled && lhs.force == rhs.force && lhs.glob == rhs.glob && lhs.arguments == rhs.arguments
}
extension TestOptions: CustomStringConvertible {
var description: String {
return "{ intValue: \(intValue), stringValue: \(stringValue), optionalStringValue: \(optionalStringValue), optionalFilename: \(optionalFilename), requiredName: \(requiredName), enabled: \(enabled), force: \(force), glob: \(glob), arguments: \(arguments) }"
}
}
| mit | bf2c8e9d6ace98ac701acd0090aa6b6d | 48.977273 | 330 | 0.691678 | 3.974096 | false | true | false | false |
ello/ello-ios | Sources/Model/LocalPerson.swift | 1 | 1566 | ////
/// LocalPerson.swift
//
// version 1: initial
// version 2: change 'id' from Int32 to String
let LocalPersonVersion = 2
@objc(LocalPerson)
final class LocalPerson: Model {
let name: String
let emails: [String]
let id: String
var identifier: String {
return "\(id)"
}
init(name: String, emails: [String], id: String) {
self.name = name
self.emails = emails
self.id = id
super.init(version: LocalPersonVersion)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.name = decoder.decodeKey("name")
self.emails = decoder.decodeKey("emails")
let version: Int = decoder.decodeKey("version")
if version < 2 {
let idInt: Int32 = decoder.decodeKey("id")
self.id = "\(idInt)"
}
else {
self.id = decoder.decodeKey("id")
}
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(name, forKey: "name")
coder.encodeObject(emails, forKey: "emails")
coder.encodeObject(id, forKey: "id")
super.encode(with: coder.coder)
}
// this shouldn't ever get called
class func fromJSON(_ data: [String: Any]) -> LocalPerson {
return LocalPerson(name: "Unknown", emails: ["[email protected]"], id: "unknown")
}
}
extension LocalPerson: JSONSaveable {
var uniqueId: String? { return "LocalPerson-\(id)" }
var tableId: String? { return id }
}
| mit | a108d46bc3e00064e58128d88efa3dc1 | 26 | 91 | 0.592593 | 3.984733 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/DP/MinPathSum.swift | 1 | 762 | //
// MinPathSum.swift
// LeetCode
//
// Created by 黄伯驹 on 2022/5/16.
// Copyright © 2022 伯驹 黄. All rights reserved.
//
import Foundation
class MinPathSum {
func minPathSum(_ grid: [[Int]]) -> Int {
let m = grid.count
let n = grid[0].count
var memo = Array(repeating: Array(repeating: 0, count: n), count: m)
memo[0][0] = grid[0][0]
for i in 1 ..< m {
memo[i][0] = memo[i - 1][0] + grid[i][0]
}
for j in 1 ..< n {
memo[0][j] = memo[0][j - 1] + grid[0][j]
}
for i in 1 ..< m {
for j in 1 ..< n {
memo[i][j] = min(memo[i-1][j], memo[i][j-1]) + grid[i][j]
}
}
return memo[m-1][n-1]
}
}
| mit | e5e7ce2b2773cefd24e54a1683da91ac | 23.966667 | 76 | 0.443258 | 2.925781 | false | false | false | false |
allenngn/firefox-ios | Storage/SQL/SQLiteLogins.swift | 15 | 37568 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = XCGLogger.defaultInstance()
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let AllLoginTables: Args = [TableLoginsMirror, TableLoginsLocal]
enum SyncStatus: Int {
// Ordinarily not needed; synced items are removed from the overlay. But they start here when cloned.
case Synced = 0
// A material change that we want to upload on next sync.
case Changed = 1
// Created locally.
case New = 2
}
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 2 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
// We ignore the version.
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local])
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db, version: to)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
let protectionSpace = NSURLProtectionSpace(host: row["hostname"] as! String,
port: 0,
`protocol`: nil,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
var login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
var login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Result<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? " +
"ORDER BY timeLastUsed DESC"
let args: Args = [protectionSpace.host, protectionSpace.host]
log.debug("Looking for login: \(args[0])")
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Result<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [protectionSpace.host, username, protectionSpace.host, username]
usernameMatch = "username = ?"
} else {
args = [protectionSpace.host, protectionSpace.host]
usernameMatch = "username IS NULL"
}
log.debug("Looking for login: \(username), \(args[0])")
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND username IS ? " +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Result<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferResult(value[0]!)
}
}
public func addLogin(login: LoginData) -> Success {
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
login.username,
login.password,
login.guid,
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,?,?,?, 1, ?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Result<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func cloneMirrorToOverlay(#whereClause: String?, args: Args?) -> Deferred<Result<Int>> {
let shared =
"guid " +
", hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", timesUsed" +
", username" +
", password "
let local =
", local_modified " +
", is_deleted " +
", sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(\(shared)\(local)) " +
"SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status " +
"FROM \(TableLoginsMirror) " +
(whereClause ?? "")
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferResult(NoSuchRecordError(guid: guid))
}
}
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", timeLastUsed = ?, timePasswordChanged = ?, password = ?" +
", hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func removeLoginByGUID(guid: GUID) -> Success {
let nowMillis = NSDate.now()
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid = ? AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid = ?"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(delete, withArgs: args)
>>> { self.db.run(update, withArgs: args) }
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(insert, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Result<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferResult($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Result<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferResult($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
let timestamp = upstream.serverModified
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Result<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferResult(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferResult(nil)
case 1:
// Great!
return deferResult(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferResult(cursor[0])
}
}
}
private func resolveConflictBetween(#local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(#local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Result<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferResult($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Result<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferResult($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
/**
* Clean up any metadata.
*/
public func onRemovedAccount() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
extension SQLiteLogins {
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
| mpl-2.0 | c3f94dd3497b7cdca9f7acd218fa2058 | 41.306306 | 198 | 0.606287 | 4.806551 | false | false | false | false |
elegion/ios-Flamingo | Source/OfflineCacheManager.swift | 1 | 2622 | //
// OfflineCacheManager.swift
// Flamingo
//
// Created by Nikolay Ischuk on 04.03.2018.
// Copyright © 2018 ELN. All rights reserved.
//
import Foundation
public protocol OfflineCacheProtocol: AnyObject {
func storeCachedResponse(_ cachedResponse: CachedURLResponse, for request: URLRequest)
func cachedResponse(for request: URLRequest) -> CachedURLResponse?
}
extension URLCache: OfflineCacheProtocol {
}
open class OfflineCacheManager: NetworkClientReporter, NetworkClientMutater {
public typealias IsOfflineClosure = () -> Bool
let cache: OfflineCacheProtocol
let storagePolicy: URLCache.StoragePolicy
private let reachability: IsOfflineClosure
unowned let networkClient: NetworkDefaultClient
private var shouldReplaceResponse: Bool {
return reachability()
}
public init(cache: OfflineCacheProtocol,
storagePolicy: URLCache.StoragePolicy = .allowed,
networkClient: NetworkDefaultClient,
reachability: @escaping IsOfflineClosure) {
self.cache = cache
self.storagePolicy = storagePolicy
self.networkClient = networkClient
self.reachability = reachability
}
open func willSendRequest<Request>(_ networkRequest: Request) where Request : NetworkRequest {
}
open func didRecieveResponse<Request>(for request: Request, context: NetworkContext) where Request : NetworkRequest {
do {
if let response = context.response,
let data = context.data {
let urlRequest = try networkClient.urlRequest(from: request)
let cached = CachedURLResponse(response: response,
data: data,
userInfo: nil,
storagePolicy: storagePolicy)
cache.storeCachedResponse(cached, for: urlRequest)
}
} catch {
}
}
open func response<Request>(for request: Request) -> NetworkClientMutater.RawResponseTuple? where Request : NetworkRequest {
do {
let urlRequest = try networkClient.urlRequest(from: request)
if shouldReplaceResponse,
let cached = cache.cachedResponse(for: urlRequest) {
return (cached.data, cached.response, nil)
}
} catch {
}
return nil
}
}
extension NetworkDefaultClient {
public func addOfflineCacheManager(_ manager: OfflineCacheManager) {
addReporter(manager)
addMutater(manager)
}
}
| mit | 3de39ab06592d7c0e2deeeaca722c29d | 30.963415 | 128 | 0.635635 | 5.660907 | false | false | false | false |
edjiang/forward-swift-workshop | SwiftNotesIOS/Pods/Stormpath/Stormpath/Networking/SocialLoginAPIRequestManager.swift | 1 | 2707 | //
// SocialLoginAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 3/3/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
class SocialLoginAPIRequestManager: APIRequestManager {
var socialProvider: StormpathSocialProvider
var callback: AccessTokenCallback
var postDictionary: [String: AnyObject]
init(withURL url: NSURL, accessToken: String, socialProvider: StormpathSocialProvider, callback: AccessTokenCallback) {
self.socialProvider = socialProvider
self.callback = callback
postDictionary = ["providerData": ["providerId": socialProvider.stringValue(), "accessToken": accessToken]]
super.init(withURL: url)
}
init(withURL url: NSURL, authorizationCode: String, socialProvider: StormpathSocialProvider, callback: AccessTokenCallback) {
self.socialProvider = socialProvider
self.callback = callback
postDictionary = ["providerData": ["providerId": socialProvider.stringValue(), "code": authorizationCode]]
super.init(withURL: url)
}
override func prepareForRequest() {
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(postDictionary, options: [])
request.HTTPMethod = "POST"
}
override func requestDidFinish(data: NSData, response: NSHTTPURLResponse) {
// Grab access token from cookies
// Callback
let accessTokenRegex = "(?<=access_token=)[^;]*"
let refreshTokenRegex = "(?<=refresh_token=)[^;]*"
guard let setCookieHeaders = response.allHeaderFields["Set-Cookie"] as? String, accessTokenRange = setCookieHeaders.rangeOfString(accessTokenRegex, options: .RegularExpressionSearch) else {
performCallback(error: StormpathError.APIResponseError)
return
}
let accessToken = setCookieHeaders.substringWithRange(accessTokenRange)
var refreshToken: String?
if let refreshTokenRange = setCookieHeaders.rangeOfString(refreshTokenRegex, options: .RegularExpressionSearch) {
refreshToken = setCookieHeaders.substringWithRange(refreshTokenRange)
}
performCallback(accessToken, refreshToken: refreshToken, error: nil)
}
override func performCallback(error error: NSError?) {
performCallback(nil, refreshToken: nil, error: error)
}
func performCallback(accessToken: String?, refreshToken: String?, error: NSError?) {
dispatch_async(dispatch_get_main_queue()) {
self.callback(accessToken: accessToken, refreshToken: refreshToken, error: error)
}
}
} | apache-2.0 | f2e87c0e8a926f36e510b8111ad7fd9b | 38.231884 | 197 | 0.682188 | 5.412 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Items/Overview/DiscountInfoItem.swift | 1 | 1048 | class DiscountInfoItem: TableItem {
private let searchInfo: HLSearchInfo
private let room: HDKRoom
init(room: HDKRoom, searchInfo: HLSearchInfo) {
self.room = room
self.searchInfo = searchInfo
}
override func cellHeight(tableWidth: CGFloat) -> CGFloat {
let duration = DateUtil.hl_daysBetweenDate(searchInfo.checkInDate, andOtherDate: searchInfo.checkOutDate)
return DiscountCell.preferredHeight(width: tableWidth, room: room, currency: searchInfo.currency, duration: duration)
}
override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DiscountCell.hl_reuseIdentifier(), for: indexPath) as! DiscountCell
let currency = searchInfo.currency
let duration = DateUtil.hl_daysBetweenDate(searchInfo.checkInDate, andOtherDate: searchInfo.checkOutDate)
cell.last = last
cell.configure(for: room, currency: currency, duration: duration)
return cell
}
}
| mit | fb53fe24ef9f4db99886574a3ffc6a83 | 40.92 | 132 | 0.723282 | 4.678571 | false | false | false | false |
gu704823/DYTV | dytv/Pods/LeanCloud/Sources/Storage/Query.swift | 3 | 16145 | //
// Query.swift
// LeanCloud
//
// Created by Tang Tianyong on 4/19/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
Query defines a query for objects.
*/
final public class LCQuery: NSObject, NSCopying, NSCoding {
/// Object class name.
public let objectClassName: String
/// The limit on the number of objects to return.
public var limit: Int?
/// The number of objects to skip before returning.
public var skip: Int?
/// Included keys.
fileprivate var includedKeys: Set<String> = []
/// Selected keys.
fileprivate var selectedKeys: Set<String> = []
/// Equality table.
fileprivate var equalityTable: [String: LCValue] = [:]
/// Equality key-value pairs.
fileprivate var equalityPairs: [[String: LCValue]] {
return equalityTable.map { [$0: $1] }
}
/// Ordered keys.
fileprivate var orderedKeys: String?
/// Dictionary of constraints indexed by key.
/// Note that it may contains LCValue or Query value.
fileprivate var constraintDictionary: [String: AnyObject] = [:]
/// Extra parameters for query request.
var extraParameters: [String: AnyObject]?
/// LCON representation of query.
var lconValue: [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
dictionary["className"] = objectClassName as AnyObject?
if !constraintDictionary.isEmpty {
dictionary["where"] = ObjectProfiler.lconValue(constraintDictionary as AnyObject)
}
if !includedKeys.isEmpty {
dictionary["include"] = includedKeys.joined(separator: ",") as AnyObject?
}
if !selectedKeys.isEmpty {
dictionary["keys"] = selectedKeys.joined(separator: ",") as AnyObject?
}
if let orderedKeys = orderedKeys {
dictionary["order"] = orderedKeys as AnyObject?
}
if let limit = limit {
dictionary["limit"] = limit as AnyObject?
}
if let skip = skip {
dictionary["skip"] = skip as AnyObject?
}
if let extraParameters = extraParameters {
extraParameters.forEach { (key, value) in
dictionary[key] = value
}
}
return dictionary
}
/// Parameters for query request.
fileprivate var parameters: [String: AnyObject] {
var parameters = lconValue
/* Encode where field to string. */
if let object = parameters["where"] {
parameters["where"] = Utility.jsonString(object) as AnyObject
}
return parameters
}
/// The dispatch queue for network request task.
static let backgroundQueue = DispatchQueue(label: "LeanCloud.Query", attributes: .concurrent)
/**
Constraint for key.
*/
public enum Constraint {
case included
case selected
case existed
case notExisted
case equalTo(LCValueConvertible)
case notEqualTo(LCValueConvertible)
case lessThan(LCValueConvertible)
case lessThanOrEqualTo(LCValueConvertible)
case greaterThan(LCValueConvertible)
case greaterThanOrEqualTo(LCValueConvertible)
case containedIn(LCArrayConvertible)
case notContainedIn(LCArrayConvertible)
case containedAllIn(LCArrayConvertible)
case equalToSize(Int)
case locatedNear(LCGeoPoint, minimal: LCGeoPoint.Distance?, maximal: LCGeoPoint.Distance?)
case locatedWithin(southwest: LCGeoPoint, northeast: LCGeoPoint)
case matchedQuery(LCQuery)
case notMatchedQuery(LCQuery)
case matchedQueryAndKey(query: LCQuery, key: String)
case notMatchedQueryAndKey(query: LCQuery, key: String)
case matchedRegularExpression(String, option: String?)
case matchedSubstring(String)
case prefixedBy(String)
case suffixedBy(String)
case relatedTo(LCObject)
case ascending
case descending
}
var endpoint: String {
return RESTClient.endpoint(objectClassName)
}
/**
Construct query with class name.
- parameter objectClassName: The class name to query.
*/
public init(className: String) {
self.objectClassName = className
}
public func copy(with zone: NSZone?) -> Any {
let query = LCQuery(className: objectClassName)
query.includedKeys = includedKeys
query.selectedKeys = selectedKeys
query.equalityTable = equalityTable
query.constraintDictionary = constraintDictionary
query.extraParameters = extraParameters
query.limit = limit
query.skip = skip
return query
}
public required init?(coder aDecoder: NSCoder) {
objectClassName = aDecoder.decodeObject(forKey: "objectClassName") as! String
includedKeys = aDecoder.decodeObject(forKey: "includedKeys") as! Set<String>
selectedKeys = aDecoder.decodeObject(forKey: "selectedKeys") as! Set<String>
equalityTable = aDecoder.decodeObject(forKey: "equalityTable") as! [String: LCValue]
constraintDictionary = aDecoder.decodeObject(forKey: "constraintDictionary") as! [String: AnyObject]
extraParameters = aDecoder.decodeObject(forKey: "extraParameters") as? [String: AnyObject]
limit = aDecoder.decodeObject(forKey: "limit") as? Int
skip = aDecoder.decodeObject(forKey: "skip") as? Int
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(objectClassName, forKey: "objectClassName")
aCoder.encode(includedKeys, forKey: "includedKeys")
aCoder.encode(selectedKeys, forKey: "selectedKeys")
aCoder.encode(equalityTable, forKey: "equalityTable")
aCoder.encode(constraintDictionary, forKey: "constraintDictionary")
if let extraParameters = extraParameters {
aCoder.encode(extraParameters, forKey: "extraParameters")
}
if let limit = limit {
aCoder.encode(limit, forKey: "limit")
}
if let skip = skip {
aCoder.encode(skip, forKey: "skip")
}
}
/**
Add constraint in query.
- parameter constraint: The constraint.
*/
public func whereKey(_ key: String, _ constraint: Constraint) {
var dictionary: [String: AnyObject]?
switch constraint {
/* Key matching. */
case .included:
includedKeys.insert(key)
case .selected:
selectedKeys.insert(key)
case .existed:
dictionary = ["$exists": true as AnyObject]
case .notExisted:
dictionary = ["$exists": false as AnyObject]
/* Equality matching. */
case let .equalTo(value):
equalityTable[key] = value.lcValue
constraintDictionary["$and"] = equalityPairs as AnyObject?
case let .notEqualTo(value):
dictionary = ["$ne": value.lcValue]
case let .lessThan(value):
dictionary = ["$lt": value.lcValue]
case let .lessThanOrEqualTo(value):
dictionary = ["$lte": value.lcValue]
case let .greaterThan(value):
dictionary = ["$gt": value.lcValue]
case let .greaterThanOrEqualTo(value):
dictionary = ["$gte": value.lcValue]
/* Array matching. */
case let .containedIn(array):
dictionary = ["$in": array.lcArray]
case let .notContainedIn(array):
dictionary = ["$nin": array.lcArray]
case let .containedAllIn(array):
dictionary = ["$all": array.lcArray]
case let .equalToSize(size):
dictionary = ["$size": size as AnyObject]
/* Geography point matching. */
case let .locatedNear(center, minimal, maximal):
var value: [String: AnyObject] = ["$nearSphere": center]
if let min = minimal { value["$minDistanceIn\(min.unit.rawValue)"] = min.value as AnyObject }
if let max = maximal { value["$maxDistanceIn\(max.unit.rawValue)"] = max.value as AnyObject }
dictionary = value
case let .locatedWithin(southwest, northeast):
dictionary = ["$within": ["$box": [southwest, northeast]] as AnyObject]
/* Query matching. */
case let .matchedQuery(query):
dictionary = ["$inQuery": query]
case let .notMatchedQuery(query):
dictionary = ["$notInQuery": query]
case let .matchedQueryAndKey(query, key):
dictionary = ["$select": ["query": query, "key": key] as AnyObject]
case let .notMatchedQueryAndKey(query, key):
dictionary = ["$dontSelect": ["query": query, "key": key] as AnyObject]
/* String matching. */
case let .matchedRegularExpression(regex, option):
dictionary = ["$regex": regex as AnyObject, "$options": option as AnyObject? ?? "" as AnyObject]
case let .matchedSubstring(string):
dictionary = ["$regex": "\(string.regularEscapedString)" as AnyObject]
case let .prefixedBy(string):
dictionary = ["$regex": "^\(string.regularEscapedString)" as AnyObject]
case let .suffixedBy(string):
dictionary = ["$regex": "\(string.regularEscapedString)$" as AnyObject]
case let .relatedTo(object):
constraintDictionary["$relatedTo"] = ["object": object, "key": key] as AnyObject
case .ascending:
appendOrderedKey(key)
case .descending:
appendOrderedKey("-\(key)")
}
if let dictionary = dictionary {
addConstraint(key, dictionary)
}
}
/**
Validate query class name.
- parameter query: The query to be validated.
*/
func validateClassName(_ query: LCQuery) throws {
guard query.objectClassName == objectClassName else {
throw LCError(code: .inconsistency, reason: "Different class names.", userInfo: nil)
}
}
/**
Get logic AND of another query.
Note that it only combine constraints of two queries, the limit and skip option will be discarded.
- parameter query: The another query.
- returns: The logic AND of two queries.
*/
public func and(_ query: LCQuery) -> LCQuery {
try! validateClassName(query)
let result = LCQuery(className: objectClassName)
result.constraintDictionary["$and"] = [self.constraintDictionary, query.constraintDictionary] as AnyObject
return result
}
/**
Get logic OR of another query.
Note that it only combine constraints of two queries, the limit and skip option will be discarded.
- parameter query: The another query.
- returns: The logic OR of two queries.
*/
public func or(_ query: LCQuery) -> LCQuery {
try! validateClassName(query)
let result = LCQuery(className: objectClassName)
result.constraintDictionary["$or"] = [self.constraintDictionary, query.constraintDictionary] as AnyObject
return result
}
/**
Append ordered key to ordered keys string.
- parameter orderedKey: The ordered key with optional '-' prefixed.
*/
func appendOrderedKey(_ orderedKey: String) {
orderedKeys = orderedKeys?.appending(orderedKey) ?? orderedKey
}
/**
Add a constraint for key.
- parameter key: The key on which the constraint to be added.
- parameter dictionary: The constraint dictionary for key.
*/
func addConstraint(_ key: String, _ dictionary: [String: AnyObject]) {
constraintDictionary[key] = dictionary as AnyObject?
}
/**
Transform JSON results to objects.
- parameter results: The results return by query.
- returns: An array of LCObject objects.
*/
func processResults<T: LCObject>(_ results: [AnyObject], className: String?) -> [T] {
return results.map { dictionary in
let object = ObjectProfiler.object(className: className ?? self.objectClassName) as! T
if let dictionary = dictionary as? [String: AnyObject] {
ObjectProfiler.updateObject(object, dictionary)
}
return object
}
}
/**
Asynchronize task into background queue.
- parameter task: The task to be performed.
- parameter completion: The completion closure to be called on main thread after task finished.
*/
static func asynchronize<Result>(_ task: @escaping () -> Result, completion: @escaping (Result) -> Void) {
Utility.asynchronize(task, backgroundQueue, completion)
}
/**
Query objects synchronously.
- returns: The result of the query request.
*/
public func find<T: LCObject>() -> LCQueryResult<T> {
let response = RESTClient.request(.get, endpoint, parameters: parameters)
if let error = response.error {
return .failure(error: error)
} else {
let className = response.value?["className"] as? String
let objects: [T] = processResults(response.results, className: className)
return .success(objects: objects)
}
}
/**
Query objects asynchronously.
- parameter completion: The completion callback closure.
*/
public func find<T: LCObject>(_ completion: @escaping (LCQueryResult<T>) -> Void) {
LCQuery.asynchronize({ self.find() }) { result in
completion(result)
}
}
/**
Get first object of query synchronously.
- note: All query conditions other than `limit` will take effect for current request.
- returns: The object result of query.
*/
public func getFirst<T: LCObject>() -> LCObjectResult<T> {
let query = copy() as! LCQuery
query.limit = 1
let result: LCQueryResult<T> = query.find()
switch result {
case let .success(objects):
guard let object = objects.first else {
return .failure(error: LCError(code: .notFound, reason: "Object not found."))
}
return .success(object: object)
case let .failure(error):
return .failure(error: error)
}
}
/**
Get first object of query asynchronously.
- parameter completion: The completion callback closure.
*/
public func getFirst<T: LCObject>(_ completion: @escaping (LCObjectResult<T>) -> Void) {
LCQuery.asynchronize({ self.getFirst() }) { result in
completion(result)
}
}
/**
Get object by object ID synchronously.
- parameter objectId: The object ID.
- returns: The object result of query.
*/
public func get<T: LCObject>(_ objectId: LCStringConvertible) -> LCObjectResult<T> {
let query = copy() as! LCQuery
query.whereKey("objectId", .equalTo(objectId.lcString))
return query.getFirst()
}
/**
Get object by object ID asynchronously.
- parameter objectId: The object ID.
- parameter completion: The completion callback closure.
*/
public func get<T: LCObject>(_ objectId: LCStringConvertible, completion: @escaping (LCObjectResult<T>) -> Void) {
LCQuery.asynchronize({ self.get(objectId) }) { result in
completion(result)
}
}
/**
Count objects synchronously.
- returns: The result of the count request.
*/
public func count() -> LCCountResult {
var parameters = self.parameters
parameters["count"] = 1 as AnyObject?
parameters["limit"] = 0 as AnyObject?
let response = RESTClient.request(.get, endpoint, parameters: parameters)
let result = LCCountResult(response: response)
return result
}
/**
Count objects asynchronously.
- parameter completion: The completion callback closure.
*/
public func count(_ completion: @escaping (LCCountResult) -> Void) {
LCQuery.asynchronize({ self.count() }) { result in
completion(result)
}
}
}
| mit | 7a3a913df4d764408e1cf2583bf075f3 | 31.482897 | 118 | 0.621036 | 4.890639 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Services/Send/Service/SendEmailNotificationService.swift | 1 | 2170 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureAuthenticationDomain
import Foundation
import MoneyKit
import NetworkKit
import ToolKit
public protocol SendEmailNotificationServiceAPI {
func postSendEmailNotificationTrigger(
moneyValue: MoneyValue,
txHash: String
) -> AnyPublisher<Void, Never>
}
public class SendEmailNotificationService: SendEmailNotificationServiceAPI {
private let client: SendEmailNotificationClientAPI
private let credentialsRepository: CredentialsRepositoryAPI
private let errorRecoder: ErrorRecording
init(
client: SendEmailNotificationClientAPI = resolve(),
credentialsRepository: CredentialsRepositoryAPI = resolve(),
errorRecoder: ErrorRecording = resolve()
) {
self.client = client
self.credentialsRepository = credentialsRepository
self.errorRecoder = errorRecoder
}
public func postSendEmailNotificationTrigger(
moneyValue: MoneyValue,
txHash: String
) -> AnyPublisher<Void, Never> {
credentialsRepository.credentials
.ignoreFailure()
.map { guid, sharedKey in
let assetModel = moneyValue.currency.cryptoCurrency?.assetModel
let network = assetModel?.kind.erc20ParentChain?.rawValue ?? moneyValue.code
let amount = moneyValue.toSimpleString(includeSymbol: false)
return SendEmailNotificationClient.Payload(
guid: guid,
sharedKey: sharedKey,
currency: moneyValue.code,
amount: amount,
network: network,
txHash: txHash
)
}
.flatMap { [client] payload in
client.postSendEmailNotificationTrigger(payload)
}
.handleEvents(receiveCompletion: { [errorRecoder] in
if case .failure(let error) = $0 {
errorRecoder.error(error)
}
})
.ignoreFailure()
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | 78b99acb3a1e6f66c7b0419d58042285 | 32.369231 | 92 | 0.629322 | 5.92623 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsComponents/BadgeCellPresenters/PreferredCurrencyCellPresenter.swift | 1 | 2524 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import PlatformUIKit
import RxRelay
import RxSwift
/// A `BadgeCellPresenting` class for showing the user's preferred local currency
final class PreferredCurrencyCellPresenter: BadgeCellPresenting {
private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell
// MARK: - Properties
let accessibility: Accessibility = .id(AccessibilityId.Currency.title)
let labelContentPresenting: LabelContentPresenting
let badgeAssetPresenting: BadgeAssetPresenting
var isLoading: Bool {
isLoadingRelay.value
}
// MARK: - Private Properties
private let isLoadingRelay = BehaviorRelay<Bool>(value: true)
private let disposeBag = DisposeBag()
// MARK: - Setup
init(interactor: PreferredCurrencyBadgeInteractor) {
labelContentPresenting = DefaultLabelContentPresenter(
knownValue: LocalizationConstants.Settings.Badge.walletDisplayCurrency,
descriptors: .settings
)
badgeAssetPresenting = PreferredCurrencyBadgePresenter(
interactor: interactor
)
badgeAssetPresenting.state
.map(\.isLoading)
.bindAndCatch(to: isLoadingRelay)
.disposed(by: disposeBag)
}
}
/// A `BadgeCellPresenting` class for showing the user's preferred local currency
final class PreferredTradingCurrencyCellPresenter: BadgeCellPresenting {
private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell
// MARK: - Properties
let accessibility: Accessibility = .id(AccessibilityId.Currency.title)
let labelContentPresenting: LabelContentPresenting
let badgeAssetPresenting: BadgeAssetPresenting
var isLoading: Bool {
isLoadingRelay.value
}
// MARK: - Private Properties
private let isLoadingRelay = BehaviorRelay<Bool>(value: true)
private let disposeBag = DisposeBag()
// MARK: - Setup
init(interactor: PreferredTradingCurrencyBadgeInteractor) {
labelContentPresenting = DefaultLabelContentPresenter(
knownValue: LocalizationConstants.Settings.Badge.tradingCurrency,
descriptors: .settings
)
badgeAssetPresenting = PreferredCurrencyBadgePresenter(
interactor: interactor
)
badgeAssetPresenting.state
.map(\.isLoading)
.bindAndCatch(to: isLoadingRelay)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | b72270dc512fc5cee52a3b06c4dd3a30 | 30.5375 | 86 | 0.714625 | 5.773455 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/BezierCurveStylerWidth.swift | 1 | 1355 | //
// BezierCurveStylerWidth.swift
// DNMView
//
// Created by James Bean on 11/6/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class BezierCurveStylerWidth: BezierCurveStyler {
public var width: CGFloat = 2
public required init(styledBezierCurve: StyledBezierCurve) {
super.init(styledBezierCurve: styledBezierCurve)
addWidth()
}
public init(styledBezierCurve: StyledBezierCurve, width: CGFloat) {
super.init(styledBezierCurve: styledBezierCurve)
self.width = width
addWidth()
}
private func addWidth() {
let newPath: BezierPath = BezierPath()
let c = carrierCurve
// upper curve
let left_upper = CGPoint(x: c.p1.x, y: c.p1.y - 0.5 * width)
let right_upper = CGPoint(x: c.p2.x, y: c.p2.y - 0.5 * width)
let upperCurve = BezierCurveLinear(point1: left_upper, point2: right_upper)
newPath.addCurve(upperCurve)
// lower curve
let right_lower = CGPoint(x: c.p2.x, y: c.p2.y + 0.5 * width)
let left_lower = CGPoint(x: c.p1.x, y: c.p1.y + 0.5 * width)
let lowerCurve = BezierCurveLinear(point1: right_lower, point2: left_lower)
newPath.addCurve(lowerCurve)
bezierPath = newPath
}
}
| gpl-2.0 | 5f2e8dcccc2406a84f542703cb68a189 | 28.434783 | 83 | 0.609306 | 3.709589 | false | false | false | false |
durbrow/ThePerfectAligner | ThePerfectAligner/DNABase.swift | 1 | 7975 | //
// DNABase.swift
// ThePerfectAligner
//
// Created by Kenneth Durbrow on 12/14/15.
// Copyright © 2015 Kenneth Durbrow. All rights reserved.
//
import Foundation
private func random4() -> UInt8
{
return UInt8(Darwin.random() % 4)
}
enum DNABase : UInt8 {
case N = 0
case A
case C
case G
case T
init(Character ch: Character)
{
switch ch {
case "A", "a":
self = .A
case "C", "c":
self = .C
case "G", "g":
self = .G
case "T", "t":
self = .T
default:
self = .N
}
}
}
extension DNABase {
static func random() -> DNABase
{
return DNABase(rawValue: random4() + 1)!
}
}
extension DNABase : CustomStringConvertible {
var description : String {
get {
let tr = ["N", "A", "C", "G", "T"]
return tr[Int(rawValue)]
}
}
}
struct DNASequence {
let data : [DNABase]
let defline : String
private init(rawData src: NSData, defline: String)
{
let wsset = NSCharacterSet.whitespaceAndNewlineCharacterSet()
var data = [DNABase]()
src.enumerateByteRangesUsingBlock { (b, r, S) -> Void in
let cdata = UnsafePointer<Int8>(b)
for i in 0..<r.length {
let chi = cdata[i];
if wsset.characterIsMember(UInt16(chi)) {
continue
}
data.append(DNABase(Character: Character(UnicodeScalar(Int(chi)))))
}
}
self.data = data
self.defline = defline
}
init(data: [DNABase], defline: String)
{
self.data = data
self.defline = defline
}
init<S: SequenceType where S.Generator.Element == DNABase>(s: S, defline: String)
{
self.data = [DNABase](s)
self.defline = defline
}
init<S: SequenceType where S.Generator.Element == Character>(s: S, defline: String)
{
self.data = s.map { DNABase(Character: $0) }
self.defline = defline
}
}
extension DNASequence {
static func randomSequence(length: Int) -> [DNABase]
{
assert(length > 0)
var rslt = (0..<length).map { DNABase(rawValue: UInt8($0 % 4) + 1)! }
srandomdev()
for i in 0..<length {
let j = random() % length
(rslt[j], rslt[i]) = (rslt[i], rslt[j])
}
return rslt
}
static func repeatedSequence(count: Int, subSequence: String) -> [DNABase]
{
guard count > 0 && subSequence != "" else { return [] }
let seq = subSequence.characters.map { DNABase(Character: $0) }
guard seq.count > 1 else { return [DNABase](count: count, repeatedValue: seq[0]) }
var rslt = [DNABase]()
rslt.reserveCapacity(count * seq.count)
for _ in 0 ..< count {
rslt.appendContentsOf(seq)
}
return rslt
}
}
extension DNASequence {
static func load<S: SequenceType where S.Generator.Element == UInt8>(Fasta src: S) -> [DNASequence]
{
var result : [DNASequence] = []
var lineno = 1
var st = 0
var ws = true
var defline = ""
var accum = [DNABase]()
for u in src {
let ch = ASCII(rawValue: u)!
if ch == .LF { lineno += 1 }
if ws && ch.isSpace { continue }
ws = false
switch st {
case 0:
if ch != ">" {
st = -1
}
else {
st = 1
}
case 1:
if ch == .LF {
st = 2
}
else {
defline.append(ch.characterValue)
}
case 2:
if ch == .LF {
st = 3
}
else {
accum.append(DNABase(rawValue: DNABase.RawValue(ch.rawValue))!)
}
case 3:
if ch == ">" {
result.append(DNASequence(data: accum, defline: defline))
}
default:
break
}
if st < 0 { return [] }
}
return result
}
static func load(contentsOfFile path: String) throws -> [DNASequence]
{
enum State {
case start
case deflineStart
case defline
case sequenceStart
case sequence
case sequenceEnd
case invalid
}
var result : [DNASequence] = []
let src = try NSData(contentsOfFile: path, options: [.DataReadingMappedIfSafe])
var part = [Int]()
var invalid = -1
var ws = true
let wsset = NSCharacterSet.whitespaceAndNewlineCharacterSet()
var st = State.start
var lineno = 1
src.enumerateByteRangesUsingBlock { (data, range, STOP) -> Void in
let cdata = UnsafePointer<Int8>(data)
for i in 0..<range.length {
let chi = cdata[i]
let ch = Character(UnicodeScalar(Int(chi)))
if ch == "\n" { lineno += 1 }
if wsset.characterIsMember(UInt16(chi)) && ws {
continue
}
ws = false
switch st {
case .start:
if ch != ">" {
st = .invalid
}
else {
ws = true
st = .deflineStart
}
case .deflineStart:
part.append(range.location + i)
st = .defline
case .defline:
if ch == "\n" {
st = .sequenceStart
ws = true
}
case .sequenceStart:
part.append(range.location + i)
st = .sequence
case .sequence:
switch ch {
case "\n":
ws = true
st = .sequenceEnd
case "A", "C", "G", "T", "a", "c", "g", "t", "N":
break
default:
st = .invalid
}
case .sequenceEnd:
if ch == ">" {
ws = true
st = .deflineStart
}
else {
st = .sequence
}
case .invalid:
assertionFailure()
}
if st == .invalid {
invalid = lineno + 1
STOP[0] = true
break
}
}
}
if invalid >= 0 {
assertionFailure("Invalid FASTA at line \(invalid)")
}
if part.count > 0 && part.count % 2 == 0 {
let N = part.count / 2
part.append(src.length)
for i in 0..<N {
let p = part[2 * i ... 2 * i + 2]
let defline = NSString(data: src.subdataWithRange(NSMakeRange(p[0] + 1, p[1] - p[0] - 2)),
encoding: NSASCIIStringEncoding)!
result.append(DNASequence(rawData: src.subdataWithRange(NSMakeRange(p[1], p[2] - p[1])),
defline: defline as String))
}
}
return result
}
}
extension DNASequence : CollectionType {
typealias Element = DNABase
var startIndex: Int {
get { return 0 }
}
var endIndex: Int {
get { return data.count }
}
subscript (index: Int) -> DNABase {
return data[index]
}
}
| mit | 775fbf6a10afc54db24d7cb75305af08 | 27.176678 | 106 | 0.4309 | 4.712766 | false | false | false | false |
kstaring/swift | test/DebugInfo/conditional-assign.swift | 7 | 871 | // RUN: %target-swift-frontend %s -emit-sil -g -o - | %FileCheck %s
public protocol DelegateA {}
public protocol DelegateB {}
public protocol WithDelegate
{
var delegate: DelegateA? { get }
func f() throws -> Int
}
public enum Err: Swift.Error {
case s(Int)
}
public class C {}
public class M {
let field: C
var value : Int
// Verify that definite initialization doesn't create a bogus description of
// self pointing to the liveness bitvector.
// CHECK: sil @_TFC4main1McfzT4fromPS_12WithDelegate__S0_
// CHECK: bb0
// CHECK-NEXT: %2 = alloc_stack $Builtin.Int2
// CHECK-NOT: let
// CHECK-NOT: name
// CHECK: scope
public init(from d: WithDelegate) throws {
guard let delegate = d.delegate as? DelegateB
else { throw Err.s(0) }
self.field = C()
let i: Int = try d.f()
value = i
}
}
| apache-2.0 | 653e49594a160a7aac16a279c9b5b429 | 26.21875 | 78 | 0.632606 | 3.456349 | false | false | false | false |
alblue/swift-corelibs-foundation | TestFoundation/TestNSKeyedArchiver.swift | 2 | 13167 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public class NSUserClass : NSObject, NSSecureCoding {
var ivar : Int
public class var supportsSecureCoding: Bool {
return true
}
public func encode(with aCoder : NSCoder) {
aCoder.encode(ivar, forKey:"$ivar") // also test escaping
}
init(_ value: Int) {
self.ivar = value
}
public required init?(coder aDecoder: NSCoder) {
self.ivar = aDecoder.decodeInteger(forKey: "$ivar")
}
public override var description: String {
get {
return "NSUserClass \(ivar)"
}
}
public override func isEqual(_ object: Any?) -> Bool {
if let custom = object as? NSUserClass {
return self.ivar == custom.ivar
} else {
return false
}
}
}
public class UserClass : NSObject, NSSecureCoding {
var ivar : Int
public class var supportsSecureCoding: Bool {
return true
}
public func encode(with aCoder : NSCoder) {
aCoder.encode(ivar, forKey:"$ivar") // also test escaping
}
init(_ value: Int) {
self.ivar = value
super.init()
}
public required init?(coder aDecoder: NSCoder) {
self.ivar = aDecoder.decodeInteger(forKey: "$ivar")
super.init()
}
public override var description: String {
get {
return "UserClass \(ivar)"
}
}
public override func isEqual(_ other: Any?) -> Bool {
guard let other = other as? UserClass else {
return false
}
return ivar == other.ivar
}
}
class TestNSKeyedArchiver : XCTestCase {
static var allTests: [(String, (TestNSKeyedArchiver) -> () throws -> Void)] {
return [
("test_archive_array", test_archive_array),
("test_archive_charptr", test_archive_charptr),
("test_archive_concrete_value", test_archive_concrete_value),
("test_archive_dictionary", test_archive_dictionary),
("test_archive_generic_objc", test_archive_generic_objc),
("test_archive_locale", test_archive_locale),
("test_archive_string", test_archive_string),
("test_archive_mutable_array", test_archive_mutable_array),
("test_archive_mutable_dictionary", test_archive_mutable_dictionary),
("test_archive_ns_user_class", test_archive_ns_user_class),
("test_archive_nspoint", test_archive_nspoint),
("test_archive_nsrange", test_archive_nsrange),
("test_archive_nsrect", test_archive_nsrect),
("test_archive_null", test_archive_null),
("test_archive_set", test_archive_set),
("test_archive_url", test_archive_url),
("test_archive_user_class", test_archive_user_class),
("test_archive_uuid_bvref", test_archive_uuid_byref),
("test_archive_uuid_byvalue", test_archive_uuid_byvalue),
("test_archive_unhashable", test_archive_unhashable),
("test_archiveRootObject_String", test_archiveRootObject_String),
("test_archiveRootObject_URLRequest()", test_archiveRootObject_URLRequest),
]
}
private func test_archive(_ encode: (NSKeyedArchiver) -> Bool,
decode: (NSKeyedUnarchiver) -> Bool) {
// Archiving using custom NSMutableData instance
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
XCTAssertTrue(encode(archiver))
archiver.finishEncoding()
let unarchiver = NSKeyedUnarchiver(forReadingWith: Data._unconditionallyBridgeFromObjectiveC(data))
XCTAssertTrue(decode(unarchiver))
// Archiving using the default initializer
let archiver1 = NSKeyedArchiver()
XCTAssertTrue(encode(archiver1))
let archivedData = archiver1.encodedData
let unarchiver1 = NSKeyedUnarchiver(forReadingWith: archivedData)
XCTAssertTrue(decode(unarchiver1))
}
private func test_archive(_ object: Any, classes: [AnyClass], allowsSecureCoding: Bool = true, outputFormat: PropertyListSerialization.PropertyListFormat) {
test_archive({ archiver -> Bool in
archiver.requiresSecureCoding = allowsSecureCoding
archiver.outputFormat = outputFormat
archiver.encode(object, forKey: NSKeyedArchiveRootObjectKey)
archiver.finishEncoding()
return true
},
decode: { unarchiver -> Bool in
unarchiver.requiresSecureCoding = allowsSecureCoding
do {
guard let rootObj = try unarchiver.decodeTopLevelObject(of: classes, forKey: NSKeyedArchiveRootObjectKey) else {
XCTFail("Unable to decode data")
return false
}
XCTAssertEqual(object as? AnyHashable, rootObj as? AnyHashable, "unarchived object \(rootObj) does not match \(object)")
} catch {
XCTFail("Error thrown: \(error)")
}
return true
})
}
private func test_archive(_ object: Any, classes: [AnyClass], allowsSecureCoding: Bool = true) {
// test both XML and binary encodings
test_archive(object, classes: classes, allowsSecureCoding: allowsSecureCoding, outputFormat: .xml)
test_archive(object, classes: classes, allowsSecureCoding: allowsSecureCoding, outputFormat: .binary)
}
private func test_archive(_ object: AnyObject, allowsSecureCoding: Bool = true) {
return test_archive(object, classes: [type(of: object)], allowsSecureCoding: allowsSecureCoding)
}
func test_archive_array() {
let array = NSArray(array: ["one", "two", "three"])
test_archive(array)
}
func test_archive_concrete_value() {
let array: Array<UInt64> = [12341234123, 23452345234, 23475982345, 9893563243, 13469816598]
let objctype = "[5Q]"
array.withUnsafeBufferPointer { cArray in
let concrete = NSValue(bytes: cArray.baseAddress!, objCType: objctype)
test_archive(concrete)
}
}
func test_archive_dictionary() {
let dictionary = NSDictionary(dictionary: ["one" : 1, "two" : 2, "three" : 3])
test_archive(dictionary)
}
func test_archive_generic_objc() {
let array: Array<Int32> = [1234, 2345, 3456, 10000]
test_archive({ archiver -> Bool in
array.withUnsafeBufferPointer { cArray in
archiver.encodeValue(ofObjCType: "[4i]", at: cArray.baseAddress!)
}
return true
},
decode: {unarchiver -> Bool in
var expected: Array<Int32> = [0, 0, 0, 0]
expected.withUnsafeMutableBufferPointer {(p: inout UnsafeMutableBufferPointer<Int32>) in
unarchiver.decodeValue(ofObjCType: "[4i]", at: UnsafeMutableRawPointer(p.baseAddress!))
}
XCTAssertEqual(expected, array)
return true
})
}
func test_archive_locale() {
let locale = Locale.current
test_archive(locale._bridgeToObjectiveC())
}
func test_archive_string() {
let string = NSString(string: "hello")
test_archive(string)
}
func test_archive_mutable_array() {
let array = NSMutableArray(array: ["one", "two", "three"])
test_archive(array)
}
func test_archive_mutable_dictionary() {
let one: NSNumber = NSNumber(value: Int(1))
let two: NSNumber = NSNumber(value: Int(2))
let three: NSNumber = NSNumber(value: Int(3))
let dict: [String : Any] = [
"one": one,
"two": two,
"three": three,
]
let mdictionary = NSMutableDictionary(dictionary: dict)
test_archive(mdictionary)
}
func test_archive_nspoint() {
let point = NSValue(point: NSPoint(x: CGFloat(20.0), y: CGFloat(35.0)))
test_archive(point)
}
func test_archive_nsrange() {
let range = NSValue(range: NSRange(location: 1234, length: 5678))
test_archive(range)
}
func test_archive_nsrect() {
let point = NSPoint(x: CGFloat(20.0), y: CGFloat(35.4))
let size = NSSize(width: CGFloat(50.0), height: CGFloat(155.0))
let rect = NSValue(rect: NSRect(origin: point, size: size))
test_archive(rect)
}
func test_archive_null() {
let null = NSNull()
test_archive(null)
}
func test_archive_set() {
let set = NSSet(array: [NSNumber(value: Int(1234234)),
NSNumber(value: Int(2374853)),
NSString(string: "foobarbarbar"),
NSValue(point: NSPoint(x: CGFloat(5.0), y: CGFloat(Double(1.5))))])
test_archive(set, classes: [NSValue.self, NSSet.self])
}
func test_archive_url() {
let url = NSURL(string: "index.html", relativeTo: URL(string: "http://www.apple.com"))!
test_archive(url)
}
func test_archive_charptr() {
let charArray = [CChar]("Hello world, we are testing!\0".utf8CString)
var charPtr = UnsafeMutablePointer(mutating: charArray)
test_archive({ archiver -> Bool in
let value = NSValue(bytes: &charPtr, objCType: "*")
archiver.encode(value, forKey: "root")
return true
},
decode: {unarchiver -> Bool in
guard let value = unarchiver.decodeObject(of: NSValue.self, forKey: "root") else {
return false
}
var expectedCharPtr: UnsafeMutablePointer<CChar>? = nil
value.getValue(&expectedCharPtr)
let s1 = String(cString: charPtr)
let s2 = String(cString: expectedCharPtr!)
#if !DEPLOYMENT_RUNTIME_OBJC
// On Darwin decoded strings would belong to the autorelease pool, but as we don't have
// one in SwiftFoundation let's explicitly deallocate it here.
expectedCharPtr!.deallocate()
#endif
return s1 == s2
})
}
func test_archive_user_class() {
#if !DARWIN_COMPATIBILITY_TESTS // Causes SIGABRT
let userClass = UserClass(1234)
test_archive(userClass)
#endif
}
func test_archive_ns_user_class() {
let nsUserClass = NSUserClass(5678)
test_archive(nsUserClass)
}
func test_archive_uuid_byref() {
let uuid = NSUUID()
test_archive(uuid)
}
func test_archive_uuid_byvalue() {
let uuid = UUID()
return test_archive(uuid, classes: [NSUUID.self])
}
func test_archive_unhashable() {
let data = """
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Accept-Language": "en",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "TestFoundation (unknown version) curl/7.54.0"
},
"origin": "0.0.0.0",
"url": "https://httpbin.org/get"
}
""".data(using: .utf8)!
do {
let json = try JSONSerialization.jsonObject(with: data)
_ = NSKeyedArchiver.archivedData(withRootObject: json)
XCTAssert(true, "NSKeyedArchiver.archivedData handles unhashable")
}
catch {
XCTFail("test_archive_unhashable, de-serialization error \(error)")
}
}
func test_archiveRootObject_String() {
let filePath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
let result = NSKeyedArchiver.archiveRootObject("Hello", toFile: filePath)
XCTAssertTrue(result)
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
XCTFail("Failed to clean up file")
}
}
func test_archiveRootObject_URLRequest() {
let filePath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
let url = URL(string: "http://swift.org")!
let request = URLRequest(url: url)._bridgeToObjectiveC()
let result = NSKeyedArchiver.archiveRootObject(request, toFile: filePath)
XCTAssertTrue(result)
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
XCTFail("Failed to clean up file")
}
}
}
| apache-2.0 | 7c0dfc625af61f50b63a81b6c1f65833 | 34.779891 | 160 | 0.577201 | 4.670805 | false | true | false | false |
Jakobeha/lAzR4t | lAzR4t Shared/Code/Mode/AddTurretTurnMode/PlaceTurretMode.swift | 1 | 4410 | //
// PlaceTurretMode.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import EventKit
class PlaceTurretMode: Mode {
private let turretGrid: GridController<TurretElem>
private let getNextMode: (TurretElemController) -> Mode?
private let placeholder: TurretElemController
init(playerDirection: PlayerDirection,
turretGrid: GridController<TurretElem>,
next getNextMode: @escaping (TurretElemController) -> Mode?) {
self.turretGrid = turretGrid
self.getNextMode = getNextMode
self.placeholder = TurretElemController(curModel: TurretElem.placeholder(playerDirection: playerDirection))
}
func bringPlaceholder(to newPos: CellPos) {
if posAvailable(newPos) {
if !turretGrid.curElems.contains(placeholder) {
turretGrid.add(elem: placeholder)
}
placeholder.pos = newPos
} else {
removePlaceholder()
}
}
func posAvailable(_ newPos: CellPos) -> Bool {
return
turretGrid.curModel.bounds.contains(center: newPos) &&
!turretGrid.curModel.elems.contains { $0.pos == newPos && !$0.isPlaceholder }
}
func tryPlacePlaceholder(at newPos: CellPos) -> Bool {
if posAvailable(newPos) {
if !turretGrid.curElems.contains(placeholder) {
turretGrid.add(elem: placeholder)
}
placeholder.pos = newPos
return true
} else {
removePlaceholder()
return false
}
}
func removePlaceholder() {
if (turretGrid.curElems.contains(placeholder)) {
try! turretGrid.removeOne(elem: placeholder)
}
}
func update(gameTime: TimeInterval, in rootGrid: GridController<Elem>) -> [Mode] {
return [self]
}
#if os(iOS) || os(tvOS)
// Touch-based event handling
///Returns the modes which will replace this one for future events.
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
bringPlaceholder(to: newPos)
return [self]
}
///Returns the modes which will replace this one for future events.
func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
bringPlaceholder(to: newPos)
return [self]
}
///Returns the modes which will replace this one for future events.
func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
if tryPlacePlaceholder(at: newPos) {
placeholder.isPlaceholder = false
let nextMode = getNextMode(placeholder)
return nextMode.toArray
} else {
return [self]
}
}
///Returns the modes which will replace this one for future events.
func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?, in rootGrid: GridController<Elem>) -> [Mode] {
removePlaceholder()
return [self]
}
#endif
#if os(OSX)
// Mouse-based event handling
///Returns the modes which will replace this one for future events.
func mouseDown(with event: NSEvent, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
bringPlaceholder(to: newPos)
return [self]
}
///Returns the modes which will replace this one for future events.
func mouseDragged(with event: NSEvent, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
bringPlaceholder(to: newPos)
return [self]
}
///Returns the modes which will replace this one for future events.
func mouseUp(with event: NSEvent, in rootGrid: GridController<Elem>) -> [Mode] {
let newPos = event.location(in: turretGrid)
if tryPlacePlaceholder(at: newPos) {
placeholder.isPlaceholder = false
let nextMode = getNextMode(placeholder)
return nextMode.toArray
} else {
return [self]
}
}
#endif
}
| mit | 6bf62de98fe2ba78df7bc987ad5b78e5 | 35.139344 | 119 | 0.625085 | 4.587929 | false | false | false | false |
0x73/GoogleWearAlert | GoogleWearAlert/GoogleWearAlertView/GoogleWearAlertView.swift | 3 | 7669 | //
// GoogleWearAlertView.swift
// GoogleWearAlertView
//
// Created by Ashley Robinson on 27/06/2014.
// Copyright (c) 2014 Ashley Robinson. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
class func successGreen() -> UIColor {
return UIColor(red: 69.0/255.0, green: 181.0/255.0, blue: 38.0/255.0, alpha: 1)
}
class func errorRed() -> UIColor {
return UIColor(red: 255.0/255.0, green: 82.0/255.0, blue: 82.0/255.0, alpha: 1)
}
class func warningYellow() -> UIColor {
return UIColor(red: 255.0/255.0, green: 205.0/255.0, blue: 64.0/255.0, alpha: 1)
}
class func messageBlue() -> UIColor {
return UIColor(red: 2.0/255.0, green: 169.0/255.0, blue: 244.0/255.0, alpha: 1)
}
}
class GoogleWearAlertView: UIView, UIGestureRecognizerDelegate {
//Constants
let alertViewSize:CGFloat = 0.4 // 40% of presenting viewcontrollers width
let imageViewSize:CGFloat = 0.4 //4 0% of AlertViews width
let imageViewOffsetFromCentre:CGFloat = 0.25 // Offset of image along Y axis
let titleLabelWidth:CGFloat = 0.7 // 70% of AlertViews width
let titleLabelHeight:CGFloat = 30
let navControllerHeight:CGFloat = 44
/** The displayed title of this message */
var title:NSString?
/** The view controller this message is displayed in, only used to size the alert*/
var viewController:UIViewController!
/** The duration of the displayed message. If it is 0.0, it will automatically be calculated */
var duration:Double?
/** The position of the message (top or bottom) */
var alertPosition:GoogleWearAlertPosition?
/** Is the message currenlty fully displayed? Is set as soon as the message is really fully visible */
var messageIsFullyDisplayed:Bool?
/** If you'd like to customise the image shown with the alert */
var iconImage:UIImage?
/** Internal properties needed to resize the view on device rotation properly */
lazy var titleLabel: UILabel = UILabel()
lazy var iconImageView: UIImageView = UIImageView()
/** Inits the notification view. Do not call this from outside this library.
@param title The text of the notification view
@param image A custom icon image (optional)
@param notificationType The type (color) of the notification view
@param duration The duration this notification should be displayed (optional)
@param viewController the view controller this message should be displayed in
@param position The position of the message on the screen
@param dismissingEnabled Should this message be dismissed when the user taps it?
*/
init(title:String, image:UIImage?, type:GoogleWearAlertType, duration:Double, viewController:UIViewController, position:GoogleWearAlertPosition, canbeDismissedByUser:Bool) {
super.init(frame: CGRectZero)
self.title = title
self.iconImage = image
self.duration = duration
self.viewController = viewController
self.alertPosition = position
// Setup background color and choose icon
var imageProvided = image != nil
switch type {
case .Error:
backgroundColor = UIColor.errorRed()
if !imageProvided { self.iconImage = UIImage(named: "errorIcon") }
case .Message:
backgroundColor = UIColor.messageBlue()
if !imageProvided { self.iconImage = UIImage(named: "messageIcon") }
case .Success:
backgroundColor = UIColor.successGreen()
if !imageProvided { self.iconImage = UIImage(named: "successIcon") }
case .Warning:
backgroundColor = UIColor.warningYellow()
if !imageProvided { self.iconImage = UIImage(named: "warningIcon") }
default:
NSLog("Unknown message type provided")
}
// Setup self
setTranslatesAutoresizingMaskIntoConstraints(false)
frame.size = CGSizeMake(viewController.view.bounds.size.width * alertViewSize, viewController.view.bounds.width * alertViewSize)
layer.cornerRadius = self.frame.width/2
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 0)
self.layer.shadowOpacity = 0.8
self.clipsToBounds = false
// Setup Image View
iconImageView.image = iconImage
iconImageView.frame = CGRectMake(0, 0, frame.size.width * imageViewSize, frame.size.width * imageViewSize)
iconImageView.center = center
iconImageView.center.y -= iconImageView.frame.size.height * imageViewOffsetFromCentre
self.addSubview(iconImageView)
// Setup Text Label
titleLabel.text = title
titleLabel.frame = CGRectMake(self.center.x - (frame.size.width * titleLabelWidth) / 2, iconImageView.frame.origin.y + iconImageView.frame.size.height - 5, frame.size.width * titleLabelWidth, titleLabelHeight)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.font = UIFont.systemFontOfSize(18)
self.addSubview(titleLabel)
//Position the alert
positionAlertForPosition(position)
if canbeDismissedByUser {
let tagGestureRecognizer = UITapGestureRecognizer(target:self, action: Selector("dismissAlert"))
self.addGestureRecognizer(tagGestureRecognizer)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSException(name: "init from storyboard error", reason: "alert cannot be initalized from a storybaord", userInfo: nil).raise()
}
func dismissAlert() {
GoogleWearAlert.sharedInstance.removeCurrentAlert(self)
}
func insideNavController() -> Bool {
if let vc = viewController {
if vc.parentViewController is UINavigationController {
return true
} else if vc is UINavigationController {
return true
}
}
return false
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection!) {
layoutSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
if let position = alertPosition {
positionAlertForPosition(position)
}
}
func positionAlertForPosition(position:GoogleWearAlertPosition) {
if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
var centerX = viewController.view.bounds.width/2
var centerY = viewController.view.bounds.height/2
center = CGPointMake(centerX, centerY)
} else {
switch position {
case .Top:
center = CGPointMake(viewController.view.center.x, viewController.view.frame.size.height / 4)
if insideNavController() { center.y += navControllerHeight }
case .Center:
center = viewController.view.center
case .Bottom:
center = CGPointMake(viewController.view.center.x, viewController.view.frame.size.height * 0.75)
default:
NSLog("Unknown position type provided")
}
}
}
} | mit | c425c80b74924c47e10b07c0c7759953 | 38.132653 | 217 | 0.635285 | 5.022266 | false | false | false | false |
hoangdang1449/Spendy | Spendy/HomeViewController.swift | 1 | 17979 | //
// HomeViewController.swift
// Spendy
//
// Created by Dave Vo on 9/16/15.
// Copyright (c) 2015 Cheetah. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var statusBarView: UIView!
@IBOutlet weak var currentBarView: UIView!
@IBOutlet weak var currentBarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var todayLabel: UILabel!
@IBOutlet weak var popupSuperView: UIView!
// View Mode
@IBOutlet weak var viewModePopup: UIView!
@IBOutlet weak var viewModeTitleLabel: UILabel!
@IBOutlet weak var viewModeTableView: UITableView!
// Select Date
@IBOutlet weak var datePopup: UIView!
@IBOutlet weak var dateTitleLabel: UILabel!
@IBOutlet weak var fromButton: UIButton!
@IBOutlet weak var toButton: UIButton!
var formatter: NSDateFormatter!
let dayCountInMonth = 30
var incomes = [String]()
var expenses = [String]()
var isCollapedIncome = true
var isCollapedExpense = true
var viewMode = ViewMode.Monthly
var weekOfYear = 0
override func viewDidLoad() {
super.viewDidLoad()
settingStatusBar()
navigationItem.title = getTodayString("MMMM")
let tapTitle = UITapGestureRecognizer(target: self, action: Selector("chooseMode:"))
navigationController?.navigationBar.addGestureRecognizer(tapTitle)
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
leftSwipe.direction = .Left
leftSwipe.delegate = self
tableView.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
rightSwipe.direction = .Right
rightSwipe.delegate = self
tableView.addGestureRecognizer(rightSwipe)
let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
downSwipe.direction = .Down
downSwipe.delegate = self
tableView.addGestureRecognizer(downSwipe)
viewModeTableView.dataSource = self
viewModeTableView.delegate = self
viewModeTableView.tableFooterView = UIView()
incomes = ["Salary", "Bonus"]
expenses = ["Meal", "Drink", "Transport"]
configPopup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: View mode
func settingStatusBar() {
currentBarView.layer.cornerRadius = 6
currentBarView.layer.masksToBounds = true
statusBarView.layer.cornerRadius = 6
statusBarView.layer.masksToBounds = true
todayLabel.text = getTodayString("MMMM dd, yyyy")
let day = NSCalendar.currentCalendar().component(NSCalendarUnit.NSDayCalendarUnit, fromDate: NSDate())
var ratio = CGFloat(day) / CGFloat(dayCountInMonth)
ratio = ratio > 1 ? 1 : ratio
currentBarWidthConstraint.constant = ratio * statusBarView.frame.width
}
func chooseMode(sender: UITapGestureRecognizer) {
print("tap title", terminator: "\n")
showPopup(viewModePopup)
}
func getWeekText(weekOfYear: Int) -> String {
var result = "Weekly"
var (beginWeek, endWeek) = Helper.sharedInstance.getWeek(weekOfYear)
if beginWeek != nil && endWeek != nil {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd MMM"
result = formatter.stringFromDate(beginWeek!) + " - " + formatter.stringFromDate(endWeek!)
}
return result
}
func getTodayString(dateFormat: String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
return formatter.stringFromDate(NSDate())
}
func configPopup() {
formatter = NSDateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
popupSuperView.hidden = true
popupSuperView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.5)
viewModePopup.layer.cornerRadius = 5
viewModePopup.layer.masksToBounds = true
viewModeTitleLabel.backgroundColor = UIColor(netHex: 0x4682B4)
viewModeTitleLabel.textColor = UIColor.whiteColor()
datePopup.layer.cornerRadius = 5
datePopup.layer.masksToBounds = true
dateTitleLabel.backgroundColor = UIColor(netHex: 0x4682B4)
dateTitleLabel.textColor = UIColor.whiteColor()
let today = NSDate()
fromButton.setTitle(formatter.stringFromDate(today), forState: UIControlState.Normal)
toButton.setTitle(formatter.stringFromDate(today), forState: UIControlState.Normal)
}
// MARK: Button
@IBAction func onFromButton(sender: UIButton) {
let defaultDate = formatter.dateFromString((sender.titleLabel?.text)!)
DatePickerDialog().show(title: "From Date", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", defaultDate: defaultDate!, minDate: nil, datePickerMode: .Date) {
(date) -> Void in
print(date, terminator: "\n")
let dateString = self.formatter.stringFromDate(date)
print("formated: \(dateString)", terminator: "\n")
sender.setTitle(dateString, forState: UIControlState.Normal)
let currentToDate = self.formatter.dateFromString((self.toButton.titleLabel?.text)!)
if currentToDate < date {
self.toButton.setTitle(self.formatter.stringFromDate(date), forState: UIControlState.Normal)
}
}
}
@IBAction func onToButton(sender: UIButton) {
let defaultDate = formatter.dateFromString((sender.titleLabel?.text)!)
let minDate = formatter.dateFromString((fromButton.titleLabel?.text)!)
DatePickerDialog().show(title: "To Date", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", defaultDate: defaultDate!, minDate: minDate, datePickerMode: .Date) {
(date) -> Void in
print(date, terminator: "\n")
let dateString = self.formatter.stringFromDate(date)
print("formated: \(dateString)", terminator: "\n")
sender.setTitle(dateString, forState: UIControlState.Normal)
}
}
@IBAction func onDoneDatePopup(sender: UIButton) {
let fromDate = formatter.dateFromString((fromButton.titleLabel!.text)!)
let toDate = formatter.dateFromString((toButton.titleLabel!.text)!)
let formater2 = NSDateFormatter()
formater2.dateFormat = "MMM dd, yyyy"
navigationItem.title = formater2.stringFromDate(fromDate!) + " - " + formater2.stringFromDate(toDate!)
closePopup(datePopup)
}
@IBAction func onCancelDatePopup(sender: UIButton) {
closePopup(datePopup)
}
func showPopup(popupView: UIView) {
popupSuperView.hidden = false
if popupView == viewModePopup {
viewModePopup.hidden = false
datePopup.hidden = true
} else {
viewModePopup.hidden = true
datePopup.hidden = false
}
popupView.transform = CGAffineTransformMakeScale(1.3, 1.3)
popupView.alpha = 0.0;
popupView.bringSubviewToFront(popupSuperView)
UIView.animateWithDuration(0.25, animations: {
popupView.alpha = 1.0
popupView.transform = CGAffineTransformMakeScale(1.0, 1.0)
});
}
func closePopup(popupView: UIView) {
UIView.animateWithDuration(0.25, animations: {
popupView.transform = CGAffineTransformMakeScale(1.3, 1.3)
popupView.alpha = 0.0;
}, completion:{(finished : Bool) in
if (finished) {
self.popupSuperView.hidden = true
}
});
}
}
// MARK: Table view
extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if tableView == self.viewModeTableView {
return 1
} else {
return 3
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == viewModeTableView {
return 4
} else {
switch section {
case 0:
return isCollapedIncome ? 1 : incomes.count + 1
case 1:
return isCollapedExpense ? 1 : expenses.count + 1
case 2:
return 1
default:
break
}
return 0
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 35
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == viewModeTableView {
let cell = tableView.dequeueReusableCellWithIdentifier("ViewModeCell", forIndexPath: indexPath) as! ViewModeCell
switch indexPath.row {
case 0:
cell.modeLabel.text = "Weekly"
break
case 1:
cell.modeLabel.text = "Monthly"
break
case 2:
cell.modeLabel.text = "Yearly"
break
case 3:
cell.modeLabel.text = "Custom"
break
default:
break
}
if indexPath.row == viewMode.rawValue {
cell.iconView.hidden = false
} else {
cell.iconView.hidden = true
}
Helper.sharedInstance.setSeparatorFullWidth(cell)
return cell
} else {
let dummyCell = UITableViewCell()
switch indexPath.section {
case 0:
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) as! MenuCell
cell.menuLabel.textColor = UIColor(netHex: 0x3D8B37)
cell.amountLabel.textColor = UIColor(netHex: 0x3D8B37)
cell.menuLabel.text = "Income"
if isCollapedIncome {
cell.iconView.image = UIImage(named: "Expand")
} else {
cell.iconView.image = UIImage(named: "Collapse")
}
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("tapIncome:"))
cell.addGestureRecognizer(tapGesture)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("SubMenuCell", forIndexPath: indexPath) as! SubMenuCell
cell.categoryLabel.text = incomes[indexPath.row - 1]
return cell
}
case 1:
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) as! MenuCell
cell.menuLabel.textColor = UIColor.redColor()
cell.amountLabel.textColor = UIColor.redColor()
cell.menuLabel.text = "Expense"
if isCollapedExpense {
cell.iconView.image = UIImage(named: "Expand")
} else {
cell.iconView.image = UIImage(named: "Collapse")
}
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("tapExpense:"))
cell.addGestureRecognizer(tapGesture)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("SubMenuCell", forIndexPath: indexPath) as! SubMenuCell
cell.categoryLabel.text = expenses[indexPath.row - 1]
return cell
}
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("BalanceCell", forIndexPath: indexPath) as! BalanceCell
return cell
default:
break
}
return dummyCell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == viewModeTableView {
switch indexPath.row {
case 0:
viewMode = ViewMode.Weekly
navigationItem.title = getWeekText(weekOfYear)
break
case 1:
viewMode = ViewMode.Monthly
navigationItem.title = getTodayString("MMMM")
break
case 2:
viewMode = ViewMode.Yearly
navigationItem.title = getTodayString("yyyy")
break
case 3:
viewMode = ViewMode.Custom
showPopup(datePopup)
return
default:
return
}
viewModeTableView.reloadData()
closePopup(viewModePopup)
}
}
}
// MARK: Handle gesture
extension HomeViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func handleSwipe(sender: UISwipeGestureRecognizer) {
// var today = NSDate()
switch sender.direction {
case UISwipeGestureRecognizerDirection.Left:
switch viewMode {
case ViewMode.Weekly:
weekOfYear += 1
navigationItem.title = getWeekText(weekOfYear)
break
case ViewMode.Monthly:
break
case ViewMode.Yearly:
break
default:
break
}
tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, 3)), withRowAnimation: UITableViewRowAnimation.Left)
break
case UISwipeGestureRecognizerDirection.Right:
switch viewMode {
case ViewMode.Weekly:
weekOfYear -= 1
navigationItem.title = getWeekText(weekOfYear)
break
case ViewMode.Monthly:
break
case ViewMode.Yearly:
break
default:
break
}
tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, 3)), withRowAnimation: UITableViewRowAnimation.Right)
break
case UISwipeGestureRecognizerDirection.Down:
let dvc = self.storyboard?.instantiateViewControllerWithIdentifier("QuickVC") as! QuickViewController
let nc = UINavigationController(rootViewController: dvc)
self.presentViewController(nc, animated: true, completion: nil)
break
default:
break
}
}
func tapIncome(sender: UITapGestureRecognizer) {
if isCollapedIncome {
isCollapedIncome = false
} else {
isCollapedIncome = true
}
tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic)
}
func tapExpense(sender: UITapGestureRecognizer) {
if isCollapedExpense {
isCollapedExpense = false
} else {
isCollapedExpense = true
}
tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Automatic)
}
func tapMode(sender: UITapGestureRecognizer) {
let selectedCell = Helper.sharedInstance.getCellAtGesture(sender, tableView: viewModeTableView)
if let selectedCell = selectedCell {
let indexPath = viewModeTableView.indexPathForCell(selectedCell)
switch indexPath!.row {
case 0:
viewMode = ViewMode.Weekly
navigationItem.title = getWeekText(weekOfYear)
break
case 1:
viewMode = ViewMode.Monthly
navigationItem.title = getTodayString("MMMM")
break
case 2:
viewMode = ViewMode.Yearly
navigationItem.title = getTodayString("yyyy")
break
case 3:
viewMode = ViewMode.Custom
break
default:
return
}
viewModeTableView.reloadData()
closePopup(viewModePopup)
}
}
} | mit | 536f3fadf8b47780199e5e0e4a722113 | 33.05303 | 173 | 0.563046 | 6.090447 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.