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
hakeemsyd/twitter
twitter/AppDelegate.swift
1
3797
// // AppDelegate.swift // twitter // // Created by Syed Hakeem Abbas on 9/25/17. // Copyright © 2017 codepath. All rights reserved. // import UIKit import BDBOAuth1Manager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { handleUserAuthentication() NotificationCenter.default.addObserver(forName: NSNotification.Name.init(User.userDidLogoutNotification), object: nil, queue: OperationQueue.main) { (Notification) in let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "loginScreen") self.window?.rootViewController = vc } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ application: UIApplication, handleOpen url: URL) -> Bool { print(url.description) TwitterClient.sharedInstance.handleOpenUrl(url: url) return true } func handleUserAuthentication() { if User.currentUser != nil { print("There is a current user") let storyboard = UIStoryboard(name: "Main", bundle: nil) /*let vc = storyboard.instantiateViewController(withIdentifier: "homeNavigationController")*/ let vc = storyboard.instantiateViewController(withIdentifier: "hamburgerViewController") as! HamburgerViewController window?.rootViewController = vc //.................................... let hamburgerViewController = window?.rootViewController as! HamburgerViewController let menuViewController = storyboard.instantiateViewController(withIdentifier: "menuViewController") as! MenuViewController menuViewController.hamburgerViewController = hamburgerViewController hamburgerViewController.menuViewController = menuViewController } else { print("There is no current user") } } }
apache-2.0
f5b96b50a92b82ab27732d7233f1f159
48.947368
285
0.710221
5.885271
false
false
false
false
ypopovych/ExpressCommandLine
Sources/swift-express/Core/Steps/RemoveItemsStep.swift
1
2303
//===--- RemoveItemsStep.swift --------------------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express Command Line is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===---------------------------------------------------------------------------===// import Foundation // Input: // Required: workingFolder // Optional: items - [String] struct RemoveItemsStep : Step { let dependsOn = [Step]() let items: [String]? init(items: [String]? = nil) { self.items = items } func run(_ params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] { guard let workingFolder = params["workingFolder"] as? URL else { throw SwiftExpressError.badOptions(message: "RemoveItems: No workingFolder option.") } var removeItems = [String]() if let i = self.items { removeItems.append(contentsOf: i) } if let i = params["items"] as! [String]? { removeItems.append(contentsOf: i) } for item in removeItems { let path = workingFolder.appendingPathComponent(item) do { if FileManager.default.directoryExists(at: path) || FileManager.default.fileExists(at: path) { try FileManager.default.removeItem(at: path) } } catch let err as NSError { throw SwiftExpressError.someNSError(error: err) } } return [String: Any]() } func cleanup(_ params:[String: Any], output: StepResponse) throws { } }
gpl-3.0
f5008012860701cfdefd1dbb6322ddd1
35.555556
110
0.595745
4.787942
false
false
false
false
dyshero/Pictorial-OC
原始/Pictorial-OC/Pods/ReactiveSwift/Sources/EventLogger.swift
19
4552
// // EventLogger.swift // ReactiveSwift // // Created by Rui Peres on 30/04/2016. // Copyright © 2016 GitHub. All rights reserved. // import Foundation /// A namespace for logging event types. public enum LoggingEvent { public enum Signal: String { case value, completed, failed, terminated, disposed, interrupted public static let allEvents: Set<Signal> = [ .value, .completed, .failed, .terminated, .disposed, .interrupted, ] } public enum SignalProducer: String { case starting, started, value, completed, failed, terminated, disposed, interrupted public static let allEvents: Set<SignalProducer> = [ .starting, .started, .value, .completed, .failed, .terminated, .disposed, .interrupted, ] } } private func defaultEventLog(identifier: String, event: String, fileName: String, functionName: String, lineNumber: Int) { print("[\(identifier)] \(event) fileName: \(fileName), functionName: \(functionName), lineNumber: \(lineNumber)") } /// A type that represents an event logging function. /// Signature is: /// - identifier /// - event /// - fileName /// - functionName /// - lineNumber public typealias EventLogger = ( _ identifier: String, _ event: String, _ fileName: String, _ functionName: String, _ lineNumber: Int ) -> Void extension SignalProtocol { /// Logs all events that the receiver sends. By default, it will print to /// the standard output. /// /// - parameters: /// - identifier: a string to identify the Signal firing events. /// - events: Types of events to log. /// - fileName: Name of the file containing the code which fired the /// event. /// - functionName: Function where event was fired. /// - lineNumber: Line number where event was fired. /// - logger: Logger that logs the events. /// /// - returns: Signal that, when observed, logs the fired events. public func logEvents(identifier: String = "", events: Set<LoggingEvent.Signal> = LoggingEvent.Signal.allEvents, fileName: String = #file, functionName: String = #function, lineNumber: Int = #line, logger: @escaping EventLogger = defaultEventLog) -> Signal<Value, Error> { func log<T>(_ event: LoggingEvent.Signal) -> ((T) -> Void)? { return event.logIfNeeded(events: events) { event in logger(identifier, event, fileName, functionName, lineNumber) } } return self.on( failed: log(.failed), completed: log(.completed), interrupted: log(.interrupted), terminated: log(.terminated), disposed: log(.disposed), value: log(.value) ) } } extension SignalProducerProtocol { /// Logs all events that the receiver sends. By default, it will print to /// the standard output. /// /// - parameters: /// - identifier: a string to identify the SignalProducer firing events. /// - events: Types of events to log. /// - fileName: Name of the file containing the code which fired the /// event. /// - functionName: Function where event was fired. /// - lineNumber: Line number where event was fired. /// - logger: Logger that logs the events. /// /// - returns: Signal producer that, when started, logs the fired events. public func logEvents(identifier: String = "", events: Set<LoggingEvent.SignalProducer> = LoggingEvent.SignalProducer.allEvents, fileName: String = #file, functionName: String = #function, lineNumber: Int = #line, logger: @escaping EventLogger = defaultEventLog ) -> SignalProducer<Value, Error> { func log<T>(_ event: LoggingEvent.SignalProducer) -> ((T) -> Void)? { return event.logIfNeeded(events: events) { event in logger(identifier, event, fileName, functionName, lineNumber) } } return self.on( starting: log(.starting), started: log(.started), failed: log(.failed), completed: log(.completed), interrupted: log(.interrupted), terminated: log(.terminated), disposed: log(.disposed), value: log(.value) ) } } private protocol LoggingEventProtocol: Hashable, RawRepresentable {} extension LoggingEvent.Signal: LoggingEventProtocol {} extension LoggingEvent.SignalProducer: LoggingEventProtocol {} private extension LoggingEventProtocol { func logIfNeeded<T>(events: Set<Self>, logger: @escaping (String) -> Void) -> ((T) -> Void)? { guard events.contains(self) else { return nil } return { value in if value is Void { logger("\(self.rawValue)") } else { logger("\(self.rawValue) \(value)") } } } }
mit
445ed98f02576046ed8d2223fe23c119
31.741007
273
0.668864
3.889744
false
false
false
false
artyom-stv/TextInputKit
Example/Example/Common/BankCard/Types.swift
1
473
// // Types.swift // Example // // Created by Artem Starosvetskiy on 16/12/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif #if os(macOS) typealias Color = NSColor typealias ViewController = NSViewController typealias TextField = NSTextField #else typealias Color = UIColor typealias ViewController = UIViewController typealias TextField = UITextField #endif
mit
2ff00a9dfb81ead21239aba0edb57da1
19.521739
62
0.716102
4.411215
false
false
false
false
wangCanHui/weiboSwift
weiboSwift/Classes/Extension/FFLabel.swift
2
8020
// // FFLabel.swift // FFLabel import UIKit @objc public protocol FFLabelDelegate: NSObjectProtocol { optional func labelDidSelectedLinkText(label: FFLabel, text: String) } public class FFLabel: UILabel { public var linkTextColor = UIColor.blueColor() public var selectedBackgroudColor = UIColor.lightGrayColor() public weak var labelDelegate: FFLabelDelegate? // MARK: - override properties override public var text: String? { didSet { updateTextStorage() } } override public var attributedText: NSAttributedString? { didSet { updateTextStorage() } } override public var font: UIFont! { didSet { updateTextStorage() } } override public var textColor: UIColor! { didSet { updateTextStorage() } } // MARK: - upadte text storage and redraw text private func updateTextStorage() { if attributedText == nil { return } let attrStringM = addLineBreak(attributedText!) regexLinkRanges(attrStringM) addLinkAttribute(attrStringM) textStorage.setAttributedString(attrStringM) setNeedsDisplay() } /// add link attribute private func addLinkAttribute(attrStringM: NSMutableAttributedString) { var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) attributes[NSFontAttributeName] = font! attributes[NSForegroundColorAttributeName] = textColor attrStringM.addAttributes(attributes, range: range) attributes[NSForegroundColorAttributeName] = linkTextColor for r in linkRanges { attrStringM.setAttributes(attributes, range: r) } } /// use regex check all link ranges private let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"] private func regexLinkRanges(attrString: NSAttributedString) { linkRanges.removeAll() let regexRange = NSRange(location: 0, length: attrString.string.characters.count) for pattern in patterns { let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) let results = regex.matchesInString(attrString.string, options: NSMatchingOptions(rawValue: 0), range: regexRange) for r in results { linkRanges.append(r.rangeAtIndex(0)) } } } /// add line break mode private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString { let attrStringM = NSMutableAttributedString(attributedString: attrString) var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle if paragraphStyle != nil { paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping } else { // iOS 8.0 can not get the paragraphStyle directly paragraphStyle = NSMutableParagraphStyle() paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping attributes[NSParagraphStyleAttributeName] = paragraphStyle attrStringM.setAttributes(attributes, range: range) } return attrStringM } public override func drawTextInRect(rect: CGRect) { let range = glyphsRange() let offset = glyphsOffset(range) layoutManager.drawBackgroundForGlyphRange(range, atPoint: offset) layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } private func glyphsRange() -> NSRange { return NSRange(location: 0, length: textStorage.length) } private func glyphsOffset(range: NSRange) -> CGPoint { let rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: textContainer) let height = (bounds.height - rect.height) * 0.5 return CGPoint(x: 0, y: height) } // MARK: - touch events public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) selectedRange = linkRangeAtLocation(location) modifySelectedAttribute(true) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) if let range = linkRangeAtLocation(location) { if !(range.location == selectedRange?.location && range.length == selectedRange?.length) { modifySelectedAttribute(false) selectedRange = range modifySelectedAttribute(true) } } else { modifySelectedAttribute(false) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if selectedRange != nil { let text = (textStorage.string as NSString).substringWithRange(selectedRange!) labelDelegate?.labelDidSelectedLinkText!(self, text: text) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { self.modifySelectedAttribute(false) } } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { modifySelectedAttribute(false) } private func modifySelectedAttribute(isSet: Bool) { if selectedRange == nil { return } var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil) attributes[NSForegroundColorAttributeName] = linkTextColor let range = selectedRange! if isSet { attributes[NSBackgroundColorAttributeName] = selectedBackgroudColor } else { attributes[NSBackgroundColorAttributeName] = UIColor.clearColor() selectedRange = nil } textStorage.addAttributes(attributes, range: range) setNeedsDisplay() } private func linkRangeAtLocation(location: CGPoint) -> NSRange? { if textStorage.length == 0 { return nil } let offset = glyphsOffset(glyphsRange()) let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y) let index = layoutManager.glyphIndexForPoint(point, inTextContainer: textContainer) for r in linkRanges { if index >= r.location && index <= r.location + r.length { return r } } return nil } // MARK: - init functions override public init(frame: CGRect) { super.init(frame: frame) prepareLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareLabel() } public override func layoutSubviews() { super.layoutSubviews() textContainer.size = bounds.size } private func prepareLabel() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) textContainer.lineFragmentPadding = 0 userInteractionEnabled = true } // MARK: lazy properties private lazy var linkRanges = [NSRange]() private var selectedRange: NSRange? private lazy var textStorage = NSTextStorage() private lazy var layoutManager = NSLayoutManager() private lazy var textContainer = NSTextContainer() }
apache-2.0
0036e555cab8e71e3db6809e52c5367d
32.140496
128
0.622818
5.651868
false
false
false
false
mathewsheets/SwiftLearningExercises
Exercise_10.playground/Sources/Dog.swift
1
1054
import Foundation public class Dog: Pet { override public var age: Int { willSet { if newValue >= 10 { print("\(name) will die in a couple of years.") } } didSet { if age >= 12 { print("\(name) died.") } } } internal unowned var owner: Owner public init(breed: String, color: String, age: Int, name: String, owner: Owner) { self.owner = owner super.init(breed: breed, color: color, age: age, name: name) } public func barking(loudness: Loudness) { print("\(name) is barking \(loudness) loud.") } override public func chase(what: Pet) { var something = "something" if what is Cat { something = "cat" } print("\(name) is chasing \(what.name) a \(something).") } override public func makeSound() { barking(loudness: Loudness.Very) } }
mit
7551ca6f2209b3998f6c057c986b39c1
21.425532
85
0.47723
4.60262
false
false
false
false
Maggie005889/weibo4
新浪微博3/Classes/Module/Message/MessageTableViewController.swift
1
3245
// // MessageTableViewController.swift // 新浪微博3 // // Created by Maggie on 15/10/8. // Copyright © 2015年 Maggie. All rights reserved. // import UIKit class MessageTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
d927cd823d8c1088c4f1507697ab5d15
33.042105
157
0.687384
5.566265
false
false
false
false
PhilJay/SugarRecord
spec/Realm/DefaultREALMStackTests.swift
11
4101
// // DefaultREALMStackTests.swift // SugarRecord // // Created by Pedro Piñera Buendía on 27/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import UIKit import XCTest import Realm class DefaultREALMStackTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testThatPropertiesAreSetInInit() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") XCTAssertEqual(stack.name, "name", "The name should be set in init") XCTAssertEqual(stack.stackDescription, "description", "The description should be set in init") } func testIfReturnsTheDefaultRLMContextForTheContext() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") XCTAssertEqual((stack.mainThreadContext() as SugarRecordRLMContext).realmContext, RLMRealm.defaultRealm(), "Default stack should return the default realm object") } func testIfReturnsTheDefaultRLMContextForTheContextInBAckground() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") let expectation = expectationWithDescription("background operation") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in XCTAssertEqual((stack.backgroundContext() as SugarRecordRLMContext).realmContext, RLMRealm.defaultRealm(), "Default stack should return the default realm object") expectation.fulfill() }) waitForExpectationsWithTimeout(0.2, handler: nil) } func testIfInitializeTriesToMigrateIfNeeded() { class MockRealmStack: DefaultREALMStack { var migrateIfNeededCalled: Bool = false override func migrateIfNeeded() { self.migrateIfNeededCalled = true } } let mockRealmStack: MockRealmStack = MockRealmStack(stackName: "Mock Stack", stackDescription: "Stack description") mockRealmStack.initialize() XCTAssertTrue(mockRealmStack.migrateIfNeededCalled, "Migration checking should be done in when initializing") } func testIfMigrationsAreProperlySorted() { var migrations: [RLMObjectMigration<RLMObject>] = [RLMObjectMigration<RLMObject>]() migrations.append(RLMObjectMigration<RLMObject>(toSchema: 13, migrationClosure: { (oldObject, newObject) -> () in })) migrations.append(RLMObjectMigration<RLMObject>(toSchema: 3, migrationClosure: { (oldObject, newObject) -> () in })) migrations.append(RLMObjectMigration<RLMObject>(toSchema: 1, migrationClosure: { (oldObject, newObject) -> () in })) let stack: DefaultREALMStack = DefaultREALMStack(stackName: "Stack name", stackDescription: "Stack description", migrations: migrations) var sortedMigrations: [RLMObjectMigration<RLMObject>] = DefaultREALMStack.sorteredAndFiltered(migrations: migrations, fromOldSchema: 2) XCTAssertEqual(sortedMigrations.first!.toSchema, 3, "First migration in the array should have toSchema = 3") XCTAssertEqual(sortedMigrations.last!.toSchema, 13, "First migration in the array should have toSchema = 13") } /* func testDatabaseRemoval() { let stack = DefaultREALMStack(stackName: "test", stackDescription: "test stack") SugarRecord.addStack(stack) let documentsPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let databaseName: String = documentsPath.stringByAppendingPathComponent("default.realm") XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(databaseName), "The database is not created in the right place") stack.removeDatabase() XCTAssertFalse(NSFileManager.defaultManager().fileExistsAtPath(databaseName), "The database is not created in the right place") SugarRecord.removeAllStacks() } */ }
mit
9d75361911e667580cfce278b2c7b80d
46.662791
174
0.714321
5.255128
false
true
false
false
mdiep/Tentacle
Sources/Tentacle/Comment.swift
1
1504
// // Comment.swift // Tentacle // // Created by Romain Pouclet on 2016-07-27. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension Repository { /// A request for the comments on the given issue. /// /// https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue public func comments(onIssue issue: Int) -> Request<[Comment]> { return Request(method: .get, path: "/repos/\(owner)/\(name)/issues/\(issue)/comments") } } public struct Comment: CustomStringConvertible, ResourceType, Identifiable { /// The id of the issue public let id: ID<Comment> /// The URL to view this comment in a browser public let url: URL /// The date this comment was created at public let createdAt: Date /// The date this comment was last updated at public let updatedAt: Date /// The body of the comment public let body: String /// The author of this comment public let author: UserInfo public var description: String { return body } private enum CodingKeys: String, CodingKey { case id case url = "html_url" case createdAt = "created_at" case updatedAt = "updated_at" case body case author = "user" } } extension Comment: Equatable { public static func ==(lhs: Comment, rhs: Comment) -> Bool { return lhs.id == rhs.id && lhs.url == rhs.url && lhs.body == rhs.body } }
mit
ff2eec46cc9306f62c77a0bf64ee3be1
25.368421
94
0.624085
4.175
false
false
false
false
debugsquad/metalic
metalic/View/Main/VBarCell.swift
1
1751
import UIKit class VBarCell:UICollectionViewCell { weak var icon:UIImageView! weak var model:MMainItem! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let icon:UIImageView = UIImageView() icon.isUserInteractionEnabled = false icon.clipsToBounds = true icon.translatesAutoresizingMaskIntoConstraints = false icon.contentMode = UIViewContentMode.center self.icon = icon addSubview(icon) let views:[String:UIView] = [ "icon":icon] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[icon]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-20-[icon]-0-|", options:[], metrics:metrics, views:views)) } required init?(coder:NSCoder) { fatalError() } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { icon.image = UIImage(named:model.iconImageOn) } else { icon.image = UIImage(named:model.iconImageOff) } } //MARK: public func config(model:MMainItem) { self.model = model hover() } }
mit
6d1f90dffeb4f333e786eb7ebbd0f820
20.353659
62
0.519132
5.338415
false
false
false
false
PodRepo/firefox-ios
Utils/FaviconFetcher.swift
3
6214
/* 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 Storage import Shared import Alamofire import XCGLogger private let log = Logger.browserLogger private let queue = dispatch_queue_create("FaviconFetcher", DISPATCH_QUEUE_CONCURRENT) class FaviconFetcherErrorType: MaybeErrorType { let description: String init(description: String) { self.description = description } } /* A helper class to find the favicon associated with a URL. * This will load the page and parse any icons it finds out of it. * If that fails, it will attempt to find a favicon.ico in the root host domain. */ public class FaviconFetcher : NSObject, NSXMLParserDelegate { public static var userAgent: String = "" static let ExpirationTime = NSTimeInterval(60*60*24*7) // Only check for icons once a week class func getForURL(url: NSURL, profile: Profile) -> Deferred<Maybe<[Favicon]>> { let f = FaviconFetcher() return f.loadFavicons(url, profile: profile) } private func loadFavicons(url: NSURL, profile: Profile, var oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> { if isIgnoredURL(url) { return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons.")) } let deferred = Deferred<Maybe<[Favicon]>>() dispatch_async(queue) { _ in self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in var deferreds = [Deferred<Maybe<Favicon>>]() if let icons = result.successValue { deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) } } return all(deferreds) }).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in for result in results { if let icon = result.successValue { oldIcons.append(icon) } } oldIcons.sortInPlace({ (a, b) -> Bool in return a.width > b.width }) return deferMaybe(oldIcons) }).upon({ (result: Maybe<[Favicon]>) in deferred.fill(result) return }) } return deferred } lazy private var alamofire: Alamofire.Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.timeoutIntervalForRequest = 5 return Alamofire.Manager.managerWithUserAgent(userAgent, configuration: configuration) }() private func fetchDataForURL(url: NSURL) -> Deferred<Maybe<NSData>> { let deferred = Deferred<Maybe<NSData>>() alamofire.request(.GET, url).response { (request, response, data, error) in if error == nil { if let data = data { deferred.fill(Maybe(success: data)) return } } deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: error?.description ?? "No content."))) } return deferred } // Loads and parses an html document and tries to find any known favicon-type tags for the page private func parseHTMLForFavicons(url: NSURL) -> Deferred<Maybe<[Favicon]>> { return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in var icons = [Favicon]() if let data = result.successValue where result.isSuccess, let element = RXMLElement(fromHTMLData: data) where element.isValid { var reloadUrl: NSURL? = nil element.iterate("head.meta") { meta in if let refresh = meta.attribute("http-equiv") where refresh == "Refresh", let content = meta.attribute("content"), let index = content.rangeOfString("URL="), let url = NSURL(string: content.substringFromIndex(index.startIndex.advancedBy(4))) { reloadUrl = url } } if let url = reloadUrl { return self.parseHTMLForFavicons(url) } element.iterate("head.link") { link in if let rel = link.attribute("rel") where (rel == "shortcut icon" || rel == "icon" || rel == "apple-touch-icon"), let href = link.attribute("href"), let url = NSURL(string: href, relativeToURL: url) { let icon = Favicon(url: url.absoluteString, date: NSDate(), type: IconType.Icon) icons.append(icon) } } } return deferMaybe(icons) }) } private func getFavicon(siteUrl: NSURL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let url = icon.url let manager = SDWebImageManager.sharedManager() let site = Site(url: siteUrl.absoluteString, title: "") var fav = Favicon(url: url, type: icon.type) if let url = url.asURL { manager.downloadImageWithURL(url, options: SDWebImageOptions.LowPriority, progress: nil, completed: { (img, err, cacheType, success, url) -> Void in fav = Favicon(url: url.absoluteString, type: icon.type) if let img = img { fav.width = Int(img.size.width) fav.height = Int(img.size.height) profile.favicons.addFavicon(fav, forSite: site) } else { fav.width = 0 fav.height = 0 } deferred.fill(Maybe(success: fav)) }) } else { return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)")) } return deferred } }
mpl-2.0
4da484cb93f5928e0c088be012ef15d1
39.090323
160
0.566785
4.999195
false
false
false
false
awslabs/aws-sdk-ios-samples
IoT-Sample/Swift/IoTSampleSwift/ConfigurationViewController.swift
1
8099
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import AWSIoT class ConfigurationViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var deleteCertificateButton: UIButton! @IBOutlet weak var topicTextField: UITextField! @IBAction func deleteCertificateButtonPressed(_ sender: AnyObject) { let actionController: UIAlertController = UIAlertController( title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction: UIAlertAction = UIAlertAction( title: "Cancel", style: .cancel) { action -> Void in } actionController.addAction( cancelAction ) let okAction: UIAlertAction = UIAlertAction( title: "Delete", style: .default) { action -> Void in print( "deleting identity...") // To delete an identity created via the API: // // 1) Set the certificate's status to 'inactive' // 2) Detach the policy from the certificate // 3) Delete the certificate // 4) Remove the keys and certificate from the keychain // 5) Delete user defaults // // To delete an identity created via a PKCS12 file in the bundle: // // 1) Remove the keys and certificate from the keychain // 2) Delete user defaults let defaults = UserDefaults.standard let certificateId = defaults.string( forKey: "certificateId") let certificateArn = defaults.string( forKey: "certificateArn") if certificateArn != "from-bundle" && certificateId != nil { let iot = AWSIoT.default() let updateCertificateRequest = AWSIoTUpdateCertificateRequest() updateCertificateRequest?.certificateId = certificateId updateCertificateRequest?.latestStatus = .inactive iot.updateCertificate( updateCertificateRequest! ).continueWith(block:{ (task) -> AnyObject? in if let error = task.error { print("failed: [\(error)]") } print("result: [\(String(describing: task.result))]") if (task.error == nil) { // The certificate is now inactive; detach the policy from the certificate. let certificateArn = defaults.string( forKey: "certificateArn") let detachPolicyRequest = AWSIoTDetachPrincipalPolicyRequest() detachPolicyRequest?.principal = certificateArn detachPolicyRequest?.policyName = POLICY_NAME iot.detachPrincipalPolicy(detachPolicyRequest!).continueWith(block: { (task) -> AnyObject? in if let error = task.error { print("failed: [\(error)]") } print("result: [\(String(describing: task.result))]") if (task.error == nil) { // The policy is now detached; delete the certificate let deleteCertificateRequest = AWSIoTDeleteCertificateRequest() deleteCertificateRequest?.certificateId = certificateId iot.deleteCertificate(deleteCertificateRequest!).continueWith(block: { (task) -> AnyObject? in if let error = task.error { print("failed: [\(error)]") } print("result: [\(String(describing: task.result))]") if (task.error == nil) { // The certificate has been deleted; now delete the keys and certificate from the keychain. if (AWSIoTManager.deleteCertificate() != true) { print("error deleting certificate") } else { defaults.removeObject(forKey: "certificateId") defaults.removeObject(forKey: "certificateArn") DispatchQueue.main.async { self.tabBarController?.selectedIndex = 0 } } } return nil }) } return nil }) } return nil }) } else if certificateArn == "from-bundle" { // Delete the keys and certificate from the keychain. if (AWSIoTManager.deleteCertificate() != true) { print("error deleting certificate") } else { defaults.removeObject(forKey: "certificateId") defaults.removeObject(forKey: "certificateArn") DispatchQueue.main.async { self.tabBarController?.selectedIndex = 0 } } } else { print("certificate id == nil!") // shouldn't be possible } } actionController.addAction( okAction ) self.present( actionController, animated: true, completion: nil ) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { topicTextField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { topicTextField.text = textField.text let defaults = UserDefaults.standard let tabBarViewController = tabBarController as! IoTSampleTabBarController tabBarViewController.topic = textField.text! defaults.set(textField.text, forKey:"sliderTopic") } override func viewDidLoad() { super.viewDidLoad() topicTextField.delegate = self let defaults = UserDefaults.standard let certificateId = defaults.string( forKey: "certificateId") let sliderTopic = defaults.string( forKey: "sliderTopic" ) let tabBarViewController = tabBarController as! IoTSampleTabBarController if (certificateId == nil) { deleteCertificateButton.isHidden=true } if (sliderTopic != nil) { tabBarViewController.topic=sliderTopic! } topicTextField.text = tabBarViewController.topic } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let defaults = UserDefaults.standard let certificateId = defaults.string( forKey: "certificateId") if (certificateId == nil) { deleteCertificateButton.isHidden=true } else { deleteCertificateButton.isHidden=false } } }
apache-2.0
b226a189d7672960edd5f5bc7816892e
41.182292
131
0.51636
6.41251
false
false
false
false
scotlandyard/expocity
expocity/Firebase/Database/Models/FDatabaseModelMessageEmoji.swift
1
1346
import Foundation class FDatabaseModelMessageEmoji:FDatabaseModelMessage { let emoji:Emoji enum Emoji:Int { case none = 0 case like = 1 case love = 2 case smile = 3 case sad = 4 case angry = 5 case surprise = 6 } init(senderId:String, senderName:String, emoji:Emoji) { self.emoji = emoji super.init(senderId:senderId, senderName:senderName) } required init(snapshot:Any?) { let snapshotDict:[String:Any]? = snapshot as? [String:Any] let rawEmoji:Int? = snapshotDict?[Property.emoji.rawValue] as? Int if rawEmoji == nil { emoji = Emoji.none } else { emoji = Emoji(rawValue:rawEmoji!)! } super.init(snapshot:snapshot) } override func modelJson() -> Any { var json:[String:Any] = [ Property.emoji.rawValue:emoji.rawValue ] let parentJson:[String:Any] = super.modelJson() as! [String:Any] let parentKeys:[String] = Array(parentJson.keys) for parentKey:String in parentKeys { let parentValue:Any = parentJson[parentKey]! json[parentKey] = parentValue } return json } }
mit
a4c491c8ea33c04b5a1a8700e9181684
22.206897
74
0.537147
4.413115
false
false
false
false
qvacua/vimr
VimR/VimR/FileBrowser.swift
1
5838
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import Commons import MaterialIcons import PureLayout import RxSwift import Workspace final class FileBrowser: NSView, UiComponent { typealias StateType = MainWindow.State enum Action { case open(url: URL, mode: MainWindow.OpenMode) case setAsWorkingDirectory(URL) case setShowHidden(Bool) case refresh } let innerCustomToolbar = InnerCustomToolbar() let menuItems: [NSMenuItem] override var isFirstResponder: Bool { self.fileView.isFirstResponder } required init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType) { self.emit = emitter.typedEmit() self.uuid = state.uuid self.cwd = state.cwd self.fileView = FileOutlineView(source: source, emitter: emitter, state: state) self.showHiddenMenuItem = NSMenuItem( title: "Show Hidden Files", action: #selector(FileBrowser.showHiddenAction), keyEquivalent: "" ) self.showHiddenMenuItem.boolState = state.fileBrowserShowHidden self.menuItems = [self.showHiddenMenuItem] super.init(frame: .zero) self.addViews() self.showHiddenMenuItem.target = self self.innerCustomToolbar.fileBrowser = self source .observe(on: MainScheduler.instance) .subscribe(onNext: { state in if self.cwd != state.cwd { self.cwd = state.cwd self.innerCustomToolbar.goToParentButton.isEnabled = state.cwd.path != "/" } self.currentBufferUrl = state.currentBuffer?.url self.showHiddenMenuItem.boolState = state.fileBrowserShowHidden }) .disposed(by: self.disposeBag) } deinit { self.fileView.unbindTreeController() } private let emit: (UuidAction<Action>) -> Void private let disposeBag = DisposeBag() private let uuid: UUID private var currentBufferUrl: URL? private let fileView: FileOutlineView private let showHiddenMenuItem: NSMenuItem private var cwd: URL @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addViews() { let scrollView = NSScrollView.standardScrollView() scrollView.borderType = .noBorder scrollView.documentView = self.fileView self.addSubview(scrollView) scrollView.autoPinEdgesToSuperviewEdges() } } extension FileBrowser { class InnerCustomToolbar: CustomToolBar { let goToParentButton = NSButton(forAutoLayout: ()) let scrollToSourceButton = NSButton(forAutoLayout: ()) let refreshButton = NSButton(forAutoLayout: ()) init() { super.init(frame: .zero) self.configureForAutoLayout() self.addViews() } override func repaint(with theme: Workspace.Theme) { self.goToParentButton.image = Icon.arrowUpward.asImage( dimension: InnerToolBar.iconDimension, style: .filled, color: theme.toolbarForeground ) self.scrollToSourceButton.image = Icon.adjust.asImage( dimension: InnerToolBar.iconDimension, style: .filled, color: theme.toolbarForeground ) self.refreshButton.image = Icon.refresh.asImage( dimension: InnerToolBar.iconDimension, style: .filled, color: theme.toolbarForeground ) } fileprivate weak var fileBrowser: FileBrowser? { didSet { self.goToParentButton.target = self.fileBrowser self.scrollToSourceButton.target = self.fileBrowser self.refreshButton.target = self.fileBrowser } } private func addViews() { let goToParent = self.goToParentButton InnerToolBar.configureToStandardIconButton( button: goToParent, iconName: .arrowUpward, style: .filled ) goToParent.toolTip = "Set parent as working directory" goToParent.action = #selector(FileBrowser.goToParentAction) let scrollToSource = self.scrollToSourceButton InnerToolBar.configureToStandardIconButton( button: scrollToSource, iconName: .adjust, style: .filled ) scrollToSource.toolTip = "Navigate to the current buffer" scrollToSource.action = #selector(FileBrowser.scrollToSourceAction) let refresh = self.refreshButton InnerToolBar.configureToStandardIconButton(button: refresh, iconName: .sync, style: .filled) refresh.toolTip = "Refresh" refresh.action = #selector(FileBrowser.refreshAction) self.addSubview(goToParent) self.addSubview(scrollToSource) self.addSubview(refresh) refresh.autoPinEdge(toSuperviewEdge: .top) refresh.autoPinEdge(toSuperviewEdge: .right, withInset: InnerToolBar.itemPadding) goToParent.autoPinEdge(toSuperviewEdge: .top) goToParent.autoPinEdge(.right, to: .left, of: refresh, withOffset: -InnerToolBar.itemPadding) scrollToSource.autoPinEdge(toSuperviewEdge: .top) scrollToSource.autoPinEdge( .right, to: .left, of: goToParent, withOffset: -InnerToolBar.itemPadding ) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } } // MARK: - Actions extension FileBrowser { @objc func showHiddenAction(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem else { return } self.emit(UuidAction(uuid: self.uuid, action: .setShowHidden(!menuItem.boolState))) } @objc func goToParentAction(_: Any?) { self.emit(UuidAction(uuid: self.uuid, action: .setAsWorkingDirectory(self.cwd.parent))) } @objc func scrollToSourceAction(_: Any?) { guard let url = self.currentBufferUrl else { return } self.fileView.select(url) } @objc func refreshAction(_: Any?) { self.emit(UuidAction(uuid: self.uuid, action: .refresh)) } }
mit
f15ac0cb96ef6350b6152686be6b47ce
27.90099
99
0.694073
4.604101
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Files/IssueFileCell.swift
1
2689
// // IssueFileCell.swift // Freetime // // Created by Ryan Nystrom on 8/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit final class IssueFileCell: SelectableCell { private let changeLabel = UILabel() private let pathLabel = UILabel() private let disclosure = UIImageView(image: UIImage(named: "chevron-right").withRenderingMode(.alwaysTemplate)) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white disclosure.tintColor = Styles.Colors.Gray.light.color disclosure.contentMode = .scaleAspectFit contentView.addSubview(disclosure) disclosure.snp.makeConstraints { make in make.right.equalTo(-Styles.Sizes.gutter) make.centerY.equalToSuperview() make.size.equalTo(Styles.Sizes.icon) } contentView.addSubview(changeLabel) changeLabel.snp.makeConstraints { make in make.left.equalTo(Styles.Sizes.gutter) make.bottom.equalTo(contentView.snp.centerY) make.right.lessThanOrEqualTo(disclosure.snp.left).offset(-Styles.Sizes.rowSpacing) } pathLabel.font = Styles.Text.body.preferredFont pathLabel.textColor = Styles.Colors.Gray.dark.color pathLabel.lineBreakMode = .byTruncatingHead contentView.addSubview(pathLabel) pathLabel.snp.makeConstraints { make in make.left.equalTo(Styles.Sizes.gutter) make.top.equalTo(changeLabel.snp.bottom) make.right.lessThanOrEqualTo(disclosure.snp.left).offset(-Styles.Sizes.rowSpacing) } addBorder(.bottom, left: Styles.Sizes.gutter) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Public API func configure(path: String, additions: Int, deletions: Int, disclosureHidden: Bool) { let changeString = NSMutableAttributedString() var attributes: [NSAttributedStringKey: Any] = [ .font: Styles.Text.secondaryBold.preferredFont ] if additions > 0 { attributes[.foregroundColor] = Styles.Colors.Green.medium.color changeString.append(NSAttributedString(string: "+\(additions) ", attributes: attributes)) } if deletions > 0 { attributes[.foregroundColor] = Styles.Colors.Red.medium.color changeString.append(NSAttributedString(string: "-\(deletions)", attributes: attributes)) } changeLabel.attributedText = changeString disclosure.isHidden = disclosureHidden pathLabel.text = path } }
mit
6696982940296b23a500de7bc65301e9
33.025316
115
0.664807
4.749117
false
false
false
false
cpimhoff/AntlerKit
Framework/AntlerKit/Game Object/GameObject.swift
1
5505
// // GameObject.swift // AntlerKit // // Created by Charlie Imhoff on 12/31/16. // Copyright © 2016 Charlie Imhoff. All rights reserved. // import Foundation import SpriteKit import GameplayKit /// An game entity in the AntlerKit game scene. open class GameObject : InternalUpdatesEachFrame { internal let root : RootTransform /// Creates a new GameObject public init() { self.root = RootTransform() self.root.gameObject = self } // MARK: - Primitive /// The visual representation of the GameObject public var primitive : Primitive? { didSet { if oldValue != nil { self.root.removeChildren(in: [oldValue!]) } if primitive != nil { primitive!.position = CGPoint(x: 0, y: 0) self.root.addChild(primitive!) } } } public var animator : Animator? { didSet { self.animator?.gameObject = self if self.primitive == nil { // animator requires a primitive to be present self.primitive = SKNode() } } } // MARK: - Agent // use this to check if we have an agent (without touching, and thus initializing it) private var isAgentInitialized = false /// An Agent for this GameObject to use for AI behavior public lazy var agent : Agent2D = { self.isAgentInitialized = true return GKAgent2D() }() // MARK: - Component private var componentMap = [String: Component]() /// All the components currently associated with this GameObject public var components : [Component] { return Array(self.componentMap.values) } internal var enabledComponents : [Component] { return self.componentMap.values.filter { $0.enabled } } /// Add a component to this GameObject public func add(_ component: Component) { if component is AnonymousComponent { self.add(component, key: UUID().uuidString) } else { let typeName = String(describing: type(of: component)) if self.componentMap[typeName] != nil { self.add(component, key: typeName) } else { self.add(component, key: UUID().uuidString) } } } private func add(_ component: Component, key: String) { self.componentMap[key] = component component.gameObject = self component.configure() } /// Get a Component attached to this GameObject of the specified class public func component<T: Component>(type: T.Type) -> T? { let typeName = String(describing: type) return self.componentMap[typeName] as? T } // MARK: - Children /// Add a GameObject as a child of this one open func add(_ child: GameObject) { self.root.addChild(child.root) } /// All the immediate child GameObjects of this GameObject public var children : [GameObject] { var gameObjects = [GameObject]() for node in self.root.children { if let transform = node as? RootTransform { gameObjects.append(transform.gameObject) } } return gameObjects } // MARK: - Destruction /// Remove this GameObject from its parent, orphaning it from the scene open func removeFromParent() { if self.root.parent == self.root.scene { let scene = (self.root.scene as? WrappedScene)?.delegateScene scene?.stopDirectUpdates(self) } self.root.removeFromParent() // unhook primitive from everything } // MARK: - Update internal func internalUpdate(deltaTime: TimeInterval) { if self.isAgentInitialized { self.updateAgent(deltaTime: deltaTime) } for child in self.children { child.internalUpdate(deltaTime: deltaTime) } for component in self.enabledComponents { component.update(deltaTime: deltaTime) } // call user provided update self.update(deltaTime: deltaTime) } open func update(deltaTime: TimeInterval) {} // MARK: - Configuration /// If true, any contact event on this gameObject will be forwarded /// to the children of this game object. public var propogateContactsToChildren = false /// If true, this gameObject should never move positions (directly moved or indirectly moved) /// The object is still allowed to animate frames, but its position and bounding box can not change. /// /// Used to generate object graphs public var isStatic = false { didSet { self.body?.isDynamic = !self.isStatic } } } // MARK: - Primitive Configuration public extension GameObject { /// The current position, relative to parent, of the reciever var position : Point { get { return root.position } set { root.position = newValue } } /// The current position in scene space of the reciever. var scenePosition : Point { guard let scene = root.scene else { fatalError("GameObject has not been added to a scene and thus has no scene-relative position") } if root.parent == scene { return self.position } return root.convert(root.position, to: scene) } /// The position of the reciver in the coordinate system of the other object func relativePosition(in other: GameObject) -> Point { return self.root.convert(self.position, to: other.root) } /// The current rotation, relative to parent, of the reciever var rotation : Float { get { return Float(self.root.zRotation) } set { self.root.zRotation = CGFloat(newValue) } } /// The current layer, relative to parent, of the reciever var layer : Int { get { return Int(root.zPosition) } set { root.zPosition = CGFloat(newValue) } } /// The GameObject's physics body var body : PhysicsBody? { get { return self.root.physicsBody } set { self.root.physicsBody = newValue self.root.physicsBody?.isDynamic = !self.isStatic } } }
mit
ccafa0e1adc703d378d016ba9815db2f
23.246696
101
0.693677
3.604453
false
false
false
false
HongliYu/firefox-ios
Shared/Extensions/UIImageExtensions.swift
1
3492
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SDWebImage private let imageLock = NSLock() extension CGRect { public init(width: CGFloat, height: CGFloat) { self.init(x: 0, y: 0, width: width, height: height) } public init(size: CGSize) { self.init(origin: .zero, size: size) } } extension Data { public var isGIF: Bool { return [0x47, 0x49, 0x46].elementsEqual(prefix(3)) } } extension UIImage { /// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132). /// As a workaround, synchronize access to this initializer. /// This fix requires that you *always* use this over UIImage(data: NSData)! public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage(data: data) imageLock.unlock() return image } public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let context = UIGraphicsGetCurrentContext() let rect = CGRect(size: size) color.setFill() context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } public func createScaled(_ size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) draw(in: CGRect(size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } public static func templateImageNamed(_ name: String) -> UIImage? { return UIImage(named: name)?.withRenderingMode(.alwaysTemplate) } // Uses compositor blending to apply color to an image. public func tinted(withColor: UIColor) -> UIImage { let img2 = UIImage.createWithColor(size, color: withColor) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let renderer = UIGraphicsImageRenderer(size: size) let result = renderer.image { ctx in img2.draw(in: rect, blendMode: .normal, alpha: 1) draw(in: rect, blendMode: .destinationIn, alpha: 1) } return result } // TESTING ONLY: not for use in release/production code. // PNG comparison can return false negatives, be very careful using for non-equal comparison. // PNG comparison requires UIImages to be constructed the same way in order for the metadata block to match, // this function ensures that. // // This can be verified with this code: // let image = UIImage(named: "fxLogo")! // let data = UIImagePNGRepresentation(image)! // assert(data != UIImagePNGRepresentation(UIImage(data: data)!)) @available(*, deprecated, message: "use only in testing code") public func isStrictlyEqual(to other: UIImage) -> Bool { // Must use same constructor for PNG metadata block to be the same. let imageA = UIImage(data: UIImagePNGRepresentation(self)!)! let imageB = UIImage(data: UIImagePNGRepresentation(other)!)! let dataA = UIImagePNGRepresentation(imageA)! let dataB = UIImagePNGRepresentation(imageB)! return dataA == dataB } }
mpl-2.0
9a23b17e69173eecfde7feabb4e02cab
37.8
112
0.663517
4.546875
false
false
false
false
alblue/swift
test/Sema/exhaustive_switch.swift
1
32433
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-resilience // RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience -enable-nonfrozen-enum-exhaustivity-diagnostics func foo(a: Int?, b: Int?) -> Int { switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (.some(_), .some(_)): return 3 } switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (_?, _?): return 3 } switch Optional<(Int?, Int?)>.some((a, b)) { case .none: return 1 case let (_, x?)?: return x case let (x?, _)?: return x case (.none, .none)?: return 0 } } func bar(a: Bool, b: Bool) -> Int { switch (a, b) { case (false, false): return 1 case (true, _): return 2 case (false, true): return 3 } } enum Result<T> { case Ok(T) case Error(Error) func shouldWork<U>(other: Result<U>) -> Int { switch (self, other) { // No warning case (.Ok, .Ok): return 1 case (.Error, .Error): return 2 case (.Error, _): return 3 case (_, .Error): return 4 } } } func overParenthesized() { // SR-7492: Space projection needs to treat extra paren-patterns explicitly. let x: Result<(Result<Int>, String)> = .Ok((.Ok(1), "World")) switch x { case let .Error(e): print(e) case let .Ok((.Error(e), b)): print(e, b) case let .Ok((.Ok(a), b)): // No warning here. print(a, b) } } enum Foo { case A(Int) case B(Int) } func foo() { switch (Foo.A(1), Foo.B(1)) { case (.A(_), .A(_)): () case (.B(_), _): () case (_, .B(_)): () } switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) { case (.A(_), _): break case (.B(_), (let q, _)?): print(q) case (.B(_), nil): break } } class C {} enum Bar { case TheCase(C?) } func test(f: Bar) -> Bool { switch f { case .TheCase(_?): return true case .TheCase(nil): return false } } func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> { switch (this, other) { // No warning case let (.none, w): return w case let (w, .none): return w case let (.some(e1), .some(e2)): return .some(e1 && e2) } } enum Threepeat { case a, b, c } func test3(x: Threepeat, y: Threepeat) { switch (x, y) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.a, .c)'}} case (.a, .a): () case (.b, _): () case (.c, _): () case (_, .b): () } } enum A { case A(Int) case B(Bool) case C case D } enum B { case A case B } func s(a: A, b: B) { switch (a, b) { case (.A(_), .A): break case (.A(_), .B): break case (.B(_), let b): // expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}} break case (.C, _), (.D, _): break } } enum Grimble { case A case B case C } enum Gromble { case D case E } func doSomething(foo:Grimble, bar:Gromble) { switch(foo, bar) { // No warning case (.A, .D): break case (.A, .E): break case (.B, _): break case (.C, _): break } } enum E { case A case B } func f(l: E, r: E) { switch (l, r) { case (.A, .A): return case (.A, _): return case (_, .A): return case (.B, .B): return } } enum TestEnum { case A, B } func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) { switch testEnumTuple { case (_,.B): // Matches (.A, .B) and (.B, .B) break case (.A,_): // Matches (.A, .A) // Would also match (.A, .B) but first case takes precedent break case (.B,.A): // Matches (.B, .A) break } } func tests(a: Int?, b: String?) { switch (a, b) { case let (.some(n), _): print("a: ", n, "?") case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case (.none, _): print("Nothing") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, .none): print("Nothing", "Nothing") } } enum X { case Empty case A(Int) case B(Int) } func f(a: X, b: X) { switch (a, b) { case (_, .Empty): () case (.Empty, _): () case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () } } func f2(a: X, b: X) { switch (a, b) { case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () case (_, .Empty): () case (.Empty, _): () case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} default: () } } enum XX : Int { case A case B case C case D case E } func switcheroo(a: XX, b: XX) -> Int { switch(a, b) { // No warning case (.A, _) : return 1 case (_, .A) : return 2 case (.C, _) : return 3 case (_, .C) : return 4 case (.B, .B) : return 5 case (.B, .D) : return 6 case (.D, .B) : return 7 case (.B, .E) : return 8 case (.E, .B) : return 9 case (.E, _) : return 10 case (_, .E) : return 11 case (.D, .D) : return 12 default: print("never hits this:", a, b) return 13 } } enum PatternCasts { case one(Any) case two case three(String) } func checkPatternCasts() { // Pattern casts with this structure shouldn't warn about duplicate cases. let x: PatternCasts = .one("One") switch x { case .one(let s as String): print(s) case .one: break case .two: break case .three: break } // But should warn here. switch x { case .one(_): print(s) case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case .two: break case .three: break } // And not here switch x { case .one: break case .two: break case .three(let s as String?): print(s as Any) } } enum MyNever {} func ~= (_ : MyNever, _ : MyNever) -> Bool { return true } func myFatalError() -> MyNever { fatalError() } @_frozen public enum UninhabitedT4<A> { case x(A) } func checkUninhabited() { // Scrutinees of uninhabited type may match any number and kind of patterns // that Sema is willing to accept at will. After all, it's quite a feat to // productively inhabit the type of crashing programs. func test1(x : Never) { switch x {} // No diagnostic. } func test2(x : Never) { switch (x, x) {} // No diagnostic. } func test3(x : MyNever) { switch x { // No diagnostic. case myFatalError(): break case myFatalError(): break case myFatalError(): break } } func test4(x: UninhabitedT4<Never>) { switch x {} // No diagnostic. } } enum Runcible { case spoon case hat case fork } func checkDiagnosticMinimality(x: Runcible?) { switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .hat)'}} // expected-note@-3 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.spoon, .hat): break case (.hat, .spoon): break } switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .spoon)'}} // expected-note@-3 {{add missing case: '(.spoon, .hat)'}} // expected-note@-4 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.hat, .hat): break } } enum LargeSpaceEnum { case case0 case case1 case case2 case case3 case case4 case case5 case case6 case case7 case case8 case case9 case case10 } func notQuiteBigEnough() -> Bool { switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}} // expected-note@-1 110 {{add missing case:}} case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case (.case4, .case4): return true case (.case5, .case5): return true case (.case6, .case6): return true case (.case7, .case7): return true case (.case8, .case8): return true case (.case9, .case9): return true case (.case10, .case10): return true } } enum OverlyLargeSpaceEnum { case case0 case case1 case case2 case case3 case case4 case case5 case case6 case case7 case case8 case case9 case case10 case case11 } enum ContainsOverlyLargeEnum { case one(OverlyLargeSpaceEnum) case two(OverlyLargeSpaceEnum) case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum) } func quiteBigEnough() -> Bool { switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} // expected-note@-1 {{do you want to add a default clause?}} case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case (.case4, .case4): return true case (.case5, .case5): return true case (.case6, .case6): return true case (.case7, .case7): return true case (.case8, .case8): return true case (.case9, .case9): return true case (.case10, .case10): return true case (.case11, .case11): return true } switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} // expected-note@-1 {{do you want to add a default clause?}} case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true } switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true @unknown default: return false // expected-note {{remove '@unknown' to handle remaining values}} {{3-12=}} } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true case (.case11, _): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (_, .case0): return true case (_, .case1): return true case (_, .case2): return true case (_, .case3): return true case (_, .case4): return true case (_, .case5): return true case (_, .case6): return true case (_, .case7): return true case (_, .case8): return true case (_, .case9): return true case (_, .case10): return true case (_, .case11): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (_, _): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case _: return true } // No diagnostic switch ContainsOverlyLargeEnum.one(.case0) { case .one: return true case .two: return true case .three: return true } // Make sure we haven't just stopped emitting diagnostics. switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}} expected-note {{handle unknown values}} } } indirect enum InfinitelySized { case one case two case recur(InfinitelySized) case mutualRecur(MutuallyRecursive, InfinitelySized) } indirect enum MutuallyRecursive { case one case two case recur(MutuallyRecursive) case mutualRecur(InfinitelySized, MutuallyRecursive) } func infinitelySized() -> Bool { switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } } func diagnoseDuplicateLiterals() { let str = "def" let int = 2 let dbl = 2.5 // No Diagnostics switch str { case "abc": break case "def": break case "ghi": break default: break } switch str { case "abc": break case "def": break // expected-note {{first occurrence of identical literal pattern is here}} case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "ghi": break default: break } switch str { case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}} case "ghi", "jkl": break case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch str { case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ghi": break case "def": break case "abc": break case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someStr() -> String { return "sdlkj" } let otherStr = "ifnvbnwe" switch str { case "sdlkj": break case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}} case someStr(): break case "def": break case otherStr: break case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ifnvbnwe": break case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } // No Diagnostics switch int { case -2: break case -1: break case 0: break case 1: break case 2: break case 3: break default: break } switch int { case -2: break // expected-note {{first occurrence of identical literal pattern is here}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1: break case 2: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3: break default: break } switch int { case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}} case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} case 4, 5: break case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}} // expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3: break case 17: break // expected-note {{first occurrence of identical literal pattern is here}} case 4: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 5: break case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 10: break case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case 3000: break case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}} case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someInt() -> Int { return 0x1234 } let otherInt = 13254 switch int { case 13254: break case 3000: break case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}} case 0x1234: break case someInt(): break case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break case otherInt: break case 230: break default: break } // No Diagnostics switch dbl { case -3.5: break case -2.5: break case -1.5: break case 1.5: break case 2.5: break case 3.5: break default: break } switch dbl { case -3.5: break case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -1.5: break case 1.5: break case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3.5: break default: break } switch dbl { case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch dbl { case 1: break case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 46.2395: break case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 23452.43: break default: break } func someDouble() -> Double { return 324.4523 } let otherDouble = 458.2345 switch dbl { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 1.5: break case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 46.2395: break case someDouble(): break case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case otherDouble: break case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}} case 23452.43: break case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 123453: break case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } } func checkLiteralTuples() { let str1 = "abc" let str2 = "def" let int1 = 23 let int2 = 7 let dbl1 = 4.23 let dbl2 = 23.45 // No Diagnostics switch (str1, str2) { case ("abc", "def"): break case ("def", "ghi"): break case ("ghi", "def"): break case ("abc", "def"): break // We currently don't catch this default: break } // No Diagnostics switch (int1, int2) { case (94, 23): break case (7, 23): break case (94, 23): break // We currently don't catch this case (23, 7): break default: break } // No Diagnostics switch (dbl1, dbl2) { case (543.21, 123.45): break case (543.21, 123.45): break // We currently don't catch this case (23.45, 4.23): break case (4.23, 23.45): break default: break } } func sr6975() { enum E { case a, b } let e = E.b switch e { case .a as E: // expected-warning {{'as' test is always true}} print("a") case .b: // Valid! print("b") case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}} print("second a") } func foo(_ str: String) -> Int { switch str { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{do you want to add a default clause?}} case let (x as Int) as Any: return x } } _ = foo("wtf") } public enum NonExhaustive { case a, b } public enum NonExhaustivePayload { case a(Int), b(Bool) } @_frozen public enum TemporalProxy { case seconds(Int) case milliseconds(Int) case microseconds(Int) case nanoseconds(Int) case never } // Inlinable code is considered "outside" the module and must include a default // case. @inlinable public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.some(_)'}} case .a?: break case .b?: break case nil: break } switch value as Optional { case .a?: break case .b?: break case nil: break @unknown case _: break } // no-warning switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, false)'}} case (.a, _): break case (.b, false): break case (_, true): break } switch (value, flag) { case (.a, _): break case (.b, false): break case (_, true): break @unknown case _: break } // no-warning switch (flag, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(false, _)'}} case (_, .a): break case (false, .b): break case (true, _): break } switch (flag, value) { case (_, .a): break case (false, .b): break case (true, _): break @unknown case _: break } // no-warning switch (value, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, _)'}} case (.a, _), (_, .a): break case (.b, _), (_, .b): break } switch (value, value) { case (.a, _), (_, .a): break case (.b, _), (_, .b): break @unknown case _: break } // no-warning // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } // Test fully-covered switches. switch interval { case .seconds, .milliseconds, .microseconds, .nanoseconds: break case .never: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag { case true: break case false: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag as Optional { case _?: break case nil: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch (flag, value) { case (true, _): break case (false, _): break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } } public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} case .a: break } switch value { // no-warning case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // no-warning case .a?: break case .b?: break case nil: break } switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // no-warning case (.a, _): break case (.b, false): break case (_, true): break } switch (flag, value) { // no-warning case (_, .a): break case (false, .b): break case (true, _): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break @unknown case _: break } // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break } switch payload { // no-warning case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } } enum UnavailableCase { case a case b @available(*, unavailable) case oopsThisWasABadIdea } enum UnavailableCaseOSSpecific { case a case b #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) @available(watchOS, unavailable) case unavailableOnAllTheseApplePlatforms #else @available(*, unavailable) case dummyCaseForOtherPlatforms #endif } enum UnavailableCaseOSIntroduced { case a case b @available(macOS 50, iOS 50, tvOS 50, watchOS 50, *) case notYetIntroduced } func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) { switch x { case .a: break case .b: break } // no-error switch y { case .a: break case .b: break } // no-error switch z { case .a: break case .b: break case .notYetIntroduced: break } // no-error } // The following test used to behave differently when the uninhabited enum was // defined in the same module as the function (as opposed to using Swift.Never). enum NoError {} extension Result where T == NoError { func testUninhabited() { switch self { case .Error(_): break // No .Ok case possible because of the 'NoError'. } switch self { case .Error(_): break case .Ok(_): break // But it's okay to write one. } } }
apache-2.0
642e03d0ee54004dbd75548963c0306a
25.628079
205
0.637869
3.614913
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/Model/User.swift
1
2249
// // User.swift // WISData.JunZheng // // Created by Allen on 16/8/22. // Copyright © 2016 Wisdri. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class User { var username: String? } extension User { class func login(username username: String, password: String, completionHandler: WISValueResponse<String> -> Void) -> Request { let loginURL = BaseURL + "/LogIn?userName=\(username)&passWord=\(password)" return HTTPManager.sharedInstance.request(.POST, loginURL).responseJSON { response in /* * For test print("request is \(response.request)") // original URL request print("response is \(response.response)") // URL response print("data is \(response.data)") // server data print("result is \(response.result)") // result of response serialization */ switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if #available(iOS 9.0, *) { debugPrint("JSON: \(json)") } if json.stringValue == "1" { completionHandler(WISValueResponse(value: username, success: true)) } else { completionHandler(WISValueResponse(success: false, message: "登录失败")) } } case .Failure(let error): debugPrint(error) completionHandler(WISValueResponse(success: false, message: error.localizedDescription + "\n请检查设备的网络设置。")) } } } } extension User { private static let userNameKey = "username" class func obtainRecentUserName() -> String? { guard let userName = NSUserDefaults.standardUserDefaults().objectForKey(userNameKey) as? String else { return nil } return userName != "" ? userName : nil } class func storeRecentUserName(userName: String) -> () { NSUserDefaults.standardUserDefaults().setObject(userName, forKey: userNameKey) } }
mit
d1135976e4af1bcc9779dc87c034649d
33.65625
131
0.567178
4.995495
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/SelfProfile/SelfProfileViewController+SettingsChangeAlert.swift
1
2016
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel import WireSyncEngine extension SelfProfileViewController { @discardableResult func presentUserSettingChangeControllerIfNeeded() -> Bool { if ZMUser.selfUser()?.readReceiptsEnabledChangedRemotely ?? false { let currentValue = ZMUser.selfUser()!.readReceiptsEnabled self.presentReadReceiptsChangedAlert(with: currentValue) return true } else { return false } } fileprivate func presentReadReceiptsChangedAlert(with newValue: Bool) { let title = newValue ? "self.read_receipts_enabled.title".localized : "self.read_receipts_disabled.title".localized let description = "self.read_receipts_description.title".localized let settingsChangedAlert = UIAlertController(title: title, message: description, preferredStyle: .alert) let okAction = UIAlertAction(title: "general.ok".localized, style: .default) { [weak settingsChangedAlert] _ in ZMUserSession.shared()?.perform { ZMUser.selfUser()?.readReceiptsEnabledChangedRemotely = false } settingsChangedAlert?.dismiss(animated: true) } settingsChangedAlert.addAction(okAction) self.present(settingsChangedAlert, animated: true) } }
gpl-3.0
af588c050d56b3e5150d7008dc007251
36.333333
123
0.709325
4.917073
false
false
false
false
horizon-institute/babyface-ios
src/view controllers/DateViewController.swift
1
1802
// // DataViewController.swift // babyface // // Created by Kevin Glover on 16/04/2015. // Copyright (c) 2015 Horizon. All rights reserved. // import Foundation import UIKit class DateViewController: PageViewController { @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var label: UILabel! let calendar = NSCalendar.currentCalendar() let dateFormatter = NSDateFormatter() override init(param: String) { super.init(param: param, nib:"DateView") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() label.text = NSLocalizedString(paramName, comment: paramName) dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .NoStyle let minComponents = NSDateComponents() minComponents.month = -6 datePicker.minimumDate = calendar.dateByAddingComponents(minComponents, toDate: NSDate(), options: []) if paramName == "birthDate" { datePicker.maximumDate = NSDate() } else { let components = NSDateComponents() components.month = 1 datePicker.maximumDate = calendar.dateByAddingComponents(components, toDate: NSDate(), options: []) } } override func viewWillAppear(animated: Bool) { if let dateString = pageController?.parameters[paramName] as? String { if let date = dateFormatter.dateFromString(dateString) { datePicker.date = date } } } override func viewWillDisappear(animated: Bool) { pageController?.parameters[paramName] = dateFormatter.stringFromDate(datePicker.date) if paramName == "birthDate" { let today = NSDate() let components = calendar.components(.Day, fromDate: datePicker.date, toDate: today, options: []) pageController?.parameters["age"] = "\(components.day) days" } } }
gpl-3.0
4baa957c5351d680f286fa34abad5362
21.822785
104
0.716981
3.917391
false
false
false
false
joerocca/GitHawk
Classes/Issues/IssueViewModels.swift
1
3870
// // IssueViewModels.swift // Freetime // // Created by Ryan Nystrom on 5/19/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit func titleStringSizing(title: String, width: CGFloat) -> NSAttributedStringSizing { let attributedString = NSAttributedString( string: title, attributes: [ NSAttributedStringKey.font: Styles.Fonts.headline, NSAttributedStringKey.foregroundColor: Styles.Colors.Gray.dark.color ]) return NSAttributedStringSizing( containerWidth: width, attributedText: attributedString, inset: IssueTitleCell.inset, backgroundColor: Styles.Colors.background ) } func createIssueReactions(reactions: ReactionFields) -> IssueCommentReactionViewModel { var models = [ReactionViewModel]() for group in reactions.reactionGroups ?? [] { // do not display reactions for 0 count let count = group.users.totalCount guard count > 0 else { continue } let nodes: [String] = { guard let filtered = group.users.nodes?.filter({ $0?.login != nil }) as? [ReactionFields.ReactionGroup.User.Node] else { return [] } return filtered.map({ $0.login }) }() models.append(ReactionViewModel(content: group.content, count: count, viewerDidReact: group.viewerHasReacted, users: nodes)) } return IssueCommentReactionViewModel(models: models) } func commentModelOptions(owner: String, repo: String) -> GitHubMarkdownOptions { return GitHubMarkdownOptions(owner: owner, repo: repo, flavors: [.issueShorthand, .usernames]) } func createCommentModel( id: String, commentFields: CommentFields, reactionFields: ReactionFields, width: CGFloat, owner: String, repo: String, threadState: IssueCommentModel.ThreadState, viewerCanUpdate: Bool, viewerCanDelete: Bool, isRoot: Bool ) -> IssueCommentModel? { guard let author = commentFields.author, let date = GithubAPIDateFormatter().date(from: commentFields.createdAt), let avatarURL = URL(string: author.avatarUrl) else { return nil } let editedAt: Date? = { guard let editedDate = commentFields.lastEditedAt else { return nil } return GithubAPIDateFormatter().date(from: editedDate) }() let details = IssueCommentDetailsViewModel( date: date, login: author.login, avatarURL: avatarURL, didAuthor: commentFields.viewerDidAuthor, editedBy: commentFields.editor?.login, editedAt: editedAt ) let options = commentModelOptions(owner: owner, repo: repo) let bodies = CreateCommentModels( markdown: commentFields.body, width: width, options: options, viewerCanUpdate: viewerCanUpdate ) let reactions = createIssueReactions(reactions: reactionFields) let collapse = IssueCollapsedBodies(bodies: bodies, width: width) return IssueCommentModel( id: id, details: details, bodyModels: bodies, reactions: reactions, collapse: collapse, threadState: threadState, rawMarkdown: commentFields.body, viewerCanUpdate: viewerCanUpdate, viewerCanDelete: viewerCanDelete, isRoot: isRoot, number: GraphQLIDDecode(id: id, separator: "IssueComment") ) } func createAssigneeModel(assigneeFields: AssigneeFields) -> IssueAssigneesModel { var models = [IssueAssigneeViewModel]() for node in assigneeFields.assignees.nodes ?? [] { guard let node = node, let url = URL(string: node.avatarUrl) else { continue } models.append(IssueAssigneeViewModel(login: node.login, avatarURL: url)) } return IssueAssigneesModel(users: models, type: .assigned) }
mit
edb92797a147ddcd5c4a18268bb9ef12
32.068376
132
0.670974
4.695388
false
false
false
false
embryoconcepts/TIY-Assignments
09 -- Calculator/Calculator/Calculator/CalculatorViewController.swift
1
1587
// // ViewController.swift // Calculator // // Created by Jennifer Hamilton on 10/15/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class CalculatorViewController: UIViewController { @IBOutlet weak var displayLabel: UILabel! var calculator = CalculatorBrain() // var finalAnswer: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Action Handler @IBAction func numberButton(sender: UIButton) { calculator.setDigit(sender.currentTitle!) displayLabel.text = "\(calculator.getFullNumber())" } @IBAction func operatorButton(sender: UIButton) { calculator.setOperator(calculator.getFullNumber()) calculator.setSymbol(sender.currentTitle!) displayLabel.text = "\(sender.currentTitle!)" } @IBAction func specialButton(sender: UIButton) { displayLabel.text = calculator.setSpecialButton(sender.currentTitle!) } @IBAction func equalsButton(sender: UIButton) { calculator.setOperator(calculator.getFullNumber()) displayLabel.text = "\(calculator.calculate())" calculator.clearCalculator() } @IBAction func clearbutton(sender: UIButton) { calculator.clearCalculator() displayLabel.text = "0" } }
cc0-1.0
828eb12643fb9b671b6859dc452ee08c
23.78125
80
0.657629
4.791541
false
false
false
false
shmidt/GooglePlacesSearchController
Example/GooglePlacesSearchController/ViewController.swift
1
1695
// // ViewController.swift // GooglePlacesSearchController // // Created by Dmitry Shmidt on 6/28/15. // Copyright (c) 2015 Dmitry Shmidt. All rights reserved. // import UIKit import CoreLocation import MapKit import GooglePlacesSearchController class ViewController: UIViewController { let GoogleMapsAPIServerKey = "YOUR_KEY" lazy var placesSearchController: GooglePlacesSearchController = { let controller = GooglePlacesSearchController(delegate: self, apiKey: GoogleMapsAPIServerKey, placeType: .address // Optional: coordinate: CLLocationCoordinate2D(latitude: 55.751244, longitude: 37.618423), // Optional: radius: 10, // Optional: strictBounds: true, // Optional: searchBarPlaceholder: "Start typing..." ) //Optional: controller.searchBar.isTranslucent = false //Optional: controller.searchBar.barStyle = .black //Optional: controller.searchBar.tintColor = .white //Optional: controller.searchBar.barTintColor = .black return controller }() @IBAction func searchAddress(_ sender: UIBarButtonItem) { present(placesSearchController, animated: true, completion: nil) } } extension ViewController: GooglePlacesAutocompleteViewControllerDelegate { func viewController(didAutocompleteWith place: PlaceDetails) { print(place.description) placesSearchController.isActive = false } func viewController(didManualCompleteWith text: String) { print(text) placesSearchController.isActive = false } }
mit
b08c1228ab304eb8e817c702abb00774
34.3125
103
0.663127
5.380952
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+WebViewDelegates.swift
2
34777
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared import Photos private let log = Logger.browserLogger /// List of schemes that are allowed to be opened in new tabs. private let schemesAllowedToBeOpenedAsPopups = ["http", "https", "javascript", "data", "about"] extension BrowserViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { guard let parentTab = tabManager[webView] else { return nil } guard !navigationAction.isInternalUnprivileged, shouldRequestBeOpenedAsPopup(navigationAction.request) else { print("Denying popup from request: \(navigationAction.request)") return nil } if let currentTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(currentTab) } guard let bvc = parentTab.browserViewController else { return nil } // If the page uses `window.open()` or `[target="_blank"]`, open the page in a new tab. // IMPORTANT!!: WebKit will perform the `URLRequest` automatically!! Attempting to do // the request here manually leads to incorrect results!! let newTab = tabManager.addPopupForParentTab(bvc: bvc, parentTab: parentTab, configuration: configuration) return newTab.webView } fileprivate func shouldRequestBeOpenedAsPopup(_ request: URLRequest) -> Bool { // Treat `window.open("")` the same as `window.open("about:blank")`. if request.url?.absoluteString.isEmpty ?? false { return true } if let scheme = request.url?.scheme?.lowercased(), schemesAllowedToBeOpenedAsPopups.contains(scheme) { return true } return false } fileprivate func shouldDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool { // Only display a JS Alert if we are selected and there isn't anything being shown return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler) if shouldDisplayJSAlertForWebView(webView) { present(messageAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(messageAlert) } else { // This should never happen since an alert needs to come from a web view but just in case call the handler // since not calling it will result in a runtime exception. completionHandler() } } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler) if shouldDisplayJSAlertForWebView(webView) { present(confirmAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(confirmAlert) } else { completionHandler(false) } } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText) if shouldDisplayJSAlertForWebView(webView) { present(textInputAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(textInputAlert) } else { completionHandler(nil) } } func webViewDidClose(_ webView: WKWebView) { if let tab = tabManager[webView] { // Need to wait here in case we're waiting for a pending `window.open()`. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { self.tabManager.removeTabAndUpdateSelectedIndex(tab) } } } @available(iOS 13.0, *) func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) { completionHandler(UIContextMenuConfiguration(identifier: nil, previewProvider: { guard let url = elementInfo.linkURL, self.profile.prefs.boolForKey(PrefsKeys.ContextMenuShowLinkPreviews) ?? true else { return nil } let previewViewController = UIViewController() previewViewController.view.isUserInteractionEnabled = false let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration) previewViewController.view.addSubview(clonedWebView) clonedWebView.snp.makeConstraints { make in make.edges.equalTo(previewViewController.view) } clonedWebView.load(URLRequest(url: url)) return previewViewController }, actionProvider: { (suggested) -> UIMenu? in guard let url = elementInfo.linkURL, let currentTab = self.tabManager.selectedTab, let contextHelper = currentTab.getContentScript(name: ContextMenuHelper.name()) as? ContextMenuHelper, let elements = contextHelper.elements else { return nil } let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu"]) guard !self.topTabsVisible else { return } var toastLabelText: String if isPrivate { toastLabelText = Strings.ContextMenuButtonToastNewPrivateTabOpenedLabelText } else { toastLabelText = Strings.ContextMenuButtonToastNewTabOpenedLabelText } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: toastLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } let getImageData = { (_ url: URL, success: @escaping (Data) -> Void) in makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.default).dataTask(with: url) { (data, response, error) in if let _ = validatedHTTPResponse(response, statusCode: 200..<300), let data = data { success(data) } }.resume() } var actions = [UIAction]() if !isPrivate { actions.append(UIAction(title: Strings.ContextMenuOpenInNewTab, image: UIImage.templateImageNamed("menu-NewTab"), identifier: UIAction.Identifier(rawValue: "linkContextMenu.openInNewTab")) {_ in addTab(url, false) }) } actions.append(UIAction(title: Strings.ContextMenuOpenInNewPrivateTab, image: UIImage.templateImageNamed("menu-NewPrivateTab"), identifier: UIAction.Identifier("linkContextMenu.openInNewPrivateTab")) { _ in addTab(url, true) }) actions.append(UIAction(title: Strings.ContextMenuBookmarkLink, image: UIImage.templateImageNamed("menu-Bookmark"), identifier: UIAction.Identifier("linkContextMenu.bookmarkLink")) { _ in self.addBookmark(url: url.absoluteString, title: elements.title) SimpleToast().showAlertWithText(Strings.AppMenuAddBookmarkConfirmMessage, bottomContainer: self.webViewContainer) UnifiedTelemetry.recordEvent(category: .action, method: .add, object: .bookmark, value: .contextMenu) }) actions.append(UIAction(title: Strings.ContextMenuDownloadLink, image: UIImage.templateImageNamed("menu-panel-Downloads"), identifier: UIAction.Identifier("linkContextMenu.download")) {_ in self.pendingDownloadWebView = currentTab.webView DownloadContentScript.requestDownload(url: url, tab: currentTab) }) actions.append(UIAction(title: Strings.ContextMenuCopyLink, image: UIImage.templateImageNamed("menu-Copy-Link"), identifier: UIAction.Identifier("linkContextMenu.copyLink")) { _ in UIPasteboard.general.url = url }) actions.append(UIAction(title: Strings.ContextMenuShareLink, image: UIImage.templateImageNamed("action_share"), identifier: UIAction.Identifier("linkContextMenu.share")) { _ in guard let tab = self.tabManager[webView], let helper = tab.getContentScript(name: ContextMenuHelper.name()) as? ContextMenuHelper else { return } // This is only used on ipad for positioning the popover. On iPhone it is an action sheet. let p = webView.convert(helper.touchPoint, to: self.view) self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: p, size: CGSize(width: 10, height: 10)), arrowDirection: .unknown) }) if let url = elements.image { let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() actions.append(UIAction(title: Strings.ContextMenuSaveImage, identifier: UIAction.Identifier("linkContextMenu.saveImage")) { _ in let handlePhotoLibraryAuthorized = { DispatchQueue.main.async { getImageData(url) { data in PHPhotoLibrary.shared().performChanges({ PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil) }) } } } let handlePhotoLibraryDenied = { DispatchQueue.main.async { let accessDenied = UIAlertController(title: Strings.PhotoLibraryFirefoxWouldLikeAccessTitle, message: Strings.PhotoLibraryFirefoxWouldLikeAccessMessage, preferredStyle: .alert) let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: Strings.OpenSettingsString, style: .default ) { _ in UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } if photoAuthorizeStatus == .notDetermined { PHPhotoLibrary.requestAuthorization({ status in guard status == .authorized else { handlePhotoLibraryDenied() return } handlePhotoLibraryAuthorized() }) } else if photoAuthorizeStatus == .authorized { handlePhotoLibraryAuthorized() } else { handlePhotoLibraryDenied() } }) actions.append(UIAction(title: Strings.ContextMenuCopyImage, identifier: UIAction.Identifier("linkContextMenu.copyImage")) { _ in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0) taskId = application.beginBackgroundTask (expirationHandler: { application.endBackgroundTask(taskId) }) makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.default).dataTask(with: url) { (data, response, error) in guard let _ = validatedHTTPResponse(response, statusCode: 200..<300) else { application.endBackgroundTask(taskId) return } // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = data, error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) }.resume() }) actions.append(UIAction(title: Strings.ContextMenuCopyImageLink, identifier: UIAction.Identifier("linkContextMenu.copyImageLink")) { _ in UIPasteboard.general.url = url as URL }) } return UIMenu(title: url.absoluteString, children: actions) })) } } extension WKNavigationAction { /// Allow local requests only if the request is privileged. var isInternalUnprivileged: Bool { guard let url = request.url else { return true } if let url = InternalURL(url) { return !url.isAuthorized } else { return false } } } extension BrowserViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } updateFindInPageVisibility(visible: false) // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.url { if !url.isReaderModeURL { urlBar.updateReaderModeState(ReaderModeState.unavailable) hideReaderModeBar(animated: false) } } } // Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise // it could just be a visit to a regular page on maps.apple.com. fileprivate func isAppleMapsURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" { if url.host == "maps.apple.com" && url.query != nil { return true } } return false } // Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com // used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case // them then iOS will actually first open Safari, which then redirects to the app store. This works but it will // leave a 'Back to Safari' button in the status bar, which we do not want. fileprivate func isStoreURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" || url.scheme == "itms-apps" { if url.host == "itunes.apple.com" { return true } } return false } // Use for sms and mailto links, which do not show a confirmation before opening. fileprivate func showSnackbar(forExternalUrl url: URL, tab: Tab, completion: @escaping (Bool) -> ()) { let snackBar = TimerSnackBar(text: Strings.ExternalLinkGenericConfirmation + "\n\(url.absoluteString)", img: nil) let ok = SnackButton(title: Strings.OKString, accessibilityIdentifier: "AppOpenExternal.button.ok") { bar in tab.removeSnackbar(bar) completion(true) } let cancel = SnackButton(title: Strings.CancelString, accessibilityIdentifier: "AppOpenExternal.button.cancel") { bar in tab.removeSnackbar(bar) completion(false) } snackBar.addButton(ok) snackBar.addButton(cancel) tab.addSnackbar(snackBar) } // This is the place where we decide what to do with a new navigation action. There are a number of special schemes // and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate // method. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url, let tab = tabManager[webView] else { decisionHandler(.cancel) return } if InternalURL.isValid(url: url) { if navigationAction.navigationType != .backForward, navigationAction.isInternalUnprivileged { log.warning("Denying unprivileged request: \(navigationAction.request)") decisionHandler(.cancel) return } decisionHandler(.allow) return } // First special case are some schemes that are about Calling. We prompt the user to confirm this action. This // gives us the exact same behaviour as Safari. if ["sms", "tel", "facetime", "facetime-audio"].contains(url.scheme) { if url.scheme == "sms" { // All the other types show a native prompt showSnackbar(forExternalUrl: url, tab: tab) { isOk in guard isOk else { return } UIApplication.shared.open(url, options: [:]) } } else { UIApplication.shared.open(url, options: [:]) } decisionHandler(.cancel) return } if url.scheme == "about" { decisionHandler(.allow) return } // Disabled due to https://bugzilla.mozilla.org/show_bug.cgi?id=1588928 // if url.scheme == "javascript", navigationAction.request.isPrivileged { // decisionHandler(.cancel) // if let javaScriptString = url.absoluteString.replaceFirstOccurrence(of: "javascript:", with: "").removingPercentEncoding { // webView.evaluateJavaScript(javaScriptString) // } // return // } // Second special case are a set of URLs that look like regular http links, but should be handed over to iOS // instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because // iOS will always say yes. if isAppleMapsURL(url) { UIApplication.shared.open(url, options: [:]) decisionHandler(.cancel) return } if isStoreURL(url) { decisionHandler(.cancel) // Make sure to wait longer than delaySelectingNewPopupTab to ensure selectedTab is correct DispatchQueue.main.asyncAfter(deadline: .now() + tabManager.delaySelectingNewPopupTab + 0.1) { guard let tab = self.tabManager.selectedTab else { return } if tab.bars.isEmpty { // i.e. no snackbars are showing TimerSnackBar.showAppStoreConfirmationBar(forTab: tab, appStoreURL: url) { _ in // If a new window was opened for this URL (it will have no history), close it. if tab.historyList.isEmpty { self.tabManager.removeTabAndUpdateSelectedIndex(tab) } } } } return } // Handles custom mailto URL schemes. if url.scheme == "mailto" { showSnackbar(forExternalUrl: url, tab: tab) { isOk in guard isOk else { return } if let mailToMetadata = url.mailToMetadata(), let mailScheme = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), mailScheme != "mailto" { self.mailtoLinkHandler.launchMailClientForScheme(mailScheme, metadata: mailToMetadata, defaultMailtoURL: url) } else { UIApplication.shared.open(url, options: [:]) } LeanPlumClient.shared.track(event: .openedMailtoLink) } decisionHandler(.cancel) return } // https://blog.mozilla.org/security/2017/11/27/blocking-top-level-navigations-data-urls-firefox-59/ if url.scheme == "data" { let url = url.absoluteString // Allow certain image types if url.hasPrefix("data:image/") && !url.hasPrefix("data:image/svg+xml") { decisionHandler(.allow) return } // Allow video, and certain application types if url.hasPrefix("data:video/") || url.hasPrefix("data:application/pdf") || url.hasPrefix("data:application/json") { decisionHandler(.allow) return } // Allow plain text types. // Note the format of data URLs is `data:[<media type>][;base64],<data>` with empty <media type> indicating plain text. if url.hasPrefix("data:;base64,") || url.hasPrefix("data:,") || url.hasPrefix("data:text/plain,") || url.hasPrefix("data:text/plain;") { decisionHandler(.allow) return } decisionHandler(.cancel) return } // This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We // always allow this. Additionally, data URIs are also handled just like normal web pages. if ["http", "https", "blob", "file"].contains(url.scheme) { if navigationAction.targetFrame?.isMainFrame ?? false { tab.changedUserAgent = Tab.ChangeUserAgent.contains(url: url) } pendingRequests[url.absoluteString] = navigationAction.request if tab.changedUserAgent { let platformSpecificUserAgent = UserAgent.oppositeUserAgent(domain: url.baseDomain ?? "") webView.customUserAgent = platformSpecificUserAgent } else { webView.customUserAgent = UserAgent.getUserAgent(domain: url.baseDomain ?? "") } decisionHandler(.allow) return } if !(url.scheme?.contains("firefox") ?? true) { showSnackbar(forExternalUrl: url, tab: tab) { isOk in guard isOk else { return } UIApplication.shared.open(url, options: [:]) { openedURL in // Do not show error message for JS navigated links or redirect as it's not the result of a user action. if !openedURL, navigationAction.navigationType == .linkActivated { let alert = UIAlertController(title: Strings.UnableToOpenURLErrorTitle, message: Strings.UnableToOpenURLError, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.OKString, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } decisionHandler(.cancel) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let response = navigationResponse.response let responseURL = response.url var request: URLRequest? if let url = responseURL { request = pendingRequests.removeValue(forKey: url.absoluteString) } // We can only show this content in the web view if this web view is not pending // download via the context menu. let canShowInWebView = navigationResponse.canShowMIMEType && (webView != pendingDownloadWebView) let forceDownload = webView == pendingDownloadWebView // Check if this response should be handed off to Passbook. if let passbookHelper = OpenPassBookHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) { // Clear the network activity indicator since our helper is handling the request. UIApplication.shared.isNetworkActivityIndicatorVisible = false // Open our helper and cancel this response from the webview. passbookHelper.open() decisionHandler(.cancel) return } if #available(iOS 12.0, *) { // Check if this response should be displayed in a QuickLook for USDZ files. if let previewHelper = OpenQLPreviewHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) { // Certain files are too large to download before the preview presents, block and use a temporary document instead if let tab = tabManager[webView] { if navigationResponse.isForMainFrame, response.mimeType != MIMEType.HTML, let request = request { tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request) previewHelper.url = tab.temporaryDocument!.getURL().value as NSURL // Open our helper and cancel this response from the webview. previewHelper.open() decisionHandler(.cancel) return } else { tab.temporaryDocument = nil } } // We don't have a temporary document, fallthrough } } // Check if this response should be downloaded. if let downloadHelper = DownloadHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) { // Clear the network activity indicator since our helper is handling the request. UIApplication.shared.isNetworkActivityIndicatorVisible = false // Clear the pending download web view so that subsequent navigations from the same // web view don't invoke another download. pendingDownloadWebView = nil // Open our helper and cancel this response from the webview. downloadHelper.open() decisionHandler(.cancel) return } // If the content type is not HTML, create a temporary document so it can be downloaded and // shared to external applications later. Otherwise, clear the old temporary document. // NOTE: This should only happen if the request/response came from the main frame, otherwise // we may end up overriding the "Share Page With..." action to share a temp file that is not // representative of the contents of the web view. if navigationResponse.isForMainFrame, let tab = tabManager[webView] { if response.mimeType != MIMEType.HTML, let request = request { tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request) } else { tab.temporaryDocument = nil } tab.mimeType = response.mimeType } // If none of our helpers are responsible for handling this response, // just let the webview handle it as normal. decisionHandler(.allow) } /// Invoked when an error occurs while starting to load data for the main frame. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) { return } if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { if let tab = tabManager[webView], tab === tabManager.selectedTab { urlBar.currentURL = tab.url?.displayURL } return } if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL { ErrorPageHelper(certStore: profile.certStore).loadPage(error, forUrl: url, inWebView: webView) } } fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool { if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { print("WebContent process has crashed. Trying to reload to restart it.") webView.reload() return true } return false } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // If this is a certificate challenge, see if the certificate has previously been // accepted by the user. let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)" if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust, let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) { completionHandler(.useCredential, URLCredential(trust: trust)) return } guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM, let tab = tabManager[webView] else { completionHandler(.performDefaultHandling, nil) return } // If this is a request to our local web server, use our private credentials. if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) { completionHandler(.useCredential, WebServer.sharedInstance.credentials) return } // The challenge may come from a background tab, so ensure it's the one visible. tabManager.selectTab(tab) let loginsHelper = tab.getContentScript(name: LoginsHelper.name()) as? LoginsHelper Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(.main) { res in if let credentials = res.successValue { completionHandler(.useCredential, credentials.credentials) } else { completionHandler(.rejectProtectionSpace, nil) } } } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { guard let tab = tabManager[webView] else { return } tab.url = webView.url // When tab url changes after web content starts loading on the page // We notify the contect blocker change so that content blocker status can be correctly shown on beside the URL bar tab.contentBlocker?.notifyContentBlockingChanged() self.scrollController.resetZoomState() if tabManager.selectedTab === tab { updateUIForReaderHomeStateForTab(tab) } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if let tab = tabManager[webView] { navigateInTab(tab: tab, to: navigation) // If this tab had previously crashed, wait 5 seconds before resetting // the consecutive crash counter. This allows a successful webpage load // without a crash to reset the consecutive crash counter in the event // that the tab begins crashing again in the future. if tab.consecutiveCrashes > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) { if tab.consecutiveCrashes > 0 { tab.consecutiveCrashes = 0 } } } } } }
mpl-2.0
ca3fbdec264b34663611ba7337ed0e70
49.328509
218
0.6211
5.596556
false
false
false
false
ypopovych/Boilerplate
Package.swift
1
952
//===--- Package.swift -----------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import PackageDescription let package = Package( name: "Boilerplate", dependencies: [ .Package(url: "https://github.com/antitypical/Result.git", majorVersion: 3, minor: 1) ] )
apache-2.0
a22bf0f22fa8e9d3754d0ad5d008540b
38.666667
93
0.622899
4.712871
false
false
false
false
QuStudio/Vocabulaire
Sources/Vocabulaire/Morpheme/Morpheme.swift
1
2965
// // GeneralWord.swift // Vocabulaire // // Created by Oleg Dreyman on 22.03.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // import Foundation /// Represents Morpheme (aka Word) type. /// - Note: In linguistics, a morpheme is the smallest grammatical unit in a language. In other words, it is the smallest meaningful unit of a language. - Wikipedia public struct Morpheme { /// Private storage for string which was passed to initializaer. private let string: String /// Type of Morpheme. /// - Note: see Kind for details. public let type: Kind #if swift(>=3.0) public init(_ value: String, type: Kind = .general) { self.type = type switch type { case .general: self.string = value.lowercased() case .caseSensitive: self.string = value } } #else /// Creates morpheme for given string with choosen type. public init(_ value: String, type: Kind = .General) { self.type = type switch type { case .General: self.string = value.lowercaseString case .CaseSensitive: self.string = value } } #endif /// String representation of morpheme. /// - Warning: general morpheme will always produce capitalized string. ("менеджер" -> "Менеджер") public var view: String { #if swift(>=3.0) switch type { case .general: #if os(Linux) return string.capitalizedString #else return string.capitalized #endif case .caseSensitive: return string } #else switch type { case .General: return string.capitalizedString case .CaseSensitive: return string } #endif } /// Type of morpheme public enum Kind { #if swift(>=3.0) case general, caseSensitive #else /// Doesn't care about how it's written case General /// Do care about how it's written case CaseSensitive #endif } } // Extension to support StringLiteralConvertible protocol. extension Morpheme: StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(value) } public init(unicodeScalarLiteral value: String) { self.init(value) } } extension Morpheme: CustomStringConvertible { public var description: String { return view } } extension Morpheme: Hashable { public var hashValue: Int { return string.hashValue } } public func == (left: Morpheme, right: Morpheme) -> Bool { //return left.view == right.view && left.type == right.type return left.type == right.type && left.view == right.view }
mit
e666d990bc24c68c0eb3042bfc7701b0
23.983051
164
0.592944
4.63522
false
false
false
false
Ryan-Vanderhoef/Antlers
AppIdea/Models/MyPFSignUpViewController.swift
1
1755
// // MyPFSignUpViewController.swift // AppIdea // // Created by Ryan Vanderhoef on 7/29/15. // Copyright (c) 2015 Ryan Vanderhoef. All rights reserved. // import UIKit import Parse import ParseUI class MyPFSignUpViewController: PFSignUpViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 130/255, green: 207/255, blue: 253/255, alpha: 1.0) //UIColor.lightGrayColor() //UIColor(red: 192/255, green: 54/255, blue: 44/255, alpha: 1) // Do any additional setup after loading the view. let logoView = UIImageView(image: UIImage(named:"AntlerLogo")) self.signUpView!.logo = logoView // var passwordLabel = UILabel() // // passwordLabel.text = "Password Must Be 8+ Characters" // passwordLabel.sizeToFit() // passwordLabel.font = UIFont(name: "Helvetica Neue", size: 11) // passwordLabel.textAlignment = NSTextAlignment.Center // passwordLabel.textColor = UIColor.whiteColor() // // self.view.addSubview(passwordLabel) // // // passwordLabel.center = CGPointMake(100, 200) //// passwordLabel.ce } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
5ca929ab1e944c8dfa70585511af02c0
30.909091
190
0.651852
4.523196
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDKExamples/MercadoPagoSDKExamples/AdvancedVaultViewController.swift
1
10157
// // AdvancedVaultViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 3/2/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import Foundation import MercadoPagoSDK class AdvancedVaultViewController : SimpleVaultViewController { @IBOutlet weak var installmentsCell : MPInstallmentsTableViewCell! var payerCosts : [PayerCost]? var selectedPayerCost : PayerCost? = nil var amount : Double = 0 var selectedIssuer : Issuer? = nil var advancedCallback : ((paymentMethod: PaymentMethod, token: String?, issuerId: NSNumber?, installments: Int) -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(merchantPublicKey: String, merchantBaseUrl: String, merchantGetCustomerUri: String, merchantAccessToken: String, amount: Double, supportedPaymentTypes: [String], callback: ((paymentMethod: PaymentMethod, token: String?, issuerId: NSNumber?, installments: Int) -> Void)?) { super.init(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, supportedPaymentTypes: supportedPaymentTypes, callback: nil) advancedCallback = callback self.amount = amount } override func getSelectionCallbackPaymentMethod() -> (paymentMethod : PaymentMethod) -> Void { return { (paymentMethod : PaymentMethod) -> Void in self.selectedCard = nil self.selectedPaymentMethod = paymentMethod if paymentMethod.settings != nil && paymentMethod.settings.count > 0 { self.securityCodeLength = paymentMethod.settings![0].securityCode!.length self.securityCodeRequired = self.securityCodeLength != 0 } let newCardViewController = MercadoPago.startNewCardViewController(MercadoPago.PUBLIC_KEY, key: ExamplesUtils.MERCHANT_PUBLIC_KEY, paymentMethod: self.selectedPaymentMethod!, requireSecurityCode: self.securityCodeRequired, callback: self.getNewCardCallback()) if self.selectedPaymentMethod!.isIssuerRequired() { let issuerViewController = MercadoPago.startIssuersViewController(ExamplesUtils.MERCHANT_PUBLIC_KEY, paymentMethod: self.selectedPaymentMethod!, callback: { (issuer: Issuer) -> Void in self.selectedIssuer = issuer self.showViewController(newCardViewController) }) self.showViewController(issuerViewController) } else { self.showViewController(newCardViewController) } } } override func getNewCardCallback() -> (cardToken: CardToken) -> Void { return { (cardToken: CardToken) -> Void in self.selectedCardToken = cardToken self.bin = self.selectedCardToken?.getBin() if self.selectedPaymentMethod!.settings != nil && self.selectedPaymentMethod!.settings.count > 0 { self.securityCodeLength = self.selectedPaymentMethod!.settings![0].securityCode!.length self.securityCodeRequired = self.securityCodeLength != 0 } self.loadPayerCosts() self.navigationController!.popToViewController(self, animated: true) } } override func getCustomerPaymentMethodCallback(paymentMethodsViewController : PaymentMethodsViewController) -> (selectedCard: Card?) -> Void { return {(selectedCard: Card?) -> Void in if selectedCard != nil { self.selectedCard = selectedCard self.selectedPaymentMethod = self.selectedCard?.paymentMethod self.selectedIssuer = self.selectedCard?.issuer self.bin = self.selectedCard?.firstSixDigits self.securityCodeLength = self.selectedCard!.securityCode!.length self.securityCodeRequired = self.securityCodeLength > 0 self.loadPayerCosts() self.navigationController!.popViewControllerAnimated(true) } else { self.showViewController(paymentMethodsViewController) } } } override func declareAndInitCells() { super.declareAndInitCells() let installmentsNib = UINib(nibName: "MPInstallmentsTableViewCell", bundle: MercadoPago.getBundle()) self.tableview.registerNib(installmentsNib, forCellReuseIdentifier: "installmentsCell") self.installmentsCell = self.tableview.dequeueReusableCellWithIdentifier("installmentsCell") as! MPInstallmentsTableViewCell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.selectedCard == nil && self.selectedCardToken == nil { return 1 } else if self.selectedPayerCost == nil { return 2 } else if !securityCodeRequired { return 2 } return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { if (self.selectedCardToken == nil && self.selectedCard == nil) { self.emptyPaymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("emptyPaymentMethodCell") as! MPPaymentMethodEmptyTableViewCell return self.emptyPaymentMethodCell } else { self.paymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("paymentMethodCell") as! MPPaymentMethodTableViewCell if self.selectedCardToken != nil { self.paymentMethodCell.fillWithCardTokenAndPaymentMethod(self.selectedCardToken, paymentMethod: self.selectedPaymentMethod!) } else { self.paymentMethodCell.fillWithCard(self.selectedCard) } return self.paymentMethodCell } } else if indexPath.row == 1 { self.installmentsCell = self.tableview.dequeueReusableCellWithIdentifier("installmentsCell") as! MPInstallmentsTableViewCell self.installmentsCell.fillWithPayerCost(self.selectedPayerCost, amount: self.amount) return self.installmentsCell } else if indexPath.row == 2 { self.securityCodeCell = self.tableview.dequeueReusableCellWithIdentifier("securityCodeCell") as! MPSecurityCodeTableViewCell self.securityCodeCell.fillWithPaymentMethod(self.selectedPaymentMethod!) self.securityCodeCell.securityCodeTextField.delegate = self return self.securityCodeCell } return UITableViewCell() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if (indexPath.row == 2) { return 143 } return 65 } func loadPayerCosts() { self.view.addSubview(self.loadingView) let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) let issuerId = self.selectedIssuer != nil ? self.selectedIssuer!._id : nil mercadoPago.getInstallments(self.bin!, amount: self.amount, issuerId: issuerId, paymentTypeId: self.selectedPaymentMethod!.paymentTypeId!, success: {(installments: [Installment]?) -> Void in if installments != nil { self.payerCosts = installments![0].payerCosts self.tableview.reloadData() self.loadingView.removeFromSuperview() } }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) self.navigationController?.popToRootViewControllerAnimated(true) }) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) } else if indexPath.row == 1 { self.showViewController(MercadoPago.startInstallmentsViewController(payerCosts!, amount: amount, callback: { (payerCost: PayerCost?) -> Void in self.selectedPayerCost = payerCost self.tableview.reloadData() self.navigationController!.popToViewController(self, animated: true) })) } } override func submitForm() { let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) // Create token if selectedCard != nil { let savedCardToken : SavedCardToken = SavedCardToken(cardId: selectedCard!._id.stringValue, securityCode: securityCodeCell.securityCodeTextField.text!) if savedCardToken.validate() { // Send card id to get token id self.view.addSubview(self.loadingView) let installments = self.selectedPayerCost == nil ? 0 : self.selectedPayerCost!.installments mercadoPago.createToken(savedCardToken, success: {(token: Token?) -> Void in self.loadingView.removeFromSuperview() self.advancedCallback!(paymentMethod: self.selectedPaymentMethod!, token: token?._id, issuerId: self.selectedIssuer?._id, installments: installments) }, failure: nil) } else { print("Invalid data") return } } else { self.selectedCardToken!.securityCode = self.securityCodeCell.securityCodeTextField.text self.view.addSubview(self.loadingView) let installments = self.selectedPayerCost == nil ? 0 : self.selectedPayerCost!.installments mercadoPago.createNewCardToken(self.selectedCardToken!, success: {(token: Token?) -> Void in self.loadingView.removeFromSuperview() self.advancedCallback!(paymentMethod: self.selectedPaymentMethod!, token: token?._id, issuerId: self.selectedIssuer?._id, installments: installments) }, failure: nil) } } }
mit
7b63293c8561fadf849976fbe6a143c8
48.55122
281
0.663779
5.797374
false
false
false
false
leberwurstsaft/XLForm
Examples/Swift/Examples/Selectors/SelectorsFormViewController.swift
41
19773
// // SelectorsFormViewController.m // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <MapKit/MapKit.h> #import "CLLocationValueTrasformer.h" #import "MapViewController.h" #import "CustomSelectorsFormViewController.h" #import "DynamicSelectorsFormViewController.h" #import "SelectorsFormViewController.h" NSString *const kSelectorPush = @"selectorPush"; NSString *const kSelectorPopover = @"selectorPopover"; NSString *const kSelectorActionSheet = @"selectorActionSheet"; NSString *const kSelectorAlertView = @"selectorAlertView"; NSString *const kSelectorLeftRight = @"selectorLeftRight"; NSString *const kSelectorPushDisabled = @"selectorPushDisabled"; NSString *const kSelectorActionSheetDisabled = @"selectorActionSheetDisabled"; NSString *const kSelectorLeftRightDisabled = @"selectorLeftRightDisabled"; NSString *const kSelectorPickerView = @"selectorPickerView"; NSString *const kSelectorPickerViewInline = @"selectorPickerViewInline"; NSString *const kMultipleSelector = @"multipleSelector"; NSString *const kMultipleSelectorPopover = @"multipleSelectorPopover"; NSString *const kDynamicSelectors = @"dynamicSelectors"; NSString *const kCustomSelectors = @"customSelectors"; NSString *const kPickerView = @"pickerView"; NSString *const kSelectorWithSegueId = @"selectorWithSegueId"; NSString *const kSelectorWithSegueClass = @"selectorWithSegueClass"; NSString *const kSelectorWithNibName = @"selectorWithNibName"; NSString *const kSelectorWithStoryboardId = @"selectorWithStoryboardId"; #pragma mark - NSValueTransformer @interface NSArrayValueTrasformer : NSValueTransformer @end @implementation NSArrayValueTrasformer + (Class)transformedValueClass { return [NSString class]; } + (BOOL)allowsReverseTransformation { return NO; } - (id)transformedValue:(id)value { if (!value) return nil; if ([value isKindOfClass:[NSArray class]]){ NSArray * array = (NSArray *)value; return [NSString stringWithFormat:@"%@ Item%@", @(array.count), array.count > 1 ? @"s" : @""]; } if ([value isKindOfClass:[NSString class]]) { return [NSString stringWithFormat:@"%@ - ;) - Transformed", value]; } return nil; } @end @interface ISOLanguageCodesValueTranformer : NSValueTransformer @end @implementation ISOLanguageCodesValueTranformer + (Class)transformedValueClass { return [NSString class]; } + (BOOL)allowsReverseTransformation { return NO; } - (id)transformedValue:(id)value { if (!value) return nil; if ([value isKindOfClass:[NSString class]]){ return [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:value]; } return nil; } @end #pragma mark - SelectorsFormViewController @implementation SelectorsFormViewController - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { [self initializeForm]; } return self; } - (instancetype)init { self = [super init]; if (self) { [self initializeForm]; } return self; } - (void)initializeForm { XLFormDescriptor * form = [XLFormDescriptor formDescriptorWithTitle:@"Selectors"]; XLFormSectionDescriptor * section; XLFormRowDescriptor * row; // Basic Information section = [XLFormSectionDescriptor formSectionWithTitle:@"Selectors"]; section.footerTitle = @"SelectorsFormViewController.h"; [form addFormSection:section]; // Selector Push row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorPush rowType:XLFormRowDescriptorTypeSelectorPush title:@"Push"]; row.selectorOptions = @[[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Option 1"], [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"], [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"], [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"], [XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Option 5"] ]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"]; [section addFormRow:row]; // Selector Popover if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){ row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorPopover rowType:XLFormRowDescriptorTypeSelectorPopover title:@"PopOver"]; row.selectorOptions = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.value = @"Option 2"; [section addFormRow:row]; } // Selector Action Sheet row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorActionSheet rowType:XLFormRowDescriptorTypeSelectorActionSheet title:@"Sheet"]; row.selectorOptions = @[[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Option 1"], [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"], [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"], [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"], [XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Option 5"] ]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"]; [section addFormRow:row]; // Selector Alert View row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorAlertView rowType:XLFormRowDescriptorTypeSelectorAlertView title:@"Alert View"]; row.selectorOptions = @[[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Option 1"], [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"], [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"], [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"], [XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Option 5"] ]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"]; [section addFormRow:row]; // Selector Left Right row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorLeftRight rowType:XLFormRowDescriptorTypeSelectorLeftRight title:@"Left Right"]; row.leftRightSelectorLeftOptionSelected = [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"]; NSArray * rightOptions = @[[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Right Option 1"], [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Right Option 2"], [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Right Option 3"], [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Right Option 4"], [XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Right Option 5"] ]; // create right selectors NSMutableArray * leftRightSelectorOptions = [[NSMutableArray alloc] init]; NSMutableArray * mutableRightOptions = [rightOptions mutableCopy]; [mutableRightOptions removeObjectAtIndex:0]; XLFormLeftRightSelectorOption * leftRightSelectorOption = [XLFormLeftRightSelectorOption formLeftRightSelectorOptionWithLeftValue:[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Option 1"] httpParameterKey:@"option_1" rightOptions:mutableRightOptions]; [leftRightSelectorOptions addObject:leftRightSelectorOption]; mutableRightOptions = [rightOptions mutableCopy]; [mutableRightOptions removeObjectAtIndex:1]; leftRightSelectorOption = [XLFormLeftRightSelectorOption formLeftRightSelectorOptionWithLeftValue:[XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"] httpParameterKey:@"option_2" rightOptions:mutableRightOptions]; [leftRightSelectorOptions addObject:leftRightSelectorOption]; mutableRightOptions = [rightOptions mutableCopy]; [mutableRightOptions removeObjectAtIndex:2]; leftRightSelectorOption = [XLFormLeftRightSelectorOption formLeftRightSelectorOptionWithLeftValue:[XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"] httpParameterKey:@"option_3" rightOptions:mutableRightOptions]; [leftRightSelectorOptions addObject:leftRightSelectorOption]; mutableRightOptions = [rightOptions mutableCopy]; [mutableRightOptions removeObjectAtIndex:3]; leftRightSelectorOption = [XLFormLeftRightSelectorOption formLeftRightSelectorOptionWithLeftValue:[XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"] httpParameterKey:@"option_4" rightOptions:mutableRightOptions]; [leftRightSelectorOptions addObject:leftRightSelectorOption]; mutableRightOptions = [rightOptions mutableCopy]; [mutableRightOptions removeObjectAtIndex:4]; leftRightSelectorOption = [XLFormLeftRightSelectorOption formLeftRightSelectorOptionWithLeftValue:[XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Option 5"] httpParameterKey:@"option_5" rightOptions:mutableRightOptions]; [leftRightSelectorOptions addObject:leftRightSelectorOption]; row.selectorOptions = leftRightSelectorOptions; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Right Option 4"]; [section addFormRow:row]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorPickerView rowType:XLFormRowDescriptorTypeSelectorPickerView title:@"Picker View"]; row.selectorOptions = @[[XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:@"Option 1"], [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"], [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"], [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"], [XLFormOptionsObject formOptionsObjectWithValue:@(4) displayText:@"Option 5"] ]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Option 4"]; [section addFormRow:row]; // --------- Fixed Controls section = [XLFormSectionDescriptor formSectionWithTitle:@"Fixed Controls"]; [form addFormSection:section]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kPickerView rowType:XLFormRowDescriptorTypePicker]; row.selectorOptions = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.value = @"Option 1"; [section addFormRow:row]; // --------- Inline Selectors section = [XLFormSectionDescriptor formSectionWithTitle:@"Inline Selectors"]; [form addFormSection:section]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kMultipleSelector rowType:XLFormRowDescriptorTypeSelectorPickerViewInline title:@"Inline Picker View"]; row.selectorOptions = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.value = @"Option 6"; [section addFormRow:row]; // --------- MultipleSelector section = [XLFormSectionDescriptor formSectionWithTitle:@"Multiple Selectors"]; [form addFormSection:section]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kMultipleSelector rowType:XLFormRowDescriptorTypeMultipleSelector title:@"Multiple Selector"]; row.selectorOptions = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.value = @[@"Option 1", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; [section addFormRow:row]; // Multiple selector with value tranformer row = [XLFormRowDescriptor formRowDescriptorWithTag:kMultipleSelector rowType:XLFormRowDescriptorTypeMultipleSelector title:@"Multiple Selector"]; row.selectorOptions = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.value = @[@"Option 1", @"Option 3", @"Option 4", @"Option 5", @"Option 6"]; row.valueTransformer = [NSArrayValueTrasformer class]; [section addFormRow:row]; // Language multiple selector row = [XLFormRowDescriptor formRowDescriptorWithTag:kMultipleSelector rowType:XLFormRowDescriptorTypeMultipleSelector title:@"Multiple Selector"]; row.selectorOptions = [NSLocale ISOLanguageCodes]; row.selectorTitle = @"Languages"; row.valueTransformer = [ISOLanguageCodesValueTranformer class]; row.value = [NSLocale preferredLanguages]; [section addFormRow:row]; if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){ // Language multiple selector popover row = [XLFormRowDescriptor formRowDescriptorWithTag:kMultipleSelectorPopover rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"Multiple Selector PopOver"]; row.selectorOptions = [NSLocale ISOLanguageCodes]; row.valueTransformer = [ISOLanguageCodesValueTranformer class]; row.value = [NSLocale preferredLanguages]; [section addFormRow:row]; } // --------- Dynamic Selectors section = [XLFormSectionDescriptor formSectionWithTitle:@"Dynamic Selectors"]; [form addFormSection:section]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kDynamicSelectors rowType:XLFormRowDescriptorTypeButton title:@"Dynamic Selectors"]; row.action.viewControllerClass = [DynamicSelectorsFormViewController class]; [section addFormRow:row]; // --------- Custom Selectors section = [XLFormSectionDescriptor formSectionWithTitle:@"Custom Selectors"]; [form addFormSection:section]; row = [XLFormRowDescriptor formRowDescriptorWithTag:kCustomSelectors rowType:XLFormRowDescriptorTypeButton title:@"Custom Selectors"]; row.action.viewControllerClass = [CustomSelectorsFormViewController class]; [section addFormRow:row]; section = [XLFormSectionDescriptor formSectionWithTitle:@"Disabled & Required Selectors"]; [form addFormSection:section]; // Disabled Selector Push row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorPushDisabled rowType:XLFormRowDescriptorTypeSelectorPush title:@"Push"]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"]; row.disabled = @YES; [section addFormRow:row]; // --------- Disabled Selector Action Sheet row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorActionSheetDisabled rowType:XLFormRowDescriptorTypeSelectorActionSheet title:@"Sheet"]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(2) displayText:@"Option 3"]; row.disabled = @YES; [section addFormRow:row]; // --------- Disabled Selector Left Right row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorLeftRightDisabled rowType:XLFormRowDescriptorTypeSelectorLeftRight title:@"Left Right"]; row.leftRightSelectorLeftOptionSelected = [XLFormOptionsObject formOptionsObjectWithValue:@(1) displayText:@"Option 2"]; row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(3) displayText:@"Right Option 4"]; row.disabled = @YES; [section addFormRow:row]; // --------- Selector definition types section = [XLFormSectionDescriptor formSectionWithTitle:@"Selectors"]; [form addFormSection:section]; // selector with segue class row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorWithSegueClass rowType:XLFormRowDescriptorTypeSelectorPush title:@"Selector with Segue Class"]; row.action.formSegueClass = NSClassFromString(@"UIStoryboardPushSegue"); row.action.viewControllerClass = [MapViewController class]; row.valueTransformer = [CLLocationValueTrasformer class]; row.value = [[CLLocation alloc] initWithLatitude:-33 longitude:-56]; [section addFormRow:row]; // selector with SegueId row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorWithSegueClass rowType:XLFormRowDescriptorTypeSelectorPush title:@"Selector with Segue Idenfifier"]; row.action.formSegueIdenfifier = @"MapViewControllerSegue"; row.valueTransformer = [CLLocationValueTrasformer class]; row.value = [[CLLocation alloc] initWithLatitude:-33 longitude:-56]; [section addFormRow:row]; // selector using StoryboardId row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorWithStoryboardId rowType:XLFormRowDescriptorTypeSelectorPush title:@"Selector with StoryboardId"]; row.action.viewControllerStoryboardId = @"MapViewController"; row.valueTransformer = [CLLocationValueTrasformer class]; row.value = [[CLLocation alloc] initWithLatitude:-33 longitude:-56]; [section addFormRow:row]; // selector with NibName row = [XLFormRowDescriptor formRowDescriptorWithTag:kSelectorWithNibName rowType:XLFormRowDescriptorTypeSelectorPush title:@"Selector with NibName"]; row.action.viewControllerNibName = @"MapViewController"; row.valueTransformer = [CLLocationValueTrasformer class]; row.value = [[CLLocation alloc] initWithLatitude:-33 longitude:-56]; [section addFormRow:row]; self.form = form; } -(UIStoryboard *)storyboardForRow:(XLFormRowDescriptor *)formRow { return [UIStoryboard storyboardWithName:@"iPhoneStoryboard" bundle:nil]; } -(void)viewDidLoad { [super viewDidLoad]; UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithTitle:@"Disable" style:UIBarButtonItemStylePlain target:self action:@selector(disableEnable:)]; barButton.possibleTitles = [NSSet setWithObjects:@"Disable", @"Enable", nil]; self.navigationItem.rightBarButtonItem = barButton; } -(void)disableEnable:(UIBarButtonItem *)button { self.form.disabled = !self.form.disabled; [button setTitle:(self.form.disabled ? @"Enable" : @"Disable")]; [self.tableView endEditing:YES]; [self.tableView reloadData]; } @end
mit
28f0ac68fcb778eb3bbfaa7c7d45cebe
46.645783
275
0.721843
6.078389
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/ViewModels/LikesViewModel.swift
1
3144
// // LikesViewModel.swift // Inbbbox // // Created by Aleksander Popko on 29.02.2016. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import PromiseKit class LikesViewModel: SimpleShotsViewModel { weak var delegate: BaseCollectionViewViewModelDelegate? let title = Localized("LikesViewModel.Title", comment:"Title of Likes screen") var shots = [ShotType]() fileprivate let shotsProvider = ShotsProvider() fileprivate var userMode: UserMode var itemsCount: Int { return shots.count } init() { userMode = UserStorage.isUserSignedIn ? .loggedUser : .demoUser } func downloadInitialItems() { firstly { shotsProvider.provideMyLikedShots() }.then { shots -> Void in if let shots = shots?.map({ $0.shot }), shots != self.shots || shots.count == 0 { self.shots = shots self.delegate?.viewModelDidLoadInitialItems() } }.catch { error in self.delegate?.viewModelDidFailToLoadInitialItems(error) } } func downloadItemsForNextPage() { guard UserStorage.isUserSignedIn else { return } firstly { shotsProvider.nextPageForLikedShots() }.then { shots -> Void in if let shots = shots?.map({ $0.shot }), shots.count > 0 { let indexes = shots.enumerated().map { index, _ in return index + self.shots.count } self.shots.append(contentsOf: shots) let indexPaths = indexes.map { IndexPath(row:($0), section: 0) } self.delegate?.viewModel(self, didLoadItemsAtIndexPaths: indexPaths) } }.catch { error in self.notifyDelegateAboutFailure(error) } } func downloadItem(at index: Int) { /* empty */ } func emptyCollectionDescriptionAttributes() -> EmptyCollectionViewDescription { let description = EmptyCollectionViewDescription( firstLocalizedString: Localized("LikesCollectionView.EmptyData.FirstLocalizedString", comment: "LikesCollectionView, empty data set view"), attachmentImageName: "ic-like-emptystate", imageOffset: CGPoint(x: 0, y: -2), lastLocalizedString: Localized("LikesCollectionView.EmptyData.LastLocalizedString", comment: "LikesCollectionView, empty data set view") ) return description } func shotCollectionViewCellViewData(_ indexPath: IndexPath) -> (shotImage: ShotImageType, animated: Bool) { let shotImage = shots[indexPath.row].shotImage let animated = shots[indexPath.row].animated return (shotImage, animated) } func clearViewModelIfNeeded() { let currentUserMode = UserStorage.isUserSignedIn ? UserMode.loggedUser : .demoUser if userMode != currentUserMode { shots = [] userMode = currentUserMode delegate?.viewModelDidLoadInitialItems() } } }
gpl-3.0
86e371623a2f35a893ea9928bdf3c8ea
33.163043
111
0.610881
5.020767
false
false
false
false
benlangmuir/swift
test/Interop/Cxx/enum/scoped-enums-module-interface.swift
8
2438
// RUN: %target-swift-ide-test -print-module -module-to-print=ScopedEnums -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s // CHECK: enum ScopedEnumDefined : Int32 { // CHECK: init?(rawValue: Int32) // CHECK: var rawValue: Int32 { get } // CHECK: typealias RawValue = Int32 // CHECK: case x // CHECK: case y // CHECK: } // CHECK: enum ScopedEnumBasic : Int32 { // CHECK: init?(rawValue: Int32) // CHECK: var rawValue: Int32 { get } // CHECK: typealias RawValue = Int32 // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: } // CHECK: enum ScopedEnumCharDefined : CChar { // CHECK: init?(rawValue: CChar) // CHECK: var rawValue: CChar { get } // CHECK: typealias RawValue = CChar // CHECK: case x // CHECK: case y // CHECK: } // CHECK: enum ScopedEnumUnsignedDefined : UInt32 { // CHECK: init?(rawValue: UInt32) // CHECK: var rawValue: UInt32 { get } // CHECK: typealias RawValue = UInt32 // CHECK: case x // CHECK: case y // CHECK: } // CHECK: enum ScopedEnumUnsignedLongDefined : [[UINT_T:UInt|UInt32]] { // CHECK: init?(rawValue: [[UINT_T]]) // CHECK: var rawValue: [[UINT_T]] { get } // CHECK: typealias RawValue = [[UINT_T]] // CHECK: case x // CHECK: case y // CHECK: } // CHECK: enum ScopedEnumChar : CChar { // CHECK: init?(rawValue: CChar) // CHECK: var rawValue: CChar { get } // CHECK: typealias RawValue = CChar // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: } // CHECK: enum ScopedEnumUnsigned : UInt32 { // CHECK: init?(rawValue: UInt32) // CHECK: var rawValue: UInt32 { get } // CHECK: typealias RawValue = UInt32 // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: } // CHECK: enum ScopedEnumUnsignedLong : [[UINT_T]] { // CHECK: init?(rawValue: [[UINT_T]]) // CHECK: var rawValue: [[UINT_T]] { get } // CHECK: typealias RawValue = [[UINT_T]] // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: } // CHECK: enum ScopedEnumInt : Int32 { // CHECK: init?(rawValue: Int32) // CHECK: var rawValue: Int32 { get } // CHECK: typealias RawValue = Int32 // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: } // CHECK: enum ScopedEnumNegativeElement : Int32 { // CHECK: init?(rawValue: Int32) // CHECK: var rawValue: Int32 { get } // CHECK: typealias RawValue = Int32 // CHECK: case x // CHECK: case y // CHECK: case z // CHECK: }
apache-2.0
8fc458565d2df032d3caa3d8bfe644ff
27.022989
154
0.621001
3.137709
false
false
false
false
overtake/TelegramSwift
packages/FoundationUtils/Sources/FoundationUtils/Tuple.swift
1
825
import Foundation public final class Tuple1<T0> { public let _0: T0 public init(_ _0: T0) { self._0 = _0 } } public final class Tuple2<T0, T1> { public let _0: T0 public let _1: T1 public init(_ _0: T0, _ _1: T1) { self._0 = _0 self._1 = _1 } } public final class Tuple3<T0, T1, T2> { public let _0: T0 public let _1: T1 public let _2: T2 public init(_ _0: T0, _ _1: T1, _ _2: T2) { self._0 = _0 self._1 = _1 self._2 = _2 } } public func Tuple<T0>(_ _0: T0) -> Tuple1<T0> { return Tuple1(_0) } public func Tuple<T0, T1>(_ _0: T0, _ _1: T1) -> Tuple2<T0, T1> { return Tuple2(_0, _1) } public func Tuple<T0, T1, T2>(_ _0: T0, _ _1: T1, _ _2: T2) -> Tuple3<T0, T1, T2> { return Tuple3(_0, _1, _2) }
gpl-2.0
483827a21977399dba49148f69ff63a6
18.186047
83
0.481212
2.37069
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaAPI.swift
5
2559
// // WikipediaAPI.swift // RxExample // // Created by Krunoslav Zaher on 3/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa func apiError(_ error: String) -> NSError { return NSError(domain: "WikipediaAPI", code: -1, userInfo: [NSLocalizedDescriptionKey: error]) } public let WikipediaParseError = apiError("Error during parsing") protocol WikipediaAPI { func getSearchResults(_ query: String) -> Observable<[WikipediaSearchResult]> func articleContent(_ searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> } class DefaultWikipediaAPI: WikipediaAPI { static let sharedAPI = DefaultWikipediaAPI() // Singleton let `$`: Dependencies = Dependencies.sharedDependencies let loadingWikipediaData = ActivityIndicator() private init() {} private func JSON(_ url: URL) -> Observable<Any> { return `$`.URLSession .rx.json(url: url) .trackActivity(loadingWikipediaData) } // Example wikipedia response http://en.wikipedia.org/w/api.php?action=opensearch&search=Rx func getSearchResults(_ query: String) -> Observable<[WikipediaSearchResult]> { let escapedQuery = query.URLEscaped let urlContent = "http://en.wikipedia.org/w/api.php?action=opensearch&search=\(escapedQuery)" let url = URL(string: urlContent)! return JSON(url) .observeOn(`$`.backgroundWorkScheduler) .map { json in guard let json = json as? [AnyObject] else { throw exampleError("Parsing error") } return try WikipediaSearchResult.parseJSON(json) } .observeOn(`$`.mainScheduler) } // http://en.wikipedia.org/w/api.php?action=parse&page=rx&format=json func articleContent(_ searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> { let escapedPage = searchResult.title.URLEscaped guard let url = URL(string: "http://en.wikipedia.org/w/api.php?action=parse&page=\(escapedPage)&format=json") else { return Observable.error(apiError("Can't create url")) } return JSON(url) .map { jsonResult in guard let json = jsonResult as? NSDictionary else { throw exampleError("Parsing error") } return try WikipediaPage.parseJSON(json) } .observeOn(`$`.mainScheduler) } }
mit
f62781d5aa0b3f25d2de63741c93edb9
33.567568
124
0.626271
4.85389
false
false
false
false
grayunicorn/Quiz
Quiz/Login/LoginViewController.swift
1
3451
// // LoginViewController.swift // Quiz // // Created by Adam Eberbach on 10/9/17. // Copyright © 2017 Adam Eberbach. All rights reserved. // // Accept a username entered in a text field and begin the application if possible. // If the username is unknown say so. import UIKit import CoreData class LoginViewController: UIViewController { var moc: NSManagedObjectContext? = nil var loggedInTeacher: Teacher? var loggedInStudent: Student? static let kTeacherLoginSegue = "TeacherLoginSegue" static let kStudentLoginSegue = "StudentLoginSegue" @IBOutlet weak var usernameField: UITextField! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let teacherVC = segue.destination as? TeacherViewController { teacherVC.me = loggedInTeacher teacherVC.moc = moc } else if let studentVC = segue.destination as? StudentViewController { studentVC.me = loggedInStudent studentVC.moc = moc } else { print("That can't happen - login type unknown") } } @IBAction func proceedButtonAction(_ sender: Any) { // can't match anything without characters or a context guard let loginAttempt = usernameField.text, loginAttempt.isEmpty == false else { return } guard let moc = moc else { return } var recognised = false // Core data search for a teacher with this name let teachersRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Teacher.kManagedObjectIdentifier) let teachersNamePredicate = NSPredicate(format: "login == %@", loginAttempt) teachersRequest.predicate = teachersNamePredicate do { let teachers = try moc.fetch(teachersRequest) as! [Teacher] if let foundTeacher = teachers.first { // teacher login recognised, proceed as teacher loggedInTeacher = foundTeacher performSegue(withIdentifier: LoginViewController.kTeacherLoginSegue, sender: self) recognised = true } } catch { print("could not look up teacher") } if recognised == false { // if not a teacher, Core data search for a student with this name let studentRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Student.kManagedObjectIdentifier) let studentNamePredicate = NSPredicate(format: "login == %@", loginAttempt) studentRequest.predicate = studentNamePredicate do { let students = try moc.fetch(studentRequest) as! [Student] if let foundStudent = students.first { loggedInStudent = foundStudent performSegue(withIdentifier: LoginViewController.kStudentLoginSegue, sender: self) recognised = true } } catch { print("could not look up student") } } if recognised == false { // if a student was not found either then a simple alert if the login is not recognized let alertController = UIAlertController(title: "Login Failure", message: "Login was not recognised.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } } } // MARK:- UITextFieldDelegate extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { proceedButtonAction(textField) return true } }
bsd-3-clause
49285b3a6247433f2d4293d5a9fe38e4
33.848485
131
0.696522
4.935622
false
false
false
false
volythat/HNHelper
HNHelper/Extensions/UILocalNotification+Ext.swift
1
960
// // UILocalNotification+Ext.swift // HNHelper // // Created by oneweek on 9/7/17. // Copyright © 2017 Harry Nguyen. All rights reserved. // import UIKit extension UILocalNotification { class func push(timestamp : Double,message : String){ let notifi = UILocalNotification() notifi.fireDate = Date(timeIntervalSince1970: timestamp) notifi.alertBody = message notifi.repeatInterval = NSCalendar.Unit(rawValue: 0) notifi.soundName = UILocalNotificationDefaultSoundName UIApplication.shared.scheduleLocalNotification(notifi) } class func remove(timestamp:Double){ for notification in UIApplication.shared.scheduledLocalNotifications! { // if (notification.fireDate == Date(timeIntervalSince1970: timestamp)) { UIApplication.shared.cancelLocalNotification(notification) // break // } } } }
mit
ad5987622b7662b258df2a0f73e4cc5b
32.068966
96
0.653806
5.211957
false
false
false
false
googlemaps/ios-on-demand-rides-deliveries-samples
swift/consumer_swiftui/App/Utils/Strings.swift
1
3124
/* * Copyright 2022 Google LLC. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import Foundation /// Strings that can be used in the sample app. enum Strings { /// Control panel button text for the request ride state. static let controlPanelRequestRideButtonText = "REQUEST RIDE" /// Control panel button text for the confirm pickup state. static let controlPanelConfirmPickupButtonText = "CONFIRM PICKUP" /// Control panel button text for the confirm dropoff state. static let controlPanelConfirmDropoffButtonText = "CONFIRM DROPOFF" /// Control panel button text for the confirm trip state. static let controlPanelConfirmTripButtonText = "CONFIRM TRIP" /// Control panel button text for the cancel trip state. static let controlPanelCancelTripButtonText = "CANCEL TRIP" /// Pick up location text for the trip info view. static let selectPickupLocationText = "pickup location" /// Drop off location text for the trip info view. static let selectDropoffLocationText = "drop-off location" /// Vehicle ID text for the trip view. static let vehicleIDText = "Vehicle ID: " /// Trip ID text for the trip view. static let tripIDText = "Trip ID: " /// Static text displayed on trip info view. static let tripInfoViewStaticText = "Choose a " /// Text displayed on control panel state label for waiting for a new trip state. static let waitingForDriverMatchTitleText = "Waiting for driver match" /// Text displayed on control panel state label for enroute to pickup state. static let enrouteToPickupTitleText = "Driver is arriving at pickup" /// Text displayed on control panel state label for driver completing another trip state. static let completeLastTripTitleText = "Driver is completing another trip" /// Text displayed on control panel state label for waiting for arrived at pickup state. static let arrivedAtPickupTitleText = "Driver is at pickup" /// Text displayed on control panel state label for enroute to intermediate destination state. static let enrouteToIntermediateDestinationTitleText = "Driving to intermediate stop" /// Text displayed on control panel state label for arrived at intermediate destination state. static let arrivedAtIntermediateDestinationTitleText = "Arrived at intermediate stop" /// Text displayed on control panel state label for waiting for enroute to dropoff state. static let enrouteToDropoffTitleText = "Driving to dropoff" /// Text displayed on control panel state label for waiting for trip completed state. static let tripCompleteTitleText = "Trip Complete" }
apache-2.0
57f0b5b6d2ec2a7450884eb7b872ef20
41.216216
96
0.764725
4.74772
false
false
false
false
tjw/swift
test/Reflection/typeref_decoding_imported.swift
6
4599
// RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension -I %S/Inputs // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // ... now, test single-frontend mode with multi-threaded LLVM emission: // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension -I %S/Inputs -whole-module-optimization -num-threads 2 // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // CHECK-32: FIELDS: // CHECK-32: ======= // CHECK-32: TypesToReflect.HasCTypes // CHECK-32: ------------------------ // CHECK-32: mcs: __C.MyCStruct // CHECK-32: (struct __C.MyCStruct) // CHECK-32: mce: __C.MyCEnum // CHECK-32: (struct __C.MyCEnum) // CHECK-32: __C.MyCStruct // CHECK-32: ------------- // CHECK-32: i: Swift.Int32 // CHECK-32: (struct Swift.Int32) // CHECK-32: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-32: (struct Swift.Int32))) // CHECK-32: c: Swift.Int8 // CHECK-32: (struct Swift.Int8) // CHECK-32: TypesToReflect.AlsoHasCTypes // CHECK-32: ---------------------------- // CHECK-32: mcu: __C.MyCUnion // CHECK-32: (struct __C.MyCUnion) // CHECK-32: mcsbf: __C.MyCStructWithBitfields // CHECK-32: (struct __C.MyCStructWithBitfields) // CHECK-32: ASSOCIATED TYPES: // CHECK-32: ================= // CHECK-32: BUILTIN TYPES: // CHECK-32: ============== // CHECK-32-LABEL: - __C.MyCStruct: // CHECK-32: Size: 12 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 12 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32-LABEL: - __C.MyCEnum: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32-LABEL: - __C.MyCUnion: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-i386-LABEL: - __C.MyCStructWithBitfields: // CHECK-i386: Size: 4 // CHECK-i386: Alignment: 4 // CHECK-i386: Stride: 4 // CHECK-i386: NumExtraInhabitants: 0 // CHECK-arm-LABEL: - __C.MyCStructWithBitfields: // CHECK-arm: Size: 2 // CHECK-arm: Alignment: 1 // CHECK-arm: Stride: 2 // CHECK-arm: NumExtraInhabitants: 0 // CHECK-32: CAPTURE DESCRIPTORS: // CHECK-32: ==================== // CHECK-64: FIELDS: // CHECK-64: ======= // CHECK-64: TypesToReflect.HasCTypes // CHECK-64: ------------------------ // CHECK-64: mcs: __C.MyCStruct // CHECK-64: (struct __C.MyCStruct) // CHECK-64: mce: __C.MyCEnum // CHECK-64: (struct __C.MyCEnum) // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: __C.MyCStruct // CHECK-64: ------------- // CHECK-64: i: Swift.Int32 // CHECK-64: (struct Swift.Int32) // CHECK-64: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-64: (struct Swift.Int32))) // CHECK-64: c: Swift.Int8 // CHECK-64: (struct Swift.Int8) // CHECK-64: TypesToReflect.AlsoHasCTypes // CHECK-64: ---------------------------- // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: mcsbf: __C.MyCStructWithBitfields // CHECK-64: (struct __C.MyCStructWithBitfields) // CHECK-64: ASSOCIATED TYPES: // CHECK-64: ================= // CHECK-64: BUILTIN TYPES: // CHECK-64: ============== // CHECK-64-LABEL: - __C.MyCStruct: // CHECK-64: Size: 24 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 24 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCEnum: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCUnion: // CHECK-64: Size: 8 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 8 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCStructWithBitfields: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: CAPTURE DESCRIPTORS: // CHECK-64: ====================
apache-2.0
12313f64f2c772c8c189c33e1d7385bd
29.256579
268
0.650359
3.105334
false
false
false
false
uasys/swift
test/SILGen/optional_lvalue.swift
1
3031
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s // CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B0ySiSgz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int> // CHECK: [[PRECOND:%.*]] = function_ref @_T0s30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]( // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1 // CHECK: assign {{%.*}} to [[PAYLOAD]] func assign_optional_lvalue(_ x: inout Int?, _ y: Int) { x! = y } // CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B0ySQySiGz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int> // CHECK: [[PRECOND:%.*]] = function_ref @_T0s30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]( // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1 // CHECK: assign {{%.*}} to [[PAYLOAD]] func assign_iuo_lvalue(_ x: inout Int!, _ y: Int) { x! = y } struct S { var x: Int var computed: Int { get {} set {} } } // CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B9_implicitySQyAA1SVGz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<S> // CHECK: [[SOME:%.*]] = unchecked_take_enum_data_addr [[WRITE]] // CHECK: [[X:%.*]] = struct_element_addr [[SOME]] func assign_iuo_lvalue_implicit(_ s: inout S!, _ y: Int) { s.x = y } struct Struct<T> { var value: T? } // CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B13_reabstractedyAA6StructVyS2icGz_S2ictF // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0S2iIxyd_S2iIxir_TR // CHECK: [[REABSTRACTED:%.*]] = partial_apply [[REABSTRACT]] // CHECK: assign [[REABSTRACTED]] to {{%.*}} : $*@callee_owned (@in Int) -> @out Int func assign_optional_lvalue_reabstracted(_ x: inout Struct<(Int) -> Int>, _ y: @escaping (Int) -> Int) { x.value! = y } // CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B9_computedSiAA1SVSgz_SitF // CHECK: function_ref @_T015optional_lvalue1SV8computedSivs // CHECK: function_ref @_T015optional_lvalue1SV8computedSivg func assign_optional_lvalue_computed(_ x: inout S?, _ y: Int) -> Int { x!.computed = y return x!.computed } func generate_int() -> Int { return 0 } // CHECK-LABEL: sil hidden @_T015optional_lvalue013assign_bound_a1_B0ySiSgzF // CHECK: select_enum_addr // CHECK: cond_br {{%.*}}, [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]] // CHECK: [[SOME]]: // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr // CHECK: [[FN:%.*]] = function_ref // CHECK: [[T0:%.*]] = apply [[FN]]() // CHECK: assign [[T0]] to [[PAYLOAD]] func assign_bound_optional_lvalue(_ x: inout Int?) { x? = generate_int() }
apache-2.0
f555800be353f0be9a79199e8c37958f
40.520548
119
0.591884
3.193888
false
false
false
false
guoyingtao/EchoTipCalc
EchoTipCalc/EchoTipCalc.swift
1
2664
// // EchoTipCalc.swift // EchoTipCalc // // Created by Echo on 2017/3/27. // Copyright © 2017年 Echo. All rights reserved. // import Foundation public class EchoTipCalculator { public init() { } // return (Tip you need pay, Total you need pay) public func calcTip(peopleNum: Int = 1, payBeforeTax: Float, tax: Float = 0, tipRate: Float = 0) -> (tipYouNeedPay: Float, moneyYouNeedPay: Float) { guard payBeforeTax > 0 else { return(0, 0) } let payBeforeTaxPerPerson = payBeforeTax / Float(peopleNum) return calcTip(peopleNum:peopleNum, payBeforeTaxPerPerson:payBeforeTaxPerPerson, tax:tax, tipRate:tipRate) } public func calcTip(peopleNum: Int = 1, totalPrice: Float, tax: Float = 0, tipRate: Float = 0) -> (tipYouNeedPay: Float, moneyYouNeedPay: Float) { guard totalPrice > 0 else { return (0, 0) } let payBeforeTax = max(0, totalPrice - tax) let actualTax = min(totalPrice, tax) // tax should be less than totalPrice let payBeforeTaxPerPerson = payBeforeTax / Float(peopleNum) return calcTip(peopleNum:peopleNum, payBeforeTaxPerPerson:payBeforeTaxPerPerson, tax:actualTax, tipRate:tipRate) } private func calcTip(peopleNum: Int = 1, payBeforeTaxPerPerson: Float, tax: Float = 0, tipRate: Float = 0) -> (tipYouNeedPay: Float, moneyYouNeedPay: Float) { guard peopleNum > 0 else { return (0, 0) } let validTax = max(0, tax) let validTipRate = max(0, tipRate) let validTaxPerPerson = validTax / Float(peopleNum) var tipYouNeedPay = payBeforeTaxPerPerson * validTipRate var moneyYouNeedPay = payBeforeTaxPerPerson + validTaxPerPerson + tipYouNeedPay tipYouNeedPay = roundFloatToDecimalPlace(number: tipYouNeedPay) moneyYouNeedPay = roundFloatToDecimalPlace(number: moneyYouNeedPay) return (tipYouNeedPay, moneyYouNeedPay) } internal func roundFloatToDecimalPlace(number: Float, decimalDigits: Int = 2) -> Float { let parameter = Float(NSDecimalNumber(decimal: pow(10, decimalDigits))) let ret = (number * parameter).rounded() / parameter return ret } }
mit
d964ceb9c14e0d15f80b1ce3c78e5918
33.558442
96
0.561067
5.187135
false
false
false
false
uasys/swift
stdlib/public/core/Policy.swift
1
26100
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Swift Standard Prolog Library. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Standardized uninhabited type //===----------------------------------------------------------------------===// /// The return type of functions that do not return normally; a type with no /// values. /// /// Use `Never` as the return type when declaring a closure, function, or /// method that unconditionally throws an error, traps, or otherwise does /// not terminate. /// /// func crashAndBurn() -> Never { /// fatalError("Something very, very bad happened") /// } @_fixed_layout public enum Never {} //===----------------------------------------------------------------------===// // Standardized aliases //===----------------------------------------------------------------------===// /// The return type of functions that don't explicitly specify a return type; /// an empty tuple (i.e., `()`). /// /// When declaring a function or method, you don't need to specify a return /// type if no value will be returned. However, the type of a function, /// method, or closure always includes a return type, which is `Void` if /// otherwise unspecified. /// /// Use `Void` or an empty tuple as the return type when declaring a /// closure, function, or method that doesn't return a value. /// /// // No return type declared: /// func logMessage(_ s: String) { /// print("Message: \(s)") /// } /// /// let logger: (String) -> Void = logMessage /// logger("This is a void function") /// // Prints "Message: This is a void function" public typealias Void = () //===----------------------------------------------------------------------===// // Aliases for floating point types //===----------------------------------------------------------------------===// // FIXME: it should be the other way round, Float = Float32, Double = Float64, // but the type checker loses sugar currently, and ends up displaying 'FloatXX' // in diagnostics. /// A 32-bit floating point type. public typealias Float32 = Float /// A 64-bit floating point type. public typealias Float64 = Double //===----------------------------------------------------------------------===// // Default types for unconstrained literals //===----------------------------------------------------------------------===// /// The default type for an otherwise-unconstrained integer literal. public typealias IntegerLiteralType = Int /// The default type for an otherwise-unconstrained floating point literal. public typealias FloatLiteralType = Double /// The default type for an otherwise-unconstrained Boolean literal. /// /// When you create a constant or variable using one of the Boolean literals /// `true` or `false`, the resulting type is determined by the /// `BooleanLiteralType` alias. For example: /// /// let isBool = true /// print("isBool is a '\(type(of: isBool))'") /// // Prints "isBool is a 'Bool'" /// /// The type aliased by `BooleanLiteralType` must conform to the /// `ExpressibleByBooleanLiteral` protocol. public typealias BooleanLiteralType = Bool /// The default type for an otherwise-unconstrained unicode scalar literal. public typealias UnicodeScalarType = String /// The default type for an otherwise-unconstrained Unicode extended /// grapheme cluster literal. public typealias ExtendedGraphemeClusterType = String /// The default type for an otherwise-unconstrained string literal. public typealias StringLiteralType = String //===----------------------------------------------------------------------===// // Default types for unconstrained number literals //===----------------------------------------------------------------------===// // Integer literals are limited to 2048 bits. // The intent is to have arbitrary-precision literals, but implementing that // requires more work. // // Rationale: 1024 bits are enough to represent the absolute value of min/max // IEEE Binary64, and we need 1 bit to represent the sign. Instead of using // 1025, we use the next round number -- 2048. public typealias _MaxBuiltinIntegerType = Builtin.Int2048 #if !os(Windows) && (arch(i386) || arch(x86_64)) public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80 #else public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64 #endif //===----------------------------------------------------------------------===// // Standard protocols //===----------------------------------------------------------------------===// #if _runtime(_ObjC) /// The protocol to which all classes implicitly conform. /// /// You use `AnyObject` when you need the flexibility of an untyped object or /// when you use bridged Objective-C methods and properties that return an /// untyped result. `AnyObject` can be used as the concrete type for an /// instance of any class, class type, or class-only protocol. For example: /// /// class FloatRef { /// let value: Float /// init(_ value: Float) { /// self.value = value /// } /// } /// /// let x = FloatRef(2.3) /// let y: AnyObject = x /// let z: AnyObject = FloatRef.self /// /// `AnyObject` can also be used as the concrete type for an instance of a type /// that bridges to an Objective-C class. Many value types in Swift bridge to /// Objective-C counterparts, like `String` and `Int`. /// /// let s: AnyObject = "This is a bridged string." as NSString /// print(s is NSString) /// // Prints "true" /// /// let v: AnyObject = 100 as NSNumber /// print(type(of: v)) /// // Prints "__NSCFNumber" /// /// The flexible behavior of the `AnyObject` protocol is similar to /// Objective-C's `id` type. For this reason, imported Objective-C types /// frequently use `AnyObject` as the type for properties, method parameters, /// and return values. /// /// Casting AnyObject Instances to a Known Type /// =========================================== /// /// Objects with a concrete type of `AnyObject` maintain a specific dynamic /// type and can be cast to that type using one of the type-cast operators /// (`as`, `as?`, or `as!`). /// /// This example uses the conditional downcast operator (`as?`) to /// conditionally cast the `s` constant declared above to an instance of /// Swift's `String` type. /// /// if let message = s as? String { /// print("Successful cast to String: \(message)") /// } /// // Prints "Successful cast to String: This is a bridged string." /// /// If you have prior knowledge that an `AnyObject` instance has a particular /// type, you can use the unconditional downcast operator (`as!`). Performing /// an invalid cast triggers a runtime error. /// /// let message = s as! String /// print("Successful cast to String: \(message)") /// // Prints "Successful cast to String: This is a bridged string." /// /// let badCase = v as! String /// // Runtime error /// /// Casting is always safe in the context of a `switch` statement. /// /// let mixedArray: [AnyObject] = [s, v] /// for object in mixedArray { /// switch object { /// case let x as String: /// print("'\(x)' is a String") /// default: /// print("'\(object)' is not a String") /// } /// } /// // Prints "'This is a bridged string.' is a String" /// // Prints "'100' is not a String" /// /// Accessing Objective-C Methods and Properties /// ============================================ /// /// When you use `AnyObject` as a concrete type, you have at your disposal /// every `@objc` method and property---that is, methods and properties /// imported from Objective-C or marked with the `@objc` attribute. Because /// Swift can't guarantee at compile time that these methods and properties /// are actually available on an `AnyObject` instance's underlying type, these /// `@objc` symbols are available as implicitly unwrapped optional methods and /// properties, respectively. /// /// This example defines an `IntegerRef` type with an `@objc` method named /// `getIntegerValue()`. /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// @objc func getIntegerValue() -> Int { /// return value /// } /// } /// /// func getObject() -> AnyObject { /// return IntegerRef(100) /// } /// /// let obj: AnyObject = getObject() /// /// In the example, `obj` has a static type of `AnyObject` and a dynamic type /// of `IntegerRef`. You can use optional chaining to call the `@objc` method /// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of /// `obj`, you can call `getIntegerValue()` directly. /// /// let possibleValue = obj.getIntegerValue?() /// print(possibleValue) /// // Prints "Optional(100)" /// /// let certainValue = obj.getIntegerValue() /// print(certainValue) /// // Prints "100" /// /// If the dynamic type of `obj` doesn't implement a `getIntegerValue()` /// method, the system returns a runtime error when you initialize /// `certainValue`. /// /// Alternatively, if you need to test whether `obj.getIntegerValue()` exists, /// use optional binding before calling the method. /// /// if let f = obj.getIntegerValue { /// print("The value of 'obj' is \(f())") /// } else { /// print("'obj' does not have a 'getIntegerValue()' method") /// } /// // Prints "The value of 'obj' is 100" public typealias AnyObject = Builtin.AnyObject #else /// The protocol to which all classes implicitly conform. public typealias AnyObject = Builtin.AnyObject #endif /// The protocol to which all class types implicitly conform. /// /// You can use the `AnyClass` protocol as the concrete type for an instance of /// any class. When you do, all known `@objc` class methods and properties are /// available as implicitly unwrapped optional methods and properties, /// respectively. For example: /// /// class IntegerRef { /// @objc class func getDefaultValue() -> Int { /// return 42 /// } /// } /// /// func getDefaultValue(_ c: AnyClass) -> Int? { /// return c.getDefaultValue?() /// } /// /// The `getDefaultValue(_:)` function uses optional chaining to safely call /// the implicitly unwrapped class method on `c`. Calling the function with /// different class types shows how the `getDefaultValue()` class method is /// only conditionally available. /// /// print(getDefaultValue(IntegerRef.self)) /// // Prints "Optional(42)" /// /// print(getDefaultValue(NSString.self)) /// // Prints "nil" public typealias AnyClass = AnyObject.Type /// A type that supports standard bitwise arithmetic operators. /// /// Types that conform to the `BitwiseOperations` protocol implement operators /// for bitwise arithmetic. The integer types in the standard library all /// conform to `BitwiseOperations` by default. When you use bitwise operators /// with an integer, you perform operations on the raw data bits that store /// the integer's value. /// /// In the following examples, the binary representation of any values are /// shown in a comment to the right, like this: /// /// let x: UInt8 = 5 // 0b00000101 /// /// Here are the required operators for the `BitwiseOperations` protocol: /// /// - The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. This /// is equivalent to the union of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR operation with a value and `allZeros` always /// returns the same value. /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise NOT operator (`~`) is a prefix operator that returns a value /// where all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// The `OptionSet` protocol uses a raw value that conforms to /// `BitwiseOperations` to provide mathematical set operations like /// `union(_:)`, `intersection(_:)` and `contains(_:)` with O(1) performance. /// /// Conforming to the BitwiseOperations Protocol /// ============================================ /// /// To make your custom type conform to `BitwiseOperations`, add a static /// `allZeros` property and declare the four required operator functions. Any /// type that conforms to `BitwiseOperations`, where `x` is an instance of the /// conforming type, must satisfy the following conditions: /// /// - `x | Self.allZeros == x` /// - `x ^ Self.allZeros == x` /// - `x & Self.allZeros == .allZeros` /// - `x & ~Self.allZeros == x` /// - `~x == x ^ ~Self.allZeros` @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use FixedWidthInteger protocol instead") public typealias BitwiseOperations = _BitwiseOperations public protocol _BitwiseOperations { /// Returns the intersection of bits set in the two arguments. /// /// The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - Complexity: O(1). static func & (lhs: Self, rhs: Self) -> Self /// Returns the union of bits set in the two arguments. /// /// The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func | (lhs: Self, rhs: Self) -> Self /// Returns the bits that are set in exactly one of the two arguments. /// /// The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR with a value and `allZeros` always returns the /// same value: /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func ^ (lhs: Self, rhs: Self) -> Self /// Returns the inverse of the bits set in the argument. /// /// The bitwise NOT operator (`~`) is a prefix operator that returns a value /// in which all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// - Complexity: O(1). static prefix func ~ (x: Self) -> Self /// The empty bitset. /// /// The `allZeros` static property is the [identity element][] for bitwise OR /// and XOR operations and the [fixed point][] for bitwise AND operations. /// For example: /// /// let x: UInt8 = 5 // 0b00000101 /// /// // Identity /// x | .allZeros // 0b00000101 /// x ^ .allZeros // 0b00000101 /// /// // Fixed point /// x & .allZeros // 0b00000000 /// /// [identity element]:http://en.wikipedia.org/wiki/Identity_element /// [fixed point]:http://en.wikipedia.org/wiki/Fixed_point_(mathematics) @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use 0 or init() of a type conforming to FixedWidthInteger") static var allZeros: Self { get } } /// Calculates the union of bits sets in the two arguments and stores the result /// in the first argument. /// /// - Parameters: /// - lhs: A value to update with the union of bits set in the two arguments. /// - rhs: Another value. public func |= <T : _BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs | rhs } /// Calculates the intersections of bits sets in the two arguments and stores /// the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the intersections of bits set in the two /// arguments. /// - rhs: Another value. public func &= <T : _BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs & rhs } /// Calculates the bits that are set in exactly one of the two arguments and /// stores the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the bits that are set in exactly one of the /// two arguments. /// - rhs: Another value. public func ^= <T : _BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs ^ rhs } //===----------------------------------------------------------------------===// // Standard pattern matching forms //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two arguments match by value /// equality. /// /// The pattern-matching operator (`~=`) is used internally in `case` /// statements for pattern matching. When you match against an `Equatable` /// value in a `case` statement, this operator is called behind the scenes. /// /// let weekday = 3 /// let lunch: String /// switch weekday { /// case 3: /// lunch = "Taco Tuesday!" /// default: /// lunch = "Pizza again." /// } /// // lunch == "Taco Tuesday!" /// /// In this example, the `case 3` expression uses this pattern-matching /// operator to test whether `weekday` is equal to the value `3`. /// /// - Note: In most cases, you should use the equal-to operator (`==`) to test /// whether two instances are equal. The pattern-matching operator is /// primarily intended to enable `case` statement pattern matching. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_transparent public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } //===----------------------------------------------------------------------===// // Standard precedence groups //===----------------------------------------------------------------------===// precedencegroup AssignmentPrecedence { assignment: true associativity: right } precedencegroup FunctionArrowPrecedence { associativity: right higherThan: AssignmentPrecedence } precedencegroup TernaryPrecedence { associativity: right higherThan: FunctionArrowPrecedence } precedencegroup DefaultPrecedence { higherThan: TernaryPrecedence } precedencegroup LogicalDisjunctionPrecedence { associativity: left higherThan: TernaryPrecedence } precedencegroup LogicalConjunctionPrecedence { associativity: left higherThan: LogicalDisjunctionPrecedence } precedencegroup ComparisonPrecedence { higherThan: LogicalConjunctionPrecedence } precedencegroup NilCoalescingPrecedence { associativity: right higherThan: ComparisonPrecedence } precedencegroup CastingPrecedence { higherThan: NilCoalescingPrecedence } precedencegroup RangeFormationPrecedence { higherThan: CastingPrecedence } precedencegroup AdditionPrecedence { associativity: left higherThan: RangeFormationPrecedence } precedencegroup MultiplicationPrecedence { associativity: left higherThan: AdditionPrecedence } precedencegroup BitwiseShiftPrecedence { higherThan: MultiplicationPrecedence } //===----------------------------------------------------------------------===// // Standard operators //===----------------------------------------------------------------------===// // Standard postfix operators. postfix operator ++ postfix operator -- postfix operator ... // Optional<T> unwrapping operator is built into the compiler as a part of // postfix expression grammar. // // postfix operator ! // Standard prefix operators. prefix operator ++ prefix operator -- prefix operator ! prefix operator ~ prefix operator + prefix operator - prefix operator ... prefix operator ..< // Standard infix operators. // "Exponentiative" infix operator << : BitwiseShiftPrecedence infix operator &<< : BitwiseShiftPrecedence infix operator >> : BitwiseShiftPrecedence infix operator &>> : BitwiseShiftPrecedence // "Multiplicative" infix operator * : MultiplicationPrecedence infix operator &* : MultiplicationPrecedence infix operator / : MultiplicationPrecedence infix operator % : MultiplicationPrecedence infix operator & : MultiplicationPrecedence // "Additive" infix operator + : AdditionPrecedence infix operator &+ : AdditionPrecedence infix operator - : AdditionPrecedence infix operator &- : AdditionPrecedence infix operator | : AdditionPrecedence infix operator ^ : AdditionPrecedence // FIXME: is this the right precedence level for "..." ? infix operator ... : RangeFormationPrecedence infix operator ..< : RangeFormationPrecedence // The cast operators 'as' and 'is' are hardcoded as if they had the // following attributes: // infix operator as : CastingPrecedence // "Coalescing" infix operator ?? : NilCoalescingPrecedence // "Comparative" infix operator < : ComparisonPrecedence infix operator <= : ComparisonPrecedence infix operator > : ComparisonPrecedence infix operator >= : ComparisonPrecedence infix operator == : ComparisonPrecedence infix operator != : ComparisonPrecedence infix operator === : ComparisonPrecedence infix operator !== : ComparisonPrecedence // FIXME: ~= will be built into the compiler. infix operator ~= : ComparisonPrecedence // "Conjunctive" infix operator && : LogicalConjunctionPrecedence // "Disjunctive" infix operator || : LogicalDisjunctionPrecedence // User-defined ternary operators are not supported. The ? : operator is // hardcoded as if it had the following attributes: // operator ternary ? : : TernaryPrecedence // User-defined assignment operators are not supported. The = operator is // hardcoded as if it had the following attributes: // infix operator = : AssignmentPrecedence // Compound infix operator *= : AssignmentPrecedence infix operator /= : AssignmentPrecedence infix operator %= : AssignmentPrecedence infix operator += : AssignmentPrecedence infix operator -= : AssignmentPrecedence infix operator <<= : AssignmentPrecedence infix operator &<<= : AssignmentPrecedence infix operator >>= : AssignmentPrecedence infix operator &>>= : AssignmentPrecedence infix operator &= : AssignmentPrecedence infix operator ^= : AssignmentPrecedence infix operator |= : AssignmentPrecedence // Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. Library authors should ensure // that this operator never needs to be seen by end-users. See // test/Prototypes/GenericDispatch.swift for a fully documented // example of how this operator is used, and how its use can be hidden // from users. infix operator ~>
apache-2.0
feb62457606b515c9df67774f305235d
35.760563
122
0.617395
4.53125
false
false
false
false
yidahis/ShopingCart
ShopingCart/UIViewExtension.swift
1
6537
import UIKit extension UIView { /// X坐标 var x: CGFloat { get { return self.frame.origin.x } set (newValue) { var frame = self.frame frame.origin.x = newValue self.frame = frame } } /// Y坐标 var y: CGFloat { get { return self.frame.origin.y } set (newValue) { var frame = self.frame frame.origin.y = newValue self.frame = frame } } /// 宽 var width: CGFloat { get { return self.frame.size.width } set (newValue) { var frame = self.frame frame.size.width = newValue self.frame = frame } } /// 高 var height: CGFloat { get { return self.frame.size.height } set (newValue) { var frame = self.frame frame.size.height = newValue self.frame = frame } } /// View大小 var size: CGSize { get { return CGSize(width: width, height: height) } set (newValue) { var frame = self.frame frame.size = newValue self.frame = frame } } /// View中心X坐标 var centerX: CGFloat { get { return self.center.x } set (newValue) { var center = self.center center.x = newValue self.center = center } } /// View中心Y坐标 var centerY: CGFloat { get { return self.center.y } set (newValue) { var center = self.center center.y = newValue self.center = center } } /// EZSwiftExtensions public var left: CGFloat { get { return self.x } set(value) { self.x = value } } /// EZSwiftExtensions public var right: CGFloat { get { return self.x + self.width } set(value) { self.x = value - self.width } } /// EZSwiftExtensions public var top: CGFloat { get { return self.y } set(value) { self.y = value } } /// EZSwiftExtensions public var bottom: CGFloat { get { return self.y + self.height } set(value) { self.y = value - self.height } } /// 添加毛玻璃 /// /// - Parameter stype: 毛玻璃样式 public func addBlurEffect(_ stype:UIBlurEffectStyle) { let blurEffect = UIBlurEffect(style: stype) let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.frame = self.bounds self.addSubview(visualEffectView) } } // MARK: Layer Extensions extension UIView { /// EZSwiftExtensions public func setCornerRadius(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.masksToBounds = true } //TODO: add this to readme /// EZSwiftExtensions public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) { self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowColor = color.cgColor if let r = cornerRadius { self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath } } /// EZSwiftExtensions public func addBorder(width: CGFloat, color: UIColor) { layer.borderWidth = width layer.borderColor = color.cgColor layer.masksToBounds = true } /// EZSwiftExtensions public func addBorderTop(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color) } //TODO: add to readme /// EZSwiftExtensions public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) { addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color) } /// EZSwiftExtensions public func addBorderBottom(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color) } /// EZSwiftExtensions public func addBorderLeft(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions public func addBorderRight(size: CGFloat, color: UIColor) { addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) { let border = CALayer() border.backgroundColor = color.cgColor border.frame = CGRect(x: x, y: y, width: width, height: height) layer.addSublayer(border) } //TODO: add this to readme /// EZSwiftExtensions public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.fillColor = fillColor.cgColor shapeLayer.strokeColor = strokeColor.cgColor shapeLayer.lineWidth = strokeWidth self.layer.addSublayer(shapeLayer) } //TODO: add this to readme /// EZSwiftExtensions public func drawStroke(width: CGFloat, color: UIColor) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2) let shapeLayer = CAShapeLayer () shapeLayer.path = path.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = color.cgColor shapeLayer.lineWidth = width self.layer.addSublayer(shapeLayer) } }
apache-2.0
283bc5d4cd5cffd7831da8e9186be74f
25.577869
131
0.543254
4.839552
false
false
false
false
crspybits/SMSyncServer
iOS/SharedNotes/Code/SyncSpinner.swift
1
2823
// // SyncSpinner.swift // SharedNotes // // Created by Christopher Prince on 4/27/16. // Copyright © 2016 Spastic Muffin, LLC. All rights reserved. // import Foundation import UIKit class SyncSpinner : UIView { let normalImage = "SyncSpinner" let yellowImage = "SyncSpinnerYellow" let redImage = "SyncSpinnerRed" private var icon = UIImageView() private var animating = false override init(frame: CGRect) { super.init(frame: frame) self.setImage(usingBackgroundColor: .Clear) self.icon.contentMode = .ScaleAspectFit self.icon.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] var iconFrame = frame; iconFrame.origin = CGPointZero self.icon.frame = iconFrame self.addSubview(self.icon) self.stop() } enum BackgroundColor { case Clear case Yellow case Red } private func setImage(usingBackgroundColor color:BackgroundColor) { var imageName:String switch color { case .Clear: imageName = self.normalImage case .Yellow: imageName = self.yellowImage case .Red: imageName = self.redImage } let image = UIImage(named: imageName) self.icon.image = image } // Dealing with issue: Spinner started when view is not displayed. When view finally gets displayed, spinner graphic is displayed but it's not animating. override func layoutSubviews() { if self.animating { self.stop() self.start() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private let animationKey = "rotationAnimation" func start() { self.setImage(usingBackgroundColor: .Clear) self.animating = true self.hidden = false let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.toValue = M_PI * 2.0 rotationAnimation.duration = 1 rotationAnimation.cumulative = true rotationAnimation.repeatCount = Float.infinity self.icon.layer.addAnimation(rotationAnimation, forKey: self.animationKey) // Dealing with issue of animation not restarting when app comes back from background. self.icon.layer.MB_setCurrentAnimationsPersistent() } func stop(withBackgroundColor color:BackgroundColor = .Clear) { self.animating = false self.setImage(usingBackgroundColor: color) // Make the spinner hidden when stopping iff background is clear self.hidden = (color == .Clear) self.icon.layer.removeAllAnimations() } }
gpl-3.0
7f848d22878eeea62d01d48bd8a1b499
28.715789
157
0.625797
5.003546
false
false
false
false
shopgun/shopgun-ios-sdk
Sources/TjekPublicationViewer/PagedPublication/PagedPublicationView+ImageLoader.swift
1
2371
/// /// Copyright (c) 2018 Tjek. All rights reserved. /// import UIKit /// The object that knows how to load/cache the page images from a URL /// Loosely based on `Kingfisher` interface public protocol PagedPublicationViewImageLoader: AnyObject { func loadImage(in imageView: UIImageView, url: URL, transition: (fadeDuration: TimeInterval, evenWhenCached: Bool), completion: @escaping ((Result<(image: UIImage, fromCache: Bool), Error>, URL) -> Void)) func cancelImageLoad(for imageView: UIImageView) } extension PagedPublicationView { enum ImageLoaderError: Error { case unknownImageLoadError(url: URL) case cancelled } } extension Error where Self == PagedPublicationView.ImageLoaderError { var isCancellationError: Bool { switch self { case .cancelled: return true default: return false } } } // MARK: - import Kingfisher extension PagedPublicationView { /// This class wraps the Kingfisher library class KingfisherImageLoader: PagedPublicationViewImageLoader { init() { // max 150 Mb of disk cache KingfisherManager.shared.cache.diskStorage.config.sizeLimit = 150*1024*1024 } func loadImage(in imageView: UIImageView, url: URL, transition: (fadeDuration: TimeInterval, evenWhenCached: Bool), completion: @escaping ((Result<(image: UIImage, fromCache: Bool), Error>, URL) -> Void)) { var options: KingfisherOptionsInfo = [.transition(.fade(transition.fadeDuration))] if transition.evenWhenCached == true { options.append(.forceTransition) } imageView.kf.setImage(with: url, options: options) { result in switch result { case .success(let retrievedImage): completion(.success((retrievedImage.image, retrievedImage.cacheType.cached)), url) case .failure(let error): let err: Error = error.isTaskCancelled ? PagedPublicationView.ImageLoaderError.cancelled : error completion(.failure(err), url) } } } func cancelImageLoad(for imageView: UIImageView) { imageView.kf.cancelDownloadTask() } } }
mit
a9f21a3af5e428ba22d7604d30a198e7
33.362319
214
0.621257
5.210989
false
false
false
false
shajrawi/swift
stdlib/public/Darwin/Accelerate/vDSP_DFT.swift
2
15098
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // Discrete Fourier Transform // //===----------------------------------------------------------------------===// extension vDSP { /// An enumeration that specifies whether to perform complex-to-complex or /// complex-to-real discrete Fourier transform. @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) // TODO: Should probably be @_frozen; check with Accelerate. public enum DFTTransformType { /// Specifies complex-to-complex discrete Fourier transform, forward /// or inverse case complexComplex /// Specifies real-to-complex (forward) or complex-to-real (inverse) /// discrete Fourier transform. case complexReal } /// A class that provides single- and double-precision discrete Fourier transform. @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) public class DFT <T: vDSP_FloatingPointDiscreteFourierTransformable> { fileprivate let dftSetup: vDSP_DFT_Setup /// Initializes a new discrete Fourier transform structure. /// /// - Parameter previous: a previous vDSP_DFT instance to share data with. /// - Parameter count: the number of real elements to be transformed. /// - Parameter direction: Specifies the transform direction. /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. public init?(previous: DFT? = nil, count: Int, direction: vDSP.FourierTransformDirection, transformType: DFTTransformType, ofType: T.Type) { guard let setup = T.DFTFunctions.makeDFTSetup(previous: previous, count: count, direction: direction, transformType: transformType) else { return nil } self.transformType = transformType dftSetup = setup } /// The transform type of this DFT. private let transformType: DFTTransformType /// Returns a single-precision real discrete Fourier transform. /// /// - Parameter inputReal: Input vector - real part. /// - Parameter inputImaginary: Input vector - imaginary part. /// - Returns: A tuple of two arrays representing the real and imaginary parts of the output. /// /// When the `transformType` is `complexComplex`, each input array (Ir, Ii) /// must have `count` elements, and the returned arrays have `count` elements. /// /// When the `transformType` is `complexReal`, each input array (Ir, Ii) /// must have `count` elements, and the returned arrays have `count / 2` elements. public func transform<U>(inputReal: U, inputImaginary: U) -> (real:[T], imaginary: [T]) where U: AccelerateBuffer, U.Element == T { let n = transformType == .complexReal ? inputReal.count / 2 : inputReal.count var imaginaryResult: Array<T>! let realResult = Array<T>(unsafeUninitializedCapacity: n) { realBuffer, realInitializedCount in imaginaryResult = Array<T>(unsafeUninitializedCapacity: n) { imaginaryBuffer, imaginaryInitializedCount in transform(inputReal: inputReal, inputImaginary: inputImaginary, outputReal: &realBuffer, outputImaginary: &imaginaryBuffer) imaginaryInitializedCount = n } realInitializedCount = n } return (real: realResult, imaginary: imaginaryResult) } /// Computes an out-of-place single-precision real discrete Fourier transform. /// /// - Parameter inputReal: Input vector - real part. /// - Parameter inputImaginary: Input vector - imaginary part. /// - Parameter outputReal: Output vector - real part. /// - Parameter outputImaginary: Output vector - imaginary part. /// /// When the `transformType` is `complexComplex`, each array (Ir, Ii, /// Or, and Oi) must have `count` elements. /// /// When the `transformType` is `complexReal`, each array (Ir, Ii, /// Or, and Oi) must have `count/2` elements. public func transform<U, V>(inputReal: U, inputImaginary: U, outputReal: inout V, outputImaginary: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == T, V.Element == T { T.DFTFunctions.transform(dftSetup: dftSetup, inputReal: inputReal, inputImaginary: inputImaginary, outputReal: &outputReal, outputImaginary: &outputImaginary) } deinit { T.DFTFunctions.destroySetup(dftSetup) } } } @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) public protocol vDSP_FloatingPointDiscreteFourierTransformable: BinaryFloatingPoint { associatedtype DFTFunctions: vDSP_DFTFunctions where DFTFunctions.Scalar == Self } @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) extension Float: vDSP_FloatingPointDiscreteFourierTransformable { public typealias DFTFunctions = vDSP.VectorizableFloat } @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) extension Double: vDSP_FloatingPointDiscreteFourierTransformable { public typealias DFTFunctions = vDSP.VectorizableDouble } @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) public protocol vDSP_DFTFunctions { associatedtype Scalar /// Returns a setup structure to perform a discrete Fourier transform /// /// - Parameter previous: a previous vDSP_DFT instance to share data with. /// - Parameter count: the number of real elements to be transformed. /// - Parameter direction: Specifies the transform direction. /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. static func makeDFTSetup<T>(previous: vDSP.DFT<T>?, count: Int, direction: vDSP.FourierTransformDirection, transformType: vDSP.DFTTransformType) -> OpaquePointer? /// Computes an out-of-place single-precision real discrete Fourier transform. /// /// - Parameter dftSetup: A DCT setup object. /// - Parameter inputReal: Input vector - real part. /// - Parameter inputImaginary: Input vector - imaginary part. /// - Parameter outputReal: Output vector - real part. /// - Parameter outputImaginary: Output vector - imaginary part. static func transform<U, V>(dftSetup: OpaquePointer, inputReal: U, inputImaginary: U, outputReal: inout V, outputImaginary: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Scalar, V.Element == Scalar /// Releases a DFT setup object. static func destroySetup(_ setup: OpaquePointer) } //===----------------------------------------------------------------------===// // // Type-specific DFT function implementations // //===----------------------------------------------------------------------===// @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) extension vDSP.VectorizableFloat: vDSP_DFTFunctions { /// Returns a setup structure to perform a discrete Fourier transform /// /// - Parameter previous: a previous vDSP_DFT instance to share data with. /// - Parameter count: the number of real elements to be transformed. /// - Parameter direction: Specifies the transform direction. /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. public static func makeDFTSetup<T>(previous: vDSP.DFT<T>? = nil, count: Int, direction: vDSP.FourierTransformDirection, transformType: vDSP.DFTTransformType) -> OpaquePointer? where T : vDSP_FloatingPointDiscreteFourierTransformable { switch transformType { case .complexComplex: return vDSP_DFT_zop_CreateSetup(previous?.dftSetup, vDSP_Length(count), direction.dftDirection) case .complexReal: return vDSP_DFT_zrop_CreateSetup(previous?.dftSetup, vDSP_Length(count), direction.dftDirection) } } /// Computes an out-of-place single-precision real discrete Fourier transform. /// /// - Parameter dftSetup: A DCT setup object. /// - Parameter inputReal: Input vector - real part. /// - Parameter inputImaginary: Input vector - imaginary part. /// - Parameter outputReal: Output vector - real part. /// - Parameter outputImaginary: Output vector - imaginary part. public static func transform<U, V>(dftSetup: OpaquePointer, inputReal: U, inputImaginary: U, outputReal: inout V, outputImaginary: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Float, V.Element == Float { inputReal.withUnsafeBufferPointer { Ir in inputImaginary.withUnsafeBufferPointer { Ii in outputReal.withUnsafeMutableBufferPointer { Or in outputImaginary.withUnsafeMutableBufferPointer { Oi in vDSP_DFT_Execute(dftSetup, Ir.baseAddress!, Ii.baseAddress!, Or.baseAddress!, Oi.baseAddress!) } } } } } /// Releases a DFT setup object. public static func destroySetup(_ setup: OpaquePointer) { vDSP_DFT_DestroySetup(setup) } } @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) extension vDSP.VectorizableDouble: vDSP_DFTFunctions { /// Returns a data structure for use with to perform a discrete Fourier transform /// /// - Parameter previous: a previous vDSP_DFT instance to share data with. /// - Parameter count: the number of real elements to be transformed. /// - Parameter direction: Specifies the transform direction. /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. public static func makeDFTSetup<T>(previous: vDSP.DFT<T>? = nil, count: Int, direction: vDSP.FourierTransformDirection, transformType: vDSP.DFTTransformType) -> OpaquePointer? where T : vDSP_FloatingPointDiscreteFourierTransformable { switch transformType { case .complexComplex: return vDSP_DFT_zop_CreateSetupD(previous?.dftSetup, vDSP_Length(count), direction.dftDirection) case .complexReal: return vDSP_DFT_zrop_CreateSetupD(previous?.dftSetup, vDSP_Length(count), direction.dftDirection) } } /// Computes an out-of-place single-precision real discrete Fourier transform. /// /// - Parameter dftSetup: A DCT setup object. /// - Parameter inputReal: Input vector - real part. /// - Parameter inputImaginary: Input vector - imaginary part. /// - Parameter outputReal: Output vector - real part. /// - Parameter outputImaginary: Output vector - imaginary part. public static func transform<U, V>(dftSetup: OpaquePointer, inputReal: U, inputImaginary: U, outputReal: inout V, outputImaginary: inout V) where U : AccelerateBuffer, V : AccelerateMutableBuffer, U.Element == Double, V.Element == Double { inputReal.withUnsafeBufferPointer { Ir in inputImaginary.withUnsafeBufferPointer { Ii in outputReal.withUnsafeMutableBufferPointer { Or in outputImaginary.withUnsafeMutableBufferPointer { Oi in vDSP_DFT_ExecuteD(dftSetup, Ir.baseAddress!, Ii.baseAddress!, Or.baseAddress!, Oi.baseAddress!) } } } } } /// Releases a DFT setup object. public static func destroySetup(_ setup: OpaquePointer) { vDSP_DFT_DestroySetupD(setup) } }
apache-2.0
a62985af3d5dee4a0c6da12be5f31398
44.890578
120
0.524904
6.180106
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 15 - PokeFinder/PokeFinder/ViewController.swift
1
5721
// // ViewController.swift // PokeFinder // // Created by Per Kristensen on 21/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import UIKit import Firebase class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() var mapHasCenteredOnce = false var geoFire: GeoFire! var geoFireRef: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.userTrackingMode = .follow geoFireRef = FIRDatabase.database().reference() geoFire = GeoFire(firebaseRef: geoFireRef) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) locationAuthStatus() } func locationAuthStatus() { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { mapView.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { mapView.showsUserLocation = true } } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2000, 2000) mapView.setRegion(coordinateRegion, animated: true) } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { if let location = userLocation.location { if !mapHasCenteredOnce { centerMapOnLocation(location: location) mapHasCenteredOnce = true } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var annotationView: MKAnnotationView? if annotation.isKind(of: MKUserLocation.self) { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User") annotationView?.image = UIImage(named: "ash") } else if let deqAnno = mapView.dequeueReusableAnnotationView(withIdentifier: "Pokemon") { annotationView = deqAnno annotationView?.annotation = annotation } else { let av = MKAnnotationView(annotation: annotation, reuseIdentifier: "Pokemon") av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) annotationView = av } if let annotationView = annotationView, let anno = annotation as? PokeAnnotation { annotationView.canShowCallout = true annotationView.image = UIImage(named: "\(anno.pokemonNumber)") let button = UIButton() button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) button.setImage(UIImage(named: "map"), for: .normal) annotationView.rightCalloutAccessoryView = button } return annotationView } func createSighting(forLocation location: CLLocation, withPokemon pokeId: Int) { geoFire.setLocation(location, forKey: "\(pokeId)") } func showSightingsOnMap(location: CLLocation) { let circleQuery = geoFire!.query(at: location, withRadius: 2.5) _ = circleQuery?.observe(.keyEntered, with: { (key, location) in if let key = key, let location = location { let annotation = PokeAnnotation(coordinate: location.coordinate, pokemonNumber: Int(key)!) self.mapView.addAnnotation(annotation) } }) } func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) showSightingsOnMap(location: location) } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let anno = view.annotation as? PokeAnnotation { let placemark = MKPlacemark(coordinate: anno.coordinate) let destination = MKMapItem(placemark: placemark) destination.name = "Pokeman Sighting" let regionDistance: CLLocationDistance = 1000 let regionSpan = MKCoordinateRegionMakeWithDistance(anno.coordinate, regionDistance, regionDistance) let options = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span), MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] as [String : Any] MKMapItem.openMaps(with: [destination], launchOptions: options) } } // MARK: - IBActions @IBAction func spotPokemon(_ sender: UIButton) { performSegue(withIdentifier: "SelectPokemonViewController", sender: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SelectPokemonViewController" { if let destination = segue.destination as? SelectPokemonViewController { destination.completed = { (pokeId) in let location = CLLocation(latitude: self.mapView.centerCoordinate.latitude, longitude: self.mapView.centerCoordinate.longitude) self.createSighting(forLocation: location, withPokemon: pokeId) } } } } }
mit
899faf2ac329c8c4b03b30d0019b4215
38.448276
258
0.65472
5.680238
false
false
false
false
RylynnLai/V2EX_sf
V2EXData/RLDataManager.swift
1
4494
// // RLDataManager.swift // V2EX // // Created by LLZ on 16/5/4. // Copyright © 2016年 LLZ. All rights reserved. // import UIKit import CoreData class RLDataManager { static let sharedManager = RLDataManager() // MARK: - Core Data stack // 获取程序数据存放文档的路径 lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.rylynn.V2EX" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() // 托管对象模型 lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("V2EX", withExtension: "momd")!//获取V2EX.xcdatamodeld文件的路径 return NSManagedObjectModel(contentsOfURL: modelURL)!// 通过momd文件对应的模型初始化托管对象模型 }() //持久性存储区 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let options = [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true] let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() // 托管上下文对象 lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator// 设置托管对象上下文管理的持久存储区 return managedObjectContext }() // MARK: - Core Data support // 保存上下文 func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
6d6d41a2f50241aec21ba5c12890c04c
49.988235
291
0.69213
5.590968
false
false
false
false
Mark-SS/ABBadgeVuew
BadgeView/ViewController.swift
1
2859
// // ViewController.swift // BadgeView // // Created by gongliang on 16/4/21. // Copyright © 2016年 AB. All rights reserved. // import UIKit let kNumBadges = 2 let kViewBackgroundColor = UIColor(red: 0.357, green: 0.757, blue: 0.357, alpha: 1) let kSquareSideLength: CGFloat = 64.0 let kSquareCornerRadius: CGFloat = 10.0 let kMarginBetwwenSquares: CGFloat = 60.0 let kSquareColor = UIColor(red: 0.004, green: 0.349, blue: 0.616, alpha: 1) class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = kViewBackgroundColor let scrollView = UIScrollView(frame: self.view.bounds) self.view.addSubview(scrollView) let viewWidth = self.view.bounds.width let numberOfSquaresPerRow = Int(viewWidth / (kSquareSideLength + kMarginBetwwenSquares)) let kInitialXOffset = (viewWidth - (CGFloat(numberOfSquaresPerRow) * kSquareSideLength)) / CGFloat(numberOfSquaresPerRow) var xOffset = kInitialXOffset let kInitialYOffset = kInitialXOffset var yOffset = kInitialYOffset let rectangleBounds = CGRectMake(0, 0, kSquareSideLength, kSquareSideLength) let rectangleShadowPath = UIBezierPath(roundedRect: rectangleBounds, byRoundingCorners: .AllCorners, cornerRadii: CGSizeMake(kSquareCornerRadius, kSquareCornerRadius)).CGPath for i in 0 ..< kNumBadges { let rectangle = UIView(frame: CGRectIntegral(CGRectMake(40 + xOffset, 10 + yOffset, rectangleBounds.width, rectangleBounds.height))) rectangle.backgroundColor = kSquareColor rectangle.layer.cornerRadius = kSquareCornerRadius rectangle.layer.shadowColor = UIColor.blackColor().CGColor; rectangle.layer.shadowOffset = CGSizeMake(0.0, 3.0) rectangle.layer.shadowOpacity = 0.4 rectangle.layer.shadowRadius = 1.0 rectangle.layer.shadowPath = rectangleShadowPath let badgeView = ABBadgeView(parentView: rectangle, alignment: ABBadgeViewAlignment.TopRight) badgeView.badgeText = String(i) scrollView.addSubview(rectangle) scrollView.sendSubviewToBack(rectangle) xOffset += kSquareSideLength + kMarginBetwwenSquares if xOffset > self.view.bounds.width - kSquareSideLength { xOffset = kInitialXOffset yOffset += kSquareSideLength + kMarginBetwwenSquares } } scrollView.contentSize = CGSizeMake(scrollView.frame.width, yOffset) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6650e49fbf1fc7b21c7653a4cc1551a8
36.090909
182
0.662115
5.090909
false
false
false
false
yuwang17/WYExtensionUtil
WYExtensionUtil/WYExtensionUIImage.swift
1
1245
// // WYExtensionUIImage.swift // WYUtil // // Created by Wang Yu on 11/9/15. // Copyright © 2015 Wang Yu. All rights reserved. // import UIKit extension UIImage { func scaleByPercent(percent: CGFloat) -> UIImage { let w = self.size.width * percent let h = self.size.height * percent return self.scaleFromImage(CGSizeMake(w, h)) } func scaleFromImage(size: CGSize) -> UIImage { UIGraphicsBeginImageContext(size) self.drawInRect(CGRectMake(0, 0, size.width, size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func subImageByRect(rect: CGRect) -> UIImage! { let subImageRef: CGImageRef = CGImageCreateWithImageInRect(self.CGImage, rect)! let smallBounds = CGRect(x: 0, y: 0, width: CGImageGetWidth(subImageRef), height: CGImageGetHeight(subImageRef)) UIGraphicsBeginImageContext(smallBounds.size) let context = UIGraphicsGetCurrentContext() CGContextDrawImage(context, smallBounds, subImageRef) let smallImage = UIImage(CGImage: subImageRef) UIGraphicsEndImageContext() return smallImage } }
mit
c4a84fd364bd705f6bd3ec5bca4e8828
30.923077
120
0.671222
4.766284
false
false
false
false
mruvim/SimpleLoadingButton
SimpleLoadingButton/Classes/SimpleLoadingView.swift
1
7084
// // SimpleLoadingView.swift // SimpleLoadingView // // Created by Ruva on 7/1/16. // Copyright (c) 2016 Ruva. All rights reserved. // import UIKit internal class SimpleLoadingView: UIView { //MARK: - Private fileprivate var viewsArray:[UIView] = [] fileprivate let kLoadingViewAlpha:CGFloat = 0.6 fileprivate let kScaleFactor:CGFloat = 1.1 fileprivate var animationDuration:Double = 2.0 private var animatingShapeSize:CGSize = CGSize(width: 10, height: 10) private var loadingIndicatorColor:UIColor = UIColor.white //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(withFrame frame: CGRect, animationDuration duration:Double = 2.0, animatingShapeSize shapeSize:CGSize = CGSize(width: 10, height: 10), loadingIndicatorColor color:UIColor = UIColor.white) { self.init(frame: frame) animationDuration = duration animatingShapeSize = shapeSize loadingIndicatorColor = color setupView() } /** Setup loading view */ private func setupView() -> Void { let centerViewFrame = CGRect(x: frame.midX - animatingShapeSize.width / 2, y: frame.midY - animatingShapeSize.height / 2, width: animatingShapeSize.width, height: animatingShapeSize.height) let centerView = createCircleView(withFrame:centerViewFrame) addSubview(centerView) centerView.translatesAutoresizingMaskIntoConstraints = false centerView.widthAnchor.constraint(equalToConstant: animatingShapeSize.width).isActive = true centerView.heightAnchor.constraint(equalToConstant: animatingShapeSize.height).isActive = true centerView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true centerView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true var leftViewFrame = centerViewFrame leftViewFrame.origin.x = centerViewFrame.origin.x - animatingShapeSize.width - 5 let leftView = createCircleView(withFrame: leftViewFrame) addSubview(leftView) leftView.translatesAutoresizingMaskIntoConstraints = false leftView.widthAnchor.constraint(equalToConstant: animatingShapeSize.width).isActive = true leftView.heightAnchor.constraint(equalToConstant: animatingShapeSize.height).isActive = true leftView.rightAnchor.constraint(equalTo: centerView.leftAnchor, constant: -5).isActive = true leftView.centerYAnchor.constraint(equalTo: centerView.centerYAnchor).isActive = true var rightViewFrame = centerViewFrame rightViewFrame.origin.x = centerViewFrame.origin.x + animatingShapeSize.width + 5 let rightView = createCircleView(withFrame:rightViewFrame) addSubview(rightView) rightView.translatesAutoresizingMaskIntoConstraints = false rightView.widthAnchor.constraint(equalToConstant: animatingShapeSize.width).isActive = true rightView.heightAnchor.constraint(equalToConstant: animatingShapeSize.height).isActive = true rightView.leftAnchor.constraint(equalTo: centerView.rightAnchor, constant: 5).isActive = true rightView.centerYAnchor.constraint(equalTo: centerView.centerYAnchor).isActive = true viewsArray = [leftView, centerView, rightView] } /** Factory method to create animating views - parameter size: Size of the loading circle - returns: UIView masked to circle shape */ fileprivate func createCircleView(withFrame circleFrame:CGRect) -> UIView { let shapeLayer = CAShapeLayer() shapeLayer.path = UIBezierPath(ovalIn: CGRect(x:0, y:0, width:circleFrame.width, height:circleFrame.height)).cgPath let ovalView = UIView(frame:circleFrame) ovalView.backgroundColor = loadingIndicatorColor ovalView.layer.mask = shapeLayer ovalView.alpha = kLoadingViewAlpha return ovalView } } extension SimpleLoadingView { //MARK: - Start / Stop animation /** Start loading animation */ func startAnimation() -> Void { weak var leftView = viewsArray[0] weak var centerView = viewsArray[1] weak var rightView = viewsArray[2] UIView.animateKeyframes(withDuration: animationDuration, delay:0, options:[.beginFromCurrentState, .repeat], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration:1/4.0, animations: { [unowned self] in centerView?.alpha = self.kLoadingViewAlpha rightView?.alpha = self.kLoadingViewAlpha leftView?.alpha = 1 leftView?.transform = CGAffineTransform.identity.scaledBy(x: self.kScaleFactor, y: self.kScaleFactor) rightView?.transform = CGAffineTransform.identity centerView?.transform = CGAffineTransform.identity }) UIView.addKeyframe(withRelativeStartTime: 1/4.0, relativeDuration:1/4.0, animations: { [unowned self] in leftView?.transform = CGAffineTransform.identity rightView?.transform = CGAffineTransform.identity centerView?.transform = CGAffineTransform.identity.scaledBy(x: self.kScaleFactor, y: self.kScaleFactor) leftView?.alpha = self.kLoadingViewAlpha rightView?.alpha = self.kLoadingViewAlpha centerView?.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 2/4.0, relativeDuration:1/4.0, animations: { [unowned self] in rightView?.transform = CGAffineTransform.identity.scaledBy(x: self.kScaleFactor, y: self.kScaleFactor) leftView?.transform = CGAffineTransform.identity centerView?.transform = CGAffineTransform.identity leftView?.alpha = self.kLoadingViewAlpha centerView?.alpha = self.kLoadingViewAlpha rightView?.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 3/4.0, relativeDuration:1/4.0, animations: { [unowned self] in leftView?.alpha = self.kLoadingViewAlpha centerView?.alpha = self.kLoadingViewAlpha rightView?.alpha = self.kLoadingViewAlpha rightView?.transform = CGAffineTransform.identity leftView?.transform = CGAffineTransform.identity centerView?.transform = CGAffineTransform.identity }) }, completion: nil) } /** Stop loading animation */ func stopAnimation() -> Void { _ = viewsArray.map( { $0.removeFromSuperview() } ) } }
mit
ad8fe6455d3fdeffa9b4fb1cb0c2c3d6
42.195122
210
0.651468
5.703704
false
false
false
false
msaveleva/SpriteKit-tDemo
SpriteKittDemo/GameViewController.swift
1
1559
// // GameViewController.swift // SpriteKittDemo // // Created by MariaSaveleva on 21/12/2016. // Copyright © 2016 MariaSaveleva. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true // view.showsFPS = true // view.showsNodeCount = true // view.showsPhysics = true view.showsFPS = false view.showsNodeCount = false view.showsPhysics = false } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
mit
b88679360262825905f146e4f1161cef
25.40678
77
0.578306
5.317406
false
false
false
false
BurntCaramel/Lantern
Lantern/PageViewController.swift
1
13824
// // PageViewController.swift // Hoverlytics for Mac // // Created by Patrick Smith on 29/03/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Cocoa import WebKit import LanternModel import BurntFoundation typealias PageViewControllerGoogleOAuth2TokenCallback = (_ tokenJSONString: String) -> () open class PageViewController: NSViewController { var splitViewController: NSSplitViewController! @IBOutlet var URLField: NSTextField! @IBOutlet var crawlWhileBrowsingCheckButton: NSButton! var webViewController: PageWebViewController! { didSet { prepareWebViewController(webViewController!) } } var crawlWhileBrowsing: Bool = true var GoogleOAuth2TokenJSONString: String? var hoverlyticsPanelDidReceiveGoogleOAuth2TokenCallback: PageViewControllerGoogleOAuth2TokenCallback? // TODO: remove var navigatedURLDidChangeCallback: ((_ URL: URL) -> ())? let minimumWidth: CGFloat = 600.0 let minimumHeight: CGFloat = 200.0 var preferredBrowserWidth: CGFloat? { didSet { if let webViewController = webViewController { webViewController.preferredBrowserWidth = preferredBrowserWidth } } } override open func viewDidLoad() { super.viewDidLoad() view.addConstraint(NSLayoutConstraint(item: view, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: minimumWidth)) view.addConstraint(NSLayoutConstraint(item: view, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: minimumHeight)) } var webViewControllerNotificationObserver: NotificationObserver<PageWebViewControllerNotification>! //var webViewControllerNotificationObservers = [PageWebViewControllerNotification: AnyObject]() func startObservingWebViewController() { webViewControllerNotificationObserver = NotificationObserver<PageWebViewControllerNotification>(object: webViewController) webViewControllerNotificationObserver.observe(.URLDidChange) { [weak self] _ in self?.navigatedURLDidChange() } } func prepareWebViewController(_ webViewController: PageWebViewController) { #if false webViewController.wantsHoverlyticsScript = true webViewController.GoogleOAuth2TokenJSONString = GoogleOAuth2TokenJSONString webViewController.hoverlyticsPanelDidReceiveGoogleOAuth2TokenCallback = hoverlyticsPanelDidReceiveGoogleOAuth2TokenCallback #endif webViewController.prepare() webViewController.preferredBrowserWidth = preferredBrowserWidth startObservingWebViewController() } // MARK: Segue override open func prepare(for segue: NSStoryboardSegue, sender: Any?) { /*if segue.identifier == "webViewController" { webViewController = segue.destinationController as! PageWebViewController prepareWebViewController(webViewController) }*/ if segue.identifier == "activeResourceSplit" { let splitVC = segue.destinationController as! NSSplitViewController self.splitViewController = splitVC let webSplit = splitVC.splitViewItems[0] webViewController = webSplit.viewController as! PageWebViewController } } func navigatedURLDidChange() { // FIXME: ask web view controller guard let url = pageMapperProvider?.activeURL else { return } navigatedURLDidChangeCallback?(url) updateUIForURL(url) } func loadURL(_ URL: Foundation.URL) { webViewController.loadURL(URL) updateUIForURL(URL) } func updateUIForURL(_ URL: Foundation.URL) { //URLField.stringValue = URL.absoluteString } // MARK: Actions @IBAction func URLFieldChanged(_ textField: NSTextField) { if let URL = LanternModel.detectWebURL(fromString: textField.stringValue) { loadURL(URL) } } @IBAction func toggleCrawlWhileBrowsing(_ checkButton: NSButton) { let on = checkButton.state == NSControl.StateValue.on crawlWhileBrowsing = on } @IBAction func reloadBrowsing(_ sender: AnyObject?) { webViewController.reloadFromOrigin() } enum ShowToggleSegment : Int { case browser = 1 case info = 2 } @IBAction func toggleShownViews(_ sender: Any?) { guard let control = sender as? NSSegmentedControl, let cell = control.cell as? NSSegmentedCell else { return } let splitViewItems = splitViewController.splitViewItems (0 ..< cell.segmentCount).forEach() { segmentIndex in let show = cell.isSelected(forSegment: segmentIndex) splitViewItems[segmentIndex].isCollapsed = !show } } } enum PageWebViewControllerNotification: String { case URLDidChange = "HoverlyticsApp.PageWebViewControllerNotification.URLDidChange" var notificationName: String { return self.rawValue } } enum MessageIdentifier: String { case receiveWindowClose = "windowDidClose" case googleAPIAuthorizationChanged = "googleAPIAuthorizationChanged" case console = "console" } private var webViewURLObservingContext = 0 class PageWebViewController : NSViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler { var webViewConfiguration = WKWebViewConfiguration() var wantsHoverlyticsScript = false var allowsClosing = false fileprivate(set) var webView: WKWebView! var URL: Foundation.URL! var hoverlyticsPanelDocumentReadyCallback: (() -> ())? var GoogleOAuth2TokenJSONString: String? var hoverlyticsPanelDidReceiveGoogleOAuth2TokenCallback: PageViewControllerGoogleOAuth2TokenCallback? fileprivate var preferredBrowserWidthContraint: NSLayoutConstraint? fileprivate var minimumWidthContraint: NSLayoutConstraint? var preferredBrowserWidth: CGFloat? { didSet { if let preferredBrowserWidthContraint = preferredBrowserWidthContraint { view.removeConstraint(preferredBrowserWidthContraint) self.preferredBrowserWidthContraint = nil } if let preferredBrowserWidth = preferredBrowserWidth { let constraint = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: preferredBrowserWidth) view.addConstraint(constraint) preferredBrowserWidthContraint = constraint } } } func prepare() { let preferences = WKPreferences() preferences.javaEnabled = false preferences.plugInsEnabled = false #if DEBUG preferences.setValue(true, forKey: "developerExtrasEnabled") #endif webViewConfiguration.preferences = preferences let userContentController = webViewConfiguration.userContentController func addBundledUserScript(_ scriptNameInBundle: String, injectAtStart: Bool = false, injectAtEnd: Bool = false, forMainFrameOnly: Bool = true, sourceReplacements: [String:String]? = nil) { let scriptURL = Bundle.main.url(forResource: scriptNameInBundle, withExtension: "js")! let scriptSource = try! NSMutableString(contentsOf: scriptURL, usedEncoding: nil) if let sourceReplacements = sourceReplacements { func replaceInTemplate(find target: String, replace replacement: String) { scriptSource.replaceOccurrences(of: target, with: replacement, options: NSString.CompareOptions(rawValue: 0), range: NSMakeRange(0, scriptSource.length)) } for (placeholderID, value) in sourceReplacements { replaceInTemplate(find: placeholderID, replace: value) } } if injectAtStart { let script = WKUserScript(source: scriptSource as String, injectionTime: .atDocumentStart, forMainFrameOnly: forMainFrameOnly) userContentController.addUserScript(script) } if injectAtEnd { let script = WKUserScript(source: scriptSource as String, injectionTime: .atDocumentEnd, forMainFrameOnly: forMainFrameOnly) userContentController.addUserScript(script) } } addBundledUserScript("console", injectAtStart: true) userContentController.add(self, name: "console") if true { addBundledUserScript("userAgent", injectAtStart: true) } if allowsClosing { addBundledUserScript("windowClose", injectAtStart: true) userContentController.add(self, name: MessageIdentifier.receiveWindowClose.rawValue) } if wantsHoverlyticsScript { addBundledUserScript("insertHoverlytics", injectAtEnd: true) #if true let tokenJSONString: String? = GoogleOAuth2TokenJSONString if let tokenJSONString = tokenJSONString { addBundledUserScript("setPanelAuthorizationToken", injectAtEnd: true, forMainFrameOnly: false, sourceReplacements: [ "__TOKEN__": tokenJSONString ]) } #endif addBundledUserScript("panelAuthorizationChanged", injectAtEnd: true, forMainFrameOnly: false) userContentController.add(self, name: MessageIdentifier.googleAPIAuthorizationChanged.rawValue) } webViewConfiguration.userContentController = userContentController webView = WKWebView(frame: NSRect.zero, configuration: webViewConfiguration) webView.navigationDelegate = self webView.uiDelegate = self webView.allowsBackForwardNavigationGestures = true if true { // Required by TypeKit to serve the correct fonts. webView.setValue("Safari/600.4.10", forKey: "applicationNameForUserAgent") } //fillViewWithChildView(webView) view.addSubview(webView) webView.translatesAutoresizingMaskIntoConstraints = false let minimumWidthContraint = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .lessThanOrEqual, toItem: view, attribute: .width, multiplier: 1.0, constant: 0.0) minimumWidthContraint.priority = NSLayoutConstraint.Priority(rawValue: 750) view.addConstraint( minimumWidthContraint ) self.minimumWidthContraint = minimumWidthContraint addLayoutConstraint(toMatch: .width, withChildView:webView, identifier:"width", priority: NSLayoutConstraint.Priority(rawValue: 250)) addLayoutConstraint(toMatch: .height, withChildView:webView, identifier:"height") addLayoutConstraint(toMatch: .centerX, withChildView:webView, identifier:"centerX") addLayoutConstraint(toMatch: .top, withChildView:webView, identifier:"top") webView.addObserver(self, forKeyPath: "URL", options: .new, context: &webViewURLObservingContext) view.wantsLayer = true view.layer?.backgroundColor = NSColor.black.cgColor } deinit { webView.removeObserver(self, forKeyPath: "URL", context: &webViewURLObservingContext) } func loadURL(_ url: Foundation.URL) { self.URL = url webView.load(URLRequest(url: url)) } func reloadFromOrigin() { webView.reloadFromOrigin() } fileprivate func mainQueue_notify(_ identifier: PageWebViewControllerNotification, userInfo: [String:AnyObject]? = nil) { let nc = NotificationCenter.default nc.post(name: Notification.Name(rawValue: identifier.notificationName), object: self, userInfo: userInfo) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } if context == &webViewURLObservingContext { switch keyPath { //case #keyPath(WKWebView.url): case "URL": pageMapperProvider?.activeURL = webView.url default: break } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // MARK: WKNavigationDelegate /* func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> ()) { switch navigationAction.navigationType { case .LinkActivated, .BackForward, .Other: if navigationAction.targetFrame?.mainFrame ?? false { let request = navigationAction.request if let URL = request.URL { didNavigateToURL(URL) } } default: break } decisionHandler(.Allow) } */ /* func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> ()) { } */ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { #if DEBUG print("didFinishNavigation \(navigation)") #endif } // MARK: WKUIDelegate func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { let innerPageViewController = PageWebViewController(nibName: nil, bundle: nil) innerPageViewController.view = NSView(frame: NSRect(x: 0, y: 0, width: 500.0, height: 500.0)) configuration.userContentController = WKUserContentController() innerPageViewController.webViewConfiguration = configuration innerPageViewController.wantsHoverlyticsScript = false innerPageViewController.allowsClosing = true innerPageViewController.prepare() // http://www.google.com/analytics/ presentAsSheet(innerPageViewController) return innerPageViewController.webView } // MARK: WKScriptMessageHandler func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if let messageIdentifier = MessageIdentifier(rawValue: message.name) { switch messageIdentifier { case .receiveWindowClose: if allowsClosing { dismiss(nil) } case .googleAPIAuthorizationChanged: if let body = message.body as? [String:AnyObject] { if body["googleClientAPILoaded"] != nil { //println("googleClientAPILoaded \(body)") } else if let tokenJSONString = body["tokenJSONString"] as? String { hoverlyticsPanelDidReceiveGoogleOAuth2TokenCallback?(tokenJSONString) #if DEBUG print("tokenJSONString \(tokenJSONString)") #endif } } case .console: #if DEBUG && false println("CONSOLE") if let messageBody = message.body as? [String: AnyObject] { println("CONSOLE \(messageBody)") } #endif } } else { print("Unhandled script message \(message.name)") } } }
apache-2.0
3139499bf5627ea273f68c04ea2b6c43
32.230769
190
0.763455
4.628055
false
false
false
false
DianQK/CardTilt
CardTilt-swift-final/CardTilt/MainViewController.swift
1
2049
// // MainViewController.swift // CardTilt // // Created by Ray Fix on 6/25/14. // Updated by Ray Fix on 4/12/15 // Copyright (c) 2014 Razeware LLC. All rights reserved. // Updated for Swift 2.0 by DianQK on 7/6/15. // import UIKit class MainViewController: UITableViewController { var members: [Member] = [] var preventAnimation = Set<NSIndexPath>() // Mark: - Model func loadModel() { let path = NSBundle.mainBundle().pathForResource("TeamMembers", ofType: "json") members = Member.loadMembersFromFile(path!) } // Mark: - View Lifetime override func viewDidLoad() { super.viewDidLoad() // appearance and layout customization self.tableView.backgroundView = UIImageView(image:UIImage(named:"background")) self.tableView.estimatedRowHeight = 280 self.tableView.rowHeight = UITableViewAutomaticDimension // load our model loadModel(); } // Mark: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return members.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Card", forIndexPath: indexPath) as! CardTableViewCell let member = members[indexPath.row] cell.useMember(member) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if !preventAnimation.contains(indexPath) { preventAnimation.insert(indexPath) TipInCellAnimator.animate(cell) } } }
mit
48d2301df1299193111374a2a983dbba
30.045455
134
0.66081
5.161209
false
false
false
false
guipanizzon/ioscreator
IOS8SwiftPlayMusicTutorial/IOS8SwiftPlayMusicTutorial/ViewController.swift
38
1730
// // ViewController.swift // IOS8SwiftPlayMusicTutorial // // Created by Arthur Knopper on 31/05/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet var trackTitle: UILabel! @IBOutlet var playedTime: UILabel! var audioPlayer = AVAudioPlayer() var isPlaying = false var timer:NSTimer! @IBAction func playOrPauseMusic(sender: AnyObject) { if isPlaying { audioPlayer.pause() isPlaying = false } else { audioPlayer.play() isPlaying = true timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTime", userInfo: nil, repeats: true) } } @IBAction func stopMusic(sender: AnyObject) { audioPlayer.stop() audioPlayer.currentTime = 0 isPlaying = false } override func viewDidLoad() { super.viewDidLoad() trackTitle.text = "Future Islands - Tin Man" var path = NSBundle.mainBundle().URLForResource("Future Islands - Tin Man", withExtension: "mp3") var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: path!, error: &error) } func updateTime() { var currentTime = Int(audioPlayer.currentTime) var minutes = currentTime/60 var seconds = currentTime - minutes * 60 playedTime.text = NSString(format: "%02d:%02d", minutes,seconds) as String } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
8aa406135279b3931eba7f6895464d16
25.615385
131
0.619653
4.95702
false
false
false
false
GoogleCloudPlatform/google-cloud-iot-arduino
examples/complex/esp32/ios-gateway/extras/iOS_IoTCore_Client_Demo/SwiftUIClient.swift
1
4344
//************************************************************************** // Copyright 2020 Google // 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 SwiftUI class contentViewDelegate : ObservableObject { @Published var toDisconnect: Bool = false } struct SwiftUIClient: View { @ObservedObject var delegate: contentViewDelegate @ObservedObject var viewController: IoTBLEView @State var tempMQTT: String = "MQTT Terminal" @State var tempData: String = "Temp Data" @State var connectedSate : Bool = false @State var filename : String = "3973-ripples" @State var type:String = "Disconnect from Cloud" var body: some View { ZStack { Group { Rectangle() .fill(Color("Background")).frame(maxWidth:.infinity, maxHeight:.infinity).edgesIgnoringSafeArea(.all) RoundedRectangle(cornerRadius: 20) .fill(Color("Background")) .frame(width:300,height: 200) .shadow(color: Color("LightShadow"), radius: 8, x: -8, y: -8) .shadow(color: Color("DarkShadow"), radius: 8, x: 8, y: 8) .offset(x: 0, y: -200) RoundedRectangle(cornerRadius: 20) .fill(Color("Background")) .frame(width:300,height: 200) .shadow(color: Color("LightShadow"), radius: 8, x: -8, y: -8) .shadow(color: Color("DarkShadow"), radius: 8, x: 8, y: 8) .offset(x: 0, y: 60) Text(viewController.command) .offset(x: 0, y: -200) .frame(width:280,height: 180) .foregroundColor(Color("textcolor")) Text(viewController.sensorData) .frame(width:280,height: 180) .offset(x: 0, y: 60) .foregroundColor(Color("textcolor")) } Group{ Image("IoTCore").resizable().frame(width: 50, height: 50).position(x: 50, y: 25) Text("MQTT Client").foregroundColor(Color("textcolor")).font(.headline).position(x: 140, y: 16) Text("Gateway Device").foregroundColor(Color("textcolor")).font(.subheadline).position(x: 145, y: 35) } Group { if(viewController.command == ""){ LottieView(filename:"3517-growing-circle").frame(width: 50, height: 50).position(x: 350, y: 25) } else { LottieView(filename:filename).frame(width: 50, height: 50).position(x: 350, y: 25) } Button(action: { // your action here if(self.delegate.toDisconnect == false){ self.viewController.command = "" self.delegate.toDisconnect = true self.self.type = "Connect to Cloud" }else{ self.delegate.toDisconnect = false self.self.type = "Disconnect Cloud" } }) { Text(self.type) }.frame(width: 180, height: 25) .padding() .foregroundColor(.white) .background(Color("Button")) .cornerRadius(40) .padding(.horizontal, 50).position(x: 205, y: 680) } } } } struct SwiftUIObservingUIKit_Previews: PreviewProvider { static var previews: some View { SwiftUIClient(delegate: contentViewDelegate(), viewController: IoTBLEView()) } }
apache-2.0
804f36f725f6bffffbb3af41f14e4ce3
37.785714
117
0.514733
4.815965
false
false
false
false
CPC-Coder/CPCBannerView
Example/CPCBannerView/CPCBannerView/Default/CPCBannerViewDefaultCell.swift
2
1195
// // CPCBannerViewDefaultCellCollectionViewCell.swift // bannerView // // Created by 鹏程 on 17/7/5. // Copyright © 2017年 pengcheng. All rights reserved. // /*-------- 温馨提示 --------*/ /* CPCBannerViewDefault --> collectionView上有lab (所有cell共享控件) CPCBannerViewCustom --> 每个cell上都有lab(cell都有独有控件) CPCBannerViewTextOnly --> 只有文字 */ /*-------- 温馨提示 --------*/ import UIKit class CPCBannerViewDefaultCell: UICollectionViewCell { lazy var imgV: UIImageView = { let imgV = UIImageView() imgV.contentMode = .scaleToFill imgV.clipsToBounds = true return imgV }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupUI() -> () { addSubview(imgV) } override func layoutSubviews() { super.layoutSubviews() imgV.frame = bounds } }
mit
65260fa00f843a323d7f454615e2d161
15.558824
58
0.516874
4.540323
false
false
false
false
hyperoslo/CollectionAnimations
Demo/Demo/AppDelegate.swift
1
556
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let vc = ViewController() let nav = UINavigationController(rootViewController: vc) self.window!.rootViewController = nav self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }
mit
b6632784acc8467c69997852bf1332f3
26.8
125
0.753597
5.346154
false
false
false
false
Turistforeningen/SjekkUT
ios/SjekkUt/views/style/DntLabel.swift
1
1917
// // DntTitleLabel.swift // SjekkUt // // Created by Henrik Hartz on 30/09/2016. // Copyright © 2016 Den Norske Turistforening. All rights reserved. // import Foundation enum Style: String { case heading = "heading" case title = "title" case subTitle = "subtitle" case body = "body" case subTitleGray = "subtitlegray" case ribbon = "ribbon" case placemark = "placemark" } class DntLabel: UILabel { @IBInspectable var style: String = "" { didSet { setupFont() } } override func awakeFromNib() { super.awakeFromNib() setupFont() } func setupFont() { switch style { case Style.heading.rawValue: textColor = DntColor.darkRed() font = UIFont.init(name:"DTL Nobel TOT", size:CGFloat.init(17*scaleFactor()))! case Style.title.rawValue: textColor = DntColor.titleForeground() font = UIFont.init(name:"DTLNobelTOT-Light", size:CGFloat.init(17*scaleFactor()))! case Style.body.rawValue: textColor = DntColor.titleForeground() font = UIFont.init(name:"DTLNobelTOT-Light", size:CGFloat.init(15*scaleFactor()))! case Style.subTitle.rawValue: textColor = DntColor.titleForeground() font = UIFont.init(name:"DTLNobelTOT-Light", size:CGFloat.init(12*scaleFactor()))! case Style.subTitleGray.rawValue: textColor = DntColor.titleLightForeground() font = UIFont.init(name:"DTLNobelTOT-Light", size:CGFloat.init(12*scaleFactor()))! case Style.ribbon.rawValue: textColor = UIColor.white font = UIFont.init(name:"DTLNobelTOT-Light", size:CGFloat.init(15))! case Style.placemark.rawValue: textColor = DntColor.green() default: textColor = UIColor.cyan break } } }
mit
8c31b7d002bd9f3916385e9e35a84d22
26.768116
94
0.606994
4.286353
false
false
false
false
MoonfaceRainbowGun/MFRG
Sholes/Sholes/Input Events/MFKeyboardEventManager.swift
1
2883
// // MFKeyboardEventManager.swift // Sholes // // Created by Wang Jinghan on 18/8/17. // Copyright © 2017 MFRG. All rights reserved. // import Cocoa class MFKeyboardEventManager: NSObject { static let sharedInstance: MFKeyboardEventManager = MFKeyboardEventManager() fileprivate var buffers = Set<MFBuffer>() override init() { super.init() } func startListening() { self.listenToEvent(); } func addBuffer(buffer: MFBuffer) { self.buffers.insert(buffer) } fileprivate func listenToEvent() { let eventType = 1 << CGEventType.keyDown.rawValue | 1 << CGEventType.flagsChanged.rawValue guard let eventTap: CFMachPort = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(eventType), callback: didReceiveKeyboardEvent, userInfo: nil) else { return } DispatchQueue(label: "keyboard-catching-queue").async { let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes) CGEvent.tapEnable(tap: eventTap, enable: true) CFRunLoopRun() } } fileprivate func didReceiveKeyDownEvent(event: CGEvent) { let keyCode = event.getIntegerValueField(.keyboardEventKeycode) self.notifyBufferForKeyCode(keyCode: Int(keyCode)) } fileprivate func didReceiveFlagsChangedEvent(event: CGEvent) { let keyCode = event.getIntegerValueField(.keyboardEventKeycode) self.notifyBufferForKeyCode(keyCode: Int(keyCode)) } fileprivate func notifyBufferForKeyCode(keyCode: Int) { for buffer in self.buffers { buffer.pushKeyCode(keycode: keyCode) } } } var previousFlag: UInt64 = 0; var capsOn: Bool = false; fileprivate func didReceiveKeyboardEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? { let manager = MFKeyboardEventManager.sharedInstance; if type == .keyDown { manager.didReceiveKeyDownEvent(event: event); } else if type == .flagsChanged { if event.flags.rawValue > previousFlag { manager.didReceiveFlagsChangedEvent(event: event) } else if capsOn { if event.flags.intersection(CGEventFlags.maskAlphaShift) == CGEventFlags(rawValue: 0) { capsOn = false; manager.didReceiveFlagsChangedEvent(event: event) } } if event.flags.intersection(CGEventFlags.maskAlphaShift) == CGEventFlags.maskAlphaShift { capsOn = true; } previousFlag = event.flags.rawValue } return Unmanaged.passRetained(event) }
unlicense
30c497cade5bd9f9306d5994a86f26a2
33.309524
232
0.663428
4.716858
false
false
false
false
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Quick/Sources/Quick/Hooks/ExampleHooks.swift
162
1282
/** A container for closures to be executed before and after each example. */ final internal class ExampleHooks { internal var befores: [BeforeExampleWithMetadataClosure] = [] internal var afters: [AfterExampleWithMetadataClosure] = [] internal var phase: HooksPhase = .nothingExecuted internal func appendBefore(_ closure: @escaping BeforeExampleWithMetadataClosure) { befores.append(closure) } internal func appendBefore(_ closure: @escaping BeforeExampleClosure) { befores.append { (_: ExampleMetadata) in closure() } } internal func appendAfter(_ closure: @escaping AfterExampleWithMetadataClosure) { afters.append(closure) } internal func appendAfter(_ closure: @escaping AfterExampleClosure) { afters.append { (_: ExampleMetadata) in closure() } } internal func executeBefores(_ exampleMetadata: ExampleMetadata) { phase = .beforesExecuting for before in befores { before(exampleMetadata) } phase = .beforesFinished } internal func executeAfters(_ exampleMetadata: ExampleMetadata) { phase = .aftersExecuting for after in afters { after(exampleMetadata) } phase = .aftersFinished } }
mit
c2b4e24591f5602bd3a67dea98de32df
29.52381
87
0.671607
5.319502
false
false
false
false
The-iPocalypse/BA-iOS-Application
src/BAViewController.swift
1
7738
// // BAViewController.swift // BA-iOS-Application // // Created by Samuel Bellerose on 2016-02-12. // Copyright © 2016 Samuel Bellerose. All rights reserved. // import UIKit import MapKit import CoreLocation class BAViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var baMapView: MKMapView! @IBOutlet weak var locationBtn: UIButton! @IBOutlet weak var listUIView: UIView! @IBOutlet weak var closeBtn: UIButton! var selectedGoodDeed: GoodDeed? private let annotationSegueIdentifier = "AnnotationModalSegueIdentifier" @IBOutlet weak var goodDeedTableView: UITableView! private var locationManager:CLLocationManager! = nil private var mapChangedFromUserInteraction = false private var shouldUpdateLocation = true private var listViewIsOpen = false private var listViewYOriginalPosition: CGFloat! = nil //Fictive GoodDeed to mock the map var goodDeedArray: [GoodDeed] = [] var firstGoodDeed: GoodDeed? override func viewDidLoad() { super.viewDidLoad() closeBtn.hidden = true listViewYOriginalPosition = listUIView.frame.origin.y + 70 //Adding 70 for top layout guide //Handle touch on listView let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:")) listUIView.addGestureRecognizer(tap) //TableView goodDeedTableView.delegate = self goodDeedTableView.dataSource = self let tblView = UIView(frame: CGRectZero) goodDeedTableView.tableFooterView = tblView goodDeedTableView?.tableFooterView!.hidden = true goodDeedTableView.backgroundColor = UIColor.clearColor() //Handle touch on close btn closeBtn.addTarget(self, action: Selector("closeListView"), forControlEvents: .TouchUpInside) //MapView baMapView.showsUserLocation = true baMapView.delegate = self locationBtn.addTarget(self, action: Selector("resetUpdateLocation"), forControlEvents: .TouchUpInside) //LocationManager locationManager = CLLocationManager() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() placeMarks() } else { print("Location service disabled") } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GoodDeedCell", forIndexPath: indexPath) as! GoodDeedCell return cell } func placeMarks() { UserRequest.sharedInstance.getUser() { (user: User) in self.goodDeedArray = user.goodDeeds } self.baMapView.addAnnotations(self.goodDeedArray) } func handleTap(gestureRecognizer: UITapGestureRecognizer) { let xPosition = listUIView.frame.origin.x let yPosition = baMapView.frame.origin.y let height = listUIView.frame.size.height let width = listUIView.frame.size.width UIView.animateWithDuration(0.2, animations: { self.listUIView.frame = CGRectMake(xPosition, yPosition, width, height) }) listViewIsOpen = true closeBtn.hidden = false } func closeListView() { let xPosition = listUIView.frame.origin.x let yPosition = listViewYOriginalPosition let height = listUIView.frame.size.height let width = listUIView.frame.size.width UIView.animateWithDuration(0.2, animations: { self.listUIView.frame = CGRectMake(xPosition, yPosition, width, height) }) listViewIsOpen = false closeBtn.hidden = true } func resetUpdateLocation() { shouldUpdateLocation = true } private func mapViewRegionDidChangeFromUserInteraction() -> Bool { let view = baMapView.subviews[0] // Look through gesture recognizers to determine whether this region change is from user interaction if let gestureRecognizers = view.gestureRecognizers { for recognizer in gestureRecognizers { if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) { return true } } } return false } func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) { mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction() if (mapChangedFromUserInteraction) { shouldUpdateLocation = false } } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { if (mapChangedFromUserInteraction) { shouldUpdateLocation = false } } func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { let button = UIButton(type: .DetailDisclosure) button.frame = CGRectMake(0, 0, 23, 23) button.addTarget(self, action: "baDetailTapped:", forControlEvents: .TouchUpInside) view.rightCalloutAccessoryView = button if let a = view.annotation as? GoodDeed { let imgView = UIImageView() imgView.image = UIImage(named: a.creator.name.lowercaseString) imgView.frame = CGRectMake(0, 0, 50, 50) view.leftCalloutAccessoryView = imgView } selectedGoodDeed = view.annotation as? GoodDeed } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if shouldUpdateLocation { let userLocation = CLLocation(latitude: (manager.location?.coordinate.latitude)! , longitude: (manager.location?.coordinate.longitude)!) centerMapOnLocation(userLocation) } } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 4000 * 2.0, 4000 * 2.0) baMapView.setRegion(coordinateRegion, animated: true) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error.debugDescription) } func baDetailTapped(sender: UIButton) { performSegueWithIdentifier(annotationSegueIdentifier, sender: sender) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let id = segue.identifier { if id == annotationSegueIdentifier { let nav = segue.destinationViewController as! UINavigationController let vc = nav.viewControllers.first as! BASubscriptionViewController vc.goodDeed = selectedGoodDeed } } super.prepareForSegue(segue, sender: sender) } func distanceBetweenUserAndGoodDeed(source:CLLocation,destination:CLLocation) -> Double { let distanceMeters = source.distanceFromLocation(destination) return (distanceMeters / 1000) } func generateRouteBetweenTwoCoordinates(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) { } }
mit
659fb61e450d084c1e6a4e31693f2b17
35.158879
148
0.66085
5.748143
false
false
false
false
AlexLombry/SwiftMastery-iOS10
PlayGround/ComputedProperties.playground/Contents.swift
1
1659
//: Playground - noun: a place where people can play import UIKit // Can be declared in a class, struct, enumeration, use them anywhere in your code. // They do not store any value inside and net get and set struct Math { var width = 10.0 var height = 10.0 var area: Double { get { return width * height } set(newArea) { let squareRoot = sqrt(newArea) width = squareRoot height = squareRoot } // // Shorthand version // set { // let squareRoot = sqrt(newValue) // width = squareRoot // height = squareRoot // } } } // Empty init var squared = Math.init() squared.width squared.height squared.area squared.area = 50 squared.width squared.height squared.area // Memberwise init var squared2 = Math.init(width: 20, height: 20) squared2.area // Property Observers // There are just for the setter (willSet and didSet keyword) // Only used with var // willSet is called just before a value is stored // didSet is called just after a value is stored class MyBank { var bankBalance: Double = 0.0 { // to avoid newValue default name, we can put our variable name instead willSet(newBalance) { print("About to set the bank account to \(newBalance)") } didSet { if bankBalance > oldValue { print("Added \(bankBalance - oldValue)") } } } } var bank = MyBank() // show by how much the count raise bank.bankBalance = 500 bank.bankBalance = 3700.87 bank.bankBalance = 187
apache-2.0
8e8dbcf918ea50de4f55b408fbc34e31
13.681416
83
0.594937
4.137157
false
false
false
false
kdawgwilk/KarmaAPI
Sources/App/Models/Group.swift
1
1826
import Vapor import Fluent import Foundation final class Group: BaseModel, Model { var name: String var description: String? init(name: String, description: String? = nil) { self.name = name self.description = description super.init() } override required init(node: Node, in context: Context) throws { name = try node.extract("name") description = try node.extract("description") try super.init(node: node, in: context) } override func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "created_on": createdOn, "name": name, "description": description ]) } static func prepare(_ database: Database) throws { try database.create("groups") { group in prepare(model: group) group.string("name") group.string("description", optional: true) } } static func revert(_ database: Database) throws { try database.delete("groups") } } // MARK: Merge extension Group { func merge(updates: Group) { super.merge(updates: updates) name = updates.name description = updates.description ?? description } } // MARK: Relationships extension Group { func users() throws -> Siblings<User> { return try siblings() } func tasks() throws -> Children<Task> { return children() } func rewards() throws -> Children<Reward> { return children() } func scores() throws -> Children<Score> { return children() } func userTasks() throws -> Children<UserTask> { return children() } func userRewards() throws -> Children<UserReward> { return children() } }
mit
68fc23312f31eff2a55bab987b0a9e5d
21.825
68
0.578861
4.47549
false
false
false
false
kpedersen00/patronus
Patronus/MeViewController.swift
1
3531
// // MeViewController.swift // Patronus // // Created by Monica Sun on 7/12/15. // Copyright (c) 2015 Monica Sun. All rights reserved. // import UIKit class MeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var meImage: UIImageView! @IBOutlet weak var meName: UILabel! @IBOutlet weak var phoneNum: UILabel! @IBOutlet weak var streetAddr: UILabel! var numReports: Int! let dataAPI = DataAPI() var survivors = [Person]() var me: Person! var myId = 1 // TODO: populate w/ user login id var incidents = [Incident]() var newIncident: Incident? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.backgroundColor = UIColor.lightGrayColor() // self.navigationController?.navigationBar.backgroundColor = UIColor(red: (43/255), green: (11/255), blue: (90/255), alpha: 1.0) meImage.layer.cornerRadius = 5 numReports = 1 tableView.dataSource = self tableView.delegate = self if let newIncident = newIncident as Incident? { incidents.append(newIncident) } dataAPI.listAllSurvivors({ (survivors, error) -> () in if error != nil { NSLog("ERROR: listAllSurvivors: \(error)") } else { self.survivors = survivors for s in survivors { if s.id == self.myId { self.me = s self.meName.text = s.name self.phoneNum.text = s.phoneNumber self.streetAddr.text = s.streetAddr } } } }) dataAPI.listAllIncidents({ (incidents, error) -> () in if error != nil { NSLog("ERROR: listAllIncidents: \(error)") } else { self.incidents = incidents self.tableView.reloadData() } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return incidents.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("myReportCell", forIndexPath: indexPath) as! MyReportCell if indexPath.row < incidents.count { let i = incidents[indexPath.row] cell.incident = i cell.incidentDesc.text = i.message! cell.datetime.text = i.datetime! } else { NSLog("ERROR: \(indexPath.row) invalid index for incidents.count: \(incidents.count)") } return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0f94d69487736529e17961249465a6e1
31.694444
136
0.58482
4.945378
false
false
false
false
nineteen-apps/themify
Sources/Element.swift
1
3450
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-04-25 by Ronaldo Faria Lima // This file purpose: Theme element declarations/implementations import Foundation import UIKit /// Abstraction for an element to be themified. class Element { /// List of attributes to be themified for this element var attributes: Set<Attribute>! /// This element proxy let element: UIAppearance.Type! init? (className: String) { element = NSObject.swiftClassFromString(className: className) as? UIAppearance.Type if element == nil { return nil } } } // MARK: - Hashable protocol compliance extension Element: Hashable { var hashValue: Int { return element.appearance().hash } static func == (first: Element, second: Element) -> Bool { return first.element == second.element } } // MARK: - Functionality Implementation extension Element { var proxy: UIAppearance { if let container = (attributes.filter { $0.type == .container }).first { // swiftlint:disable:next force_cast return element.appearance(whenContainedInInstancesOf: [container.value as! UIAppearanceContainer.Type]) } return element.appearance() } /// Applies attributes to appearance proxies /// /// - Throws: ThemifyError.invalidProxyConfiguration func applyAttributes(usingOldValues: Bool = false) throws { let proxy = element.appearance() for attribute in attributes { if attribute.type == .container { // Container is not taken into account. Skip it. continue } if let getSelector = attribute.getSelector { if (element as AnyClass).instancesRespond(to: getSelector) { attribute.oldValue = proxy.perform(getSelector) } } if (element as AnyClass).instancesRespond(to: attribute.setSelector!) { proxy.perform(attribute.setSelector, with: usingOldValues ? attribute.oldValue : attribute.value) } else { throw ThemifyError.invalidProxyConfiguration(className: String(describing: element), attributeName: attribute.name) } } } }
mit
fff13afdfe94de465408a2f694e8be1e
38.204545
115
0.662609
4.831933
false
false
false
false
JadenGeller/Yield
ArgumentPassingCoroutine.swift
1
2333
import Dispatch private let coroutineQueue = dispatch_queue_create("argument-passing-coroutine", DISPATCH_QUEUE_CONCURRENT) private enum TransportStorage<Argument, Element> { case Input(Argument) case Output(Element) } public class ArgumentPassingCoroutine<Argument, Element> { private let callerReady = dispatch_semaphore_create(0) private let coroutineReady = dispatch_semaphore_create(0) private var done: Bool = false private var transportStorage: TransportStorage<Argument, Element>? public typealias Yield = Element -> Argument public init(implementation: Yield -> ()) { dispatch_async(coroutineQueue) { // Don't start coroutine until first call. dispatch_semaphore_wait(self.callerReady, DISPATCH_TIME_FOREVER) implementation { next in // Place element in transport storage, and let caller know it's ready. self.transportStorage = .Output(next) dispatch_semaphore_signal(self.coroutineReady) // Don't continue coroutine until next call. dispatch_semaphore_wait(self.callerReady, DISPATCH_TIME_FOREVER) // Caller sent the next argument, so let's continue. defer { self.transportStorage = nil } guard case let .Some(.Input(input)) = self.transportStorage else { fatalError() } return input } // The coroutine is forever over, so let's let the caller know. self.done = true dispatch_semaphore_signal(self.coroutineReady) } } public func next(argument: Argument) -> Element? { // Make sure work is happening before we wait. guard !done else { return nil } // Return to the coroutine, passing the argument. transportStorage = .Input(argument) dispatch_semaphore_signal(callerReady) // Wait until it has finished. dispatch_semaphore_wait(coroutineReady, DISPATCH_TIME_FOREVER) // Return to the caller the result, then clear it. defer { transportStorage = nil } guard case let .Some(.Output(output)) = transportStorage else { return nil } return output } }
mit
57c4d487620794bc3914f19f18a5a150
39.224138
107
0.623232
5.017204
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Common/TZSegmentedControl.swift
1
42498
// // TZSegmentedControl.swift // CleanStore // // Created by hoi on 28/6/17. // Copyright © 2017 hoi. All rights reserved. // // // TZScrollView.swift // Pods // // Created by Tasin Zarkoob on 05/05/17. // // import UIKit class TZScrollView: UIScrollView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesBegan(touches, with: event) } else { super.touchesBegan(touches, with: event) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesMoved(touches, with: event) } else { super.touchesMoved(touches, with: event) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesEnded(touches, with: event) } else { super.touchesEnded(touches, with: event) } } } /// Selection Style for the Segmented control /// /// - Parameter textWidth : Indicator width will only be as big as the text width /// - Parameter fullWidth : Indicator width will fill the whole segment /// - Parameter box : A rectangle that covers the whole segment /// - Parameter arrow : An arrow in the middle of the segment pointing up or down depending /// on `TZSegmentedControlSelectionIndicatorLocation` /// public enum TZSegmentedControlSelectionStyle { case textWidth case fullWidth case box case arrow } public enum TZSegmentedControlSelectionIndicatorLocation{ case up case down case none // No selection indicator } public enum TZSegmentedControlSegmentWidthStyle { case fixed // Segment width is fixed case dynamic // Segment width will only be as big as the text width (including inset) } public enum TZSegmentedControlBorderType { case none // 0 case top // (1 << 0) case left // (1 << 1) case bottom // (1 << 2) case right // (1 << 3) } public enum TZSegmentedControlType { case text case images case textImages } public let TZSegmentedControlNoSegment = -1 public typealias IndexChangeBlock = ((Int) -> Void) public typealias TZTitleFormatterBlock = ((_ segmentedControl: TZSegmentedControl, _ title: String, _ index: Int, _ selected: Bool) -> NSAttributedString) open class TZSegmentedControl: UIControl { public var sectionTitles : [String]! { didSet { self.updateSegmentsRects() self.setNeedsLayout() self.setNeedsDisplay() } } public var sectionImages: [UIImage]! { didSet { self.updateSegmentsRects() self.setNeedsLayout() self.setNeedsDisplay() } } public var sectionSelectedImages : [UIImage]! /// Provide a block to be executed when selected index is changed. /// Alternativly, you could use `addTarget:action:forControlEvents:` public var indexChangeBlock : IndexChangeBlock? /// Used to apply custom text styling to titles when set. /// When this block is set, no additional styling is applied to the `NSAttributedString` object /// returned from this block. public var titleFormatter : TZTitleFormatterBlock? /// Text attributes to apply to labels of the unselected segments public var titleTextAttributes: [String:Any]? /// Text attributes to apply to selected item title text. /// Attributes not set in this dictionary are inherited from `titleTextAttributes`. public var selectedTitleTextAttributes: [String: Any]? /// Segmented control background color. /// Default is `[UIColor whiteColor]` dynamic override open var backgroundColor: UIColor! { set { TZSegmentedControl.appearance().backgroundColor = newValue } get { return TZSegmentedControl.appearance().backgroundColor } } /// Color for the selection indicator stripe public var selectionIndicatorColor: UIColor = .black { didSet { self.selectionIndicator.backgroundColor = self.selectionIndicatorColor self.selectionIndicatorBoxColor = self.selectionIndicatorColor } } public lazy var selectionIndicator: UIView = { let selectionIndicator = UIView() selectionIndicator.backgroundColor = self.selectionIndicatorColor selectionIndicator.translatesAutoresizingMaskIntoConstraints = false return selectionIndicator }() /// Color for the selection indicator box /// Default is selectionIndicatorColor public var selectionIndicatorBoxColor : UIColor = .black /// Color for the vertical divider between segments. /// Default is `[UIColor blackColor]` public var verticalDividerColor = UIColor.black //TODO Add other visual apperance properities /// Specifies the style of the control /// Default is `text` public var type: TZSegmentedControlType = .text /// Specifies the style of the selection indicator. /// Default is `textWidth` public var selectionStyle: TZSegmentedControlSelectionStyle = .textWidth /// Specifies the style of the segment's width. /// Default is `fixed` public var segmentWidthStyle: TZSegmentedControlSegmentWidthStyle = .dynamic { didSet { if self.segmentWidthStyle == .dynamic && self.type == .images { self.segmentWidthStyle = .fixed } } } /// Specifies the location of the selection indicator. /// Default is `up` public var selectionIndicatorLocation: TZSegmentedControlSelectionIndicatorLocation = .down { didSet { if self.selectionIndicatorLocation == .none { self.selectionIndicatorHeight = 0.0 } } } /// Specifies the border type. /// Default is `none` public var borderType: TZSegmentedControlBorderType = .none { didSet { self.setNeedsDisplay() } } /// Specifies the border color. /// Default is `black` public var borderColor = UIColor.black /// Specifies the border width. /// Default is `1.0f` public var borderWidth: CGFloat = 1.0 /// Default is NO. Set to YES to show a vertical divider between the segments. public var verticalDividerEnabled = false /// Index of the currently selected segment. public var selectedSegmentIndex: Int = 0 /// Height of the selection indicator stripe. public var selectionIndicatorHeight: CGFloat = 5.0 public var edgeInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) public var selectionEdgeInset = UIEdgeInsets.zero public var verticalDividerWidth = 1.0 public var selectionIndicatorBoxOpacity : Float = 0.3 ///MARK: Private variable internal var selectionIndicatorStripLayer = CALayer() internal var selectionIndicatorBoxLayer = CALayer() { didSet { self.selectionIndicatorBoxLayer.opacity = self.selectionIndicatorBoxOpacity self.selectionIndicatorBoxLayer.borderWidth = self.borderWidth } } internal var selectionIndicatorArrowLayer = CALayer() internal var segmentWidth : CGFloat = 0.0 internal var segmentWidthsArray : [CGFloat] = [] internal var scrollView : TZScrollView! = { let scroll = TZScrollView() scroll.scrollsToTop = false scroll.showsVerticalScrollIndicator = false scroll.showsHorizontalScrollIndicator = false return scroll }() //MARK: - Init Methods /// Initialiaze the segmented control with only titles. /// /// - Parameter sectionTitles: array of strings for the section title public convenience init(sectionTitles titles: [String]) { self.init() self.setup() self.sectionTitles = titles self.type = .text self.postInitMethod() } /// Initialiaze the segmented control with only images/icons. /// /// - Parameter sectionImages: array of images for the section images. /// - Parameter selectedImages: array of images for the selected section images. public convenience init(sectionImages images: [UIImage], selectedImages sImages: [UIImage]) { self.init() self.setup() self.sectionImages = images self.sectionSelectedImages = sImages self.type = .images self.segmentWidthStyle = .fixed self.postInitMethod() } /// Initialiaze the segmented control with both titles and images/icons. /// /// - Parameter sectionTitles: array of strings for the section title /// - Parameter sectionImages: array of images for the section images. /// - Parameter selectedImages: array of images for the selected section images. public convenience init(sectionTitles titles: [String], sectionImages images: [UIImage], selectedImages sImages: [UIImage]) { self.init() self.setup() self.sectionTitles = titles self.sectionImages = images self.sectionSelectedImages = sImages self.type = .textImages assert(sectionTitles.count == sectionSelectedImages.count, "Titles and images are not in correct count") self.postInitMethod() } open override func awakeFromNib() { self.setup() self.postInitMethod() } private func setup(){ self.addSubview(self.scrollView) self.backgroundColor = UIColor.clear self.isOpaque = false self.contentMode = .redraw } open func postInitMethod(){ } //MARK: - View LifeCycle open override func willMove(toSuperview newSuperview: UIView?) { if newSuperview == nil { // Control is being removed return } if self.sectionTitles != nil || self.sectionImages != nil { self.updateSegmentsRects() } } //MARK: - Drawing private func measureTitleAtIndex(index : Int) -> CGSize { if index >= self.sectionTitles.count { return CGSize.zero } let title = self.sectionTitles[index] let selected = (index == self.selectedSegmentIndex) var size = CGSize.zero if self.titleFormatter == nil { size = (title as NSString).size( attributes: selected ? self.finalSelectedTitleAttributes() : self.finalTitleAttributes()) } else { size = self.titleFormatter!(self, title, index, selected).size() } return size } private func attributedTitleAtIndex(index : Int) -> NSAttributedString { let title = self.sectionTitles[index] let selected = (index == self.selectedSegmentIndex) var str = NSAttributedString() if self.titleFormatter == nil { let attr = selected ? self.finalSelectedTitleAttributes() : self.finalTitleAttributes() str = NSAttributedString(string: title, attributes: attr) } else { str = self.titleFormatter!(self, title, index, selected) } return str } override open func draw(_ rect: CGRect) { self.backgroundColor.setFill() UIRectFill(self.bounds) self.selectionIndicatorArrowLayer.backgroundColor = self.selectionIndicatorColor.cgColor self.selectionIndicatorStripLayer.backgroundColor = self.selectionIndicatorColor.cgColor self.selectionIndicatorBoxLayer.backgroundColor = self.selectionIndicatorBoxColor.cgColor self.selectionIndicatorBoxLayer.borderColor = self.selectionIndicatorBoxColor.cgColor // Remove all sublayers to avoid drawing images over existing ones self.scrollView.layer.sublayers = nil let oldrect = rect if self.type == .text { if sectionTitles == nil { return } for (index, _) in self.sectionTitles.enumerated() { let size = self.measureTitleAtIndex(index: index) let strWidth = size.width let strHeight = size.height var rectDiv = CGRect.zero var fullRect = CGRect.zero // Text inside the CATextLayer will appear blurry unless the rect values are rounded let isLocationUp : CGFloat = (self.selectionIndicatorLocation != .up) ? 0.0 : 1.0 let isBoxStyle : CGFloat = (self.selectionStyle != .box) ? 0.0 : 1.0 let a : CGFloat = (self.frame.height - (isBoxStyle * self.selectionIndicatorHeight)) / 2 let b : CGFloat = (strHeight / 2) + (self.selectionIndicatorHeight * isLocationUp) let yPosition : CGFloat = CGFloat(roundf(Float(a - b))) var newRect = CGRect.zero if self.segmentWidthStyle == .fixed { let xPosition : CGFloat = CGFloat((self.segmentWidth * CGFloat(index)) + (self.segmentWidth - strWidth) / 2) newRect = CGRect(x: xPosition, y: yPosition, width: strWidth, height: strHeight) rectDiv = self.calculateRectDiv(at: index, xoffSet: nil) fullRect = CGRect(x: self.segmentWidth * CGFloat(index), y: 0.0, width: self.segmentWidth, height: oldrect.size.height) } else { // When we are drawing dynamic widths, we need to loop the widths array to calculate the xOffset var xOffset : CGFloat = 0.0 var i = 0 for width in self.segmentWidthsArray { if index == i { break } xOffset += width i += 1 } let widthForIndex = self.segmentWidthsArray[index] newRect = CGRect(x: xOffset, y: yPosition, width: widthForIndex, height: strHeight) fullRect = CGRect(x: self.segmentWidth * CGFloat(index), y: 0.0, width: widthForIndex, height: oldrect.size.height) rectDiv = self.calculateRectDiv(at: index, xoffSet: xOffset) } // Fix rect position/size to avoid blurry labels newRect = CGRect(x: ceil(newRect.origin.x), y: ceil(newRect.origin.y), width: ceil(newRect.size.width), height: ceil(newRect.size.height)) let titleLayer = CATextLayer() titleLayer.frame = newRect titleLayer.alignmentMode = kCAAlignmentCenter if (UIDevice.current.systemVersion as NSString).floatValue < 10.0 { titleLayer.truncationMode = kCATruncationEnd } titleLayer.string = self.attributedTitleAtIndex(index: index) titleLayer.contentsScale = UIScreen.main.scale self.scrollView.layer.addSublayer(titleLayer) // Vertical Divider self.addVerticalLayer(at: index, rectDiv: rectDiv) self.addBgAndBorderLayer(with: fullRect) } } else if self.type == .images { if sectionImages == nil { return } for (index, image) in self.sectionImages.enumerated() { let imageWidth = image.size.width let imageHeight = image.size.height let a = (self.frame.height - self.selectionIndicatorHeight) / 2 let b = (imageHeight/2) + (self.selectionIndicatorLocation == .up ? self.selectionIndicatorHeight : 0.0) let y : CGFloat = CGFloat(roundf(Float(a - b))) let x : CGFloat = (self.segmentWidth * CGFloat(index)) + (self.segmentWidth - imageWidth) / 2.0 let newRect = CGRect(x: x, y: y, width: imageWidth, height: imageHeight) let imageLayer = CALayer() imageLayer.frame = newRect imageLayer.contents = image.cgImage if self.selectedSegmentIndex == index && self.sectionSelectedImages.count > index { let highlightedImage = self.sectionSelectedImages[index] imageLayer.contents = highlightedImage.cgImage } self.scrollView.layer.addSublayer(imageLayer) //vertical Divider self.addVerticalLayer(at: index, rectDiv: self.calculateRectDiv(at: index, xoffSet: nil)) self.addBgAndBorderLayer(with: newRect) } } else if self.type == .textImages { if sectionImages == nil { return } for (index, image) in self.sectionImages.enumerated() { let imageWidth = image.size.width let imageHeight = image.size.height let stringHeight = self.measureTitleAtIndex(index: index).height let yOffset : CGFloat = CGFloat(roundf(Float( ((self.frame.height - self.selectionIndicatorHeight) / 2) - (stringHeight / 2) ))) var imagexOffset : CGFloat = self.edgeInset.left var textxOffset : CGFloat = self.edgeInset.left var textWidth : CGFloat = 0.0 if self.segmentWidthStyle == .fixed { imagexOffset = (self.segmentWidth * CGFloat(index)) + (self.segmentWidth / 2) - (imageWidth / 2.0) textxOffset = self.segmentWidth * CGFloat(index) textWidth = self.segmentWidth } else { // When we are drawing dynamic widths, we need to loop the widths array to calculate the xOffset let a = self.getDynamicWidthTillSegmentIndex(index: index) imagexOffset = a.0 + (a.1 / 2) - (imageWidth / 2) textxOffset = a.0 textWidth = self.segmentWidthsArray[index] } let imageyOffset : CGFloat = CGFloat(roundf(Float( ((self.frame.height - self.selectionIndicatorHeight) / 2) + 8.0))) let imageRect = CGRect(x: imagexOffset, y: imageyOffset, width: imageWidth, height: imageHeight) var textRect = CGRect(x: textxOffset, y: yOffset, width: textWidth, height: stringHeight) // Fix rect position/size to avoid blurry labels textRect = CGRect(x: ceil(textRect.origin.x), y: ceil(textRect.origin.y), width: ceil(textRect.size.width), height: ceil(textRect.size.height)) let titleLayer = CATextLayer() titleLayer.frame = textRect titleLayer.alignmentMode = kCAAlignmentCenter if (UIDevice.current.systemVersion as NSString).floatValue < 10.0 { titleLayer.truncationMode = kCATruncationEnd } titleLayer.string = self.attributedTitleAtIndex(index: index) titleLayer.contentsScale = UIScreen.main.scale let imageLayer = CALayer() imageLayer.frame = imageRect imageLayer.contents = image.cgImage if self.selectedSegmentIndex == index && self.sectionSelectedImages.count > index { let highlightedImage = self.sectionSelectedImages[index] imageLayer.contents = highlightedImage.cgImage } self.scrollView.layer.addSublayer(imageLayer) self.scrollView.layer.addSublayer(titleLayer) self.addBgAndBorderLayer(with: imageRect) } } // Add the selection indicators if self.selectedSegmentIndex != TZSegmentedControlNoSegment { if self.selectionStyle == .arrow { if (self.selectionIndicatorArrowLayer.superlayer == nil) { self.setArrowFrame() self.scrollView.layer.addSublayer(self.selectionIndicatorArrowLayer) } } else { if (self.selectionIndicatorStripLayer.superlayer == nil) { self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() self.scrollView.layer.addSublayer(self.selectionIndicatorStripLayer) if self.selectionStyle == .box && self.selectionIndicatorBoxLayer.superlayer == nil { self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() self.selectionIndicatorBoxLayer.opacity = self.selectionIndicatorBoxOpacity self.scrollView.layer.insertSublayer(self.selectionIndicatorBoxLayer, at: 0) } } } } } private func calculateRectDiv(at index: Int, xoffSet: CGFloat?) -> CGRect { var a :CGFloat if xoffSet != nil { a = xoffSet! } else { a = self.segmentWidth * CGFloat(index) } let xPosition = CGFloat( a - CGFloat(self.verticalDividerWidth / 2)) let rectDiv = CGRect(x: xPosition, y: self.selectionIndicatorHeight * 2, width: CGFloat(self.verticalDividerWidth), height: self.frame.size.height - (self.selectionIndicatorHeight * 4)) return rectDiv } // Add Vertical Divider Layer private func addVerticalLayer(at index: Int, rectDiv: CGRect) { if self.verticalDividerEnabled && index > 0 { let vDivLayer = CALayer() vDivLayer.frame = rectDiv vDivLayer.backgroundColor = self.verticalDividerColor.cgColor self.scrollView.layer.addSublayer(vDivLayer) } } private func addBgAndBorderLayer(with rect: CGRect){ // Background layer let bgLayer = CALayer() bgLayer.frame = rect self.layer.insertSublayer(bgLayer, at: 0) // Border layer if self.borderType != .none { let borderLayer = CALayer() borderLayer.backgroundColor = self.borderColor.cgColor var borderRect = CGRect.zero switch self.borderType { case .top: borderRect = CGRect(x: 0, y: 0, width: rect.size.width, height: self.borderWidth) break case .left: borderRect = CGRect(x: 0, y: 0, width: self.borderWidth, height: rect.size.height) break case .bottom: borderRect = CGRect(x: 0, y: rect.size.height, width: rect.size.width, height: self.borderWidth) break case .right: borderRect = CGRect(x: 0, y: rect.size.width, width: self.borderWidth, height: rect.size.height) break case .none: break } borderLayer.frame = borderRect bgLayer.addSublayer(borderLayer) } } private func setArrowFrame(){ self.selectionIndicatorArrowLayer.frame = self.frameForSelectionIndicator() self.selectionIndicatorArrowLayer.mask = nil; let arrowPath = UIBezierPath() var p1 = CGPoint.zero; var p2 = CGPoint.zero; var p3 = CGPoint.zero; if self.selectionIndicatorLocation == .down { p1 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width / 2, y: 0); p2 = CGPoint(x: 0, y: self.selectionIndicatorArrowLayer.bounds.size.height); p3 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width, y: self.selectionIndicatorArrowLayer.bounds.size.height) } else if self.selectionIndicatorLocation == .up { p1 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width / 2, y: self.selectionIndicatorArrowLayer.bounds.size.height); p2 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width, y:0); } arrowPath.move(to: p1) arrowPath.addLine(to: p2) arrowPath.addLine(to: p3) arrowPath.close() let maskLayer = CAShapeLayer() maskLayer.frame = self.selectionIndicatorArrowLayer.bounds maskLayer.path = arrowPath.cgPath self.selectionIndicatorArrowLayer.mask = maskLayer } /// Stripe width in range(0.0 - 1.0). /// Default is 1.0 public var indicatorWidthPercent : Double = 1.0 { didSet { if !(indicatorWidthPercent <= 1.0 && indicatorWidthPercent >= 0.0){ indicatorWidthPercent = max(0.0, min(indicatorWidthPercent, 1.5)) } } } private func frameForSelectionIndicator() -> CGRect { var indicatorYOffset : CGFloat = 0 if self.selectionIndicatorLocation == .down { indicatorYOffset = self.bounds.size.height - self.selectionIndicatorHeight + self.edgeInset.bottom } else if self.selectionIndicatorLocation == .up { indicatorYOffset = self.edgeInset.top } var sectionWidth : CGFloat = 0.0 if self.type == .text { sectionWidth = self.measureTitleAtIndex(index: self.selectedSegmentIndex).width } else if self.type == .images { sectionWidth = self.sectionImages[self.selectedSegmentIndex].size.width } else if self.type == .textImages { let stringWidth = self.measureTitleAtIndex(index: self.selectedSegmentIndex).width let imageWidth = self.sectionImages[self.selectedSegmentIndex].size.width sectionWidth = max(stringWidth, imageWidth) } var indicatorFrame = CGRect.zero if self.selectionStyle == .arrow { var widthToStartOfSelIndex : CGFloat = 0.0 var widthToEndOfSelIndex : CGFloat = 0.0 if (self.segmentWidthStyle == .dynamic) { let a = self.getDynamicWidthTillSegmentIndex(index: self.selectedSegmentIndex) widthToStartOfSelIndex = a.0 widthToEndOfSelIndex = widthToStartOfSelIndex + a.1 } else { widthToStartOfSelIndex = CGFloat(self.selectedSegmentIndex) * self.segmentWidth widthToEndOfSelIndex = widthToStartOfSelIndex + self.segmentWidth } let xPos = widthToStartOfSelIndex + ((widthToEndOfSelIndex - widthToStartOfSelIndex) / 2) - (self.selectionIndicatorHeight) indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: self.selectionIndicatorHeight * 2, height: self.selectionIndicatorHeight) } else { if self.selectionStyle == .textWidth && sectionWidth <= self.segmentWidth && self.segmentWidthStyle != .dynamic { let widthToStartOfSelIndex : CGFloat = CGFloat(self.selectedSegmentIndex) * self.segmentWidth let widthToEndOfSelIndex : CGFloat = widthToStartOfSelIndex + self.segmentWidth var xPos = (widthToStartOfSelIndex - (sectionWidth / 2)) + ((widthToEndOfSelIndex - widthToStartOfSelIndex) / 2) xPos += self.edgeInset.left indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: (sectionWidth - self.edgeInset.right), height: self.selectionIndicatorHeight) } else { if self.segmentWidthStyle == .dynamic { var selectedSegmentOffset : CGFloat = 0 var i = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } selectedSegmentOffset += width i += 1 } indicatorFrame = CGRect(x: selectedSegmentOffset + self.edgeInset.left, y: indicatorYOffset, width: self.segmentWidthsArray[self.selectedSegmentIndex] - self.edgeInset.right - self.edgeInset.left, height: self.selectionIndicatorHeight + self.edgeInset.bottom) } else { let xPos = (self.segmentWidth * CGFloat(self.selectedSegmentIndex)) + self.edgeInset.left indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: (self.segmentWidth - self.edgeInset.right - self.edgeInset.left), height: self.selectionIndicatorHeight) } } } if self.selectionStyle != .arrow { let currentIndicatorWidth = indicatorFrame.size.width let widthToMinus = CGFloat(1 - self.indicatorWidthPercent) * currentIndicatorWidth // final width indicatorFrame.size.width = currentIndicatorWidth - widthToMinus // frame position indicatorFrame.origin.x += widthToMinus / 2 } return indicatorFrame } private func getDynamicWidthTillSegmentIndex(index: Int) -> (CGFloat, CGFloat){ var selectedSegmentOffset : CGFloat = 0 var i = 0 var selectedSegmentWidth : CGFloat = 0 for width in self.segmentWidthsArray { if index == i { selectedSegmentWidth = width break } selectedSegmentOffset += width i += 1 } return (selectedSegmentOffset, selectedSegmentWidth) } private func frameForFillerSelectionIndicator() -> CGRect { if self.segmentWidthStyle == .dynamic { var selectedSegmentOffset : CGFloat = 0 var i = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } selectedSegmentOffset += width i += 1 } return CGRect(x: selectedSegmentOffset, y: 0, width:self.segmentWidthsArray[self.selectedSegmentIndex], height: self.frame.height) } return CGRect(x: self.segmentWidth * CGFloat(self.selectedSegmentIndex), y: 0, width: self.segmentWidth, height: self.frame.height) } private func updateSegmentsRects() { self.scrollView.contentInset = UIEdgeInsets.zero self.scrollView.frame = CGRect(origin: CGPoint.zero, size: self.frame.size) let count = self.sectionCount() if count > 0 { self.segmentWidth = self.frame.size.width / CGFloat(count) } if self.type == .text { if self.segmentWidthStyle == .fixed { for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(stringWidth, self.segmentWidth) } } else if self.segmentWidthStyle == .dynamic { var arr = [CGFloat]() for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right arr.append(stringWidth) } self.segmentWidthsArray = arr } } else if self.type == .images { for image in self.sectionImages { let imageWidth = image.size.width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(imageWidth, self.segmentWidth) } } else if self.type == .textImages { if self.segmentWidthStyle == .fixed { for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(stringWidth, self.segmentWidth) } } else if self.segmentWidthStyle == .dynamic { var arr = [CGFloat]() for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.right let imageWidth = self.sectionImages[index].size.width + self.edgeInset.left arr.append(max(stringWidth, imageWidth)) } self.segmentWidthsArray = arr } } self.scrollView.isScrollEnabled = true self.scrollView.contentSize = CGSize(width: self.totalSegmentedControlWidth(), height: self.frame.height) } private func sectionCount() -> Int { if self.type == .text { return self.sectionTitles.count } else { return self.sectionImages.count } } var enlargeEdgeInset = UIEdgeInsets.zero //MARK: - Touch Methods open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first guard let touchesLocation = touch?.location(in: self) else { assert(false, "Touch Location not found") return } let enlargeRect = CGRect(x: self.bounds.origin.x - self.enlargeEdgeInset.left, y: self.bounds.origin.y - self.enlargeEdgeInset.top, width: self.bounds.size.width + self.enlargeEdgeInset.left + self.enlargeEdgeInset.right, height: self.bounds.size.height + self.enlargeEdgeInset.top + self.enlargeEdgeInset.bottom) if enlargeRect.contains(touchesLocation) { var segment = 0 if self.segmentWidthStyle == .fixed { segment = Int((touchesLocation.x + self.scrollView.contentOffset.x) / self.segmentWidth) } else { // To know which segment the user touched, we need to loop over the widths and substract it from the x position. var widthLeft = touchesLocation.x + self.scrollView.contentOffset.x for width in self.segmentWidthsArray { widthLeft -= width // When we don't have any width left to substract, we have the segment index. if widthLeft <= 0 { break } segment += 1 } } var sectionsCount = 0 if self.type == .images { sectionsCount = self.sectionImages.count } else { sectionsCount = self.sectionTitles.count } if segment != self.selectedSegmentIndex && segment < sectionsCount { // Check if we have to do anything with the touch event self.setSelected(forIndex: segment, animated: true, shouldNotify: true) } } } //MARK: - Scrolling private func totalSegmentedControlWidth() -> CGFloat { if self.type != .images { if self.segmentWidthStyle == .fixed { return CGFloat(self.sectionTitles.count) * self.segmentWidth } else { let sum = self.segmentWidthsArray.reduce(0,+) return sum } } else { return CGFloat(self.sectionImages.count) * self.segmentWidth } } func scrollToSelectedSegmentIndex(animated: Bool) { var rectForSelectedIndex = CGRect.zero var selectedSegmentOffset : CGFloat = 0 if self.segmentWidthStyle == .fixed { rectForSelectedIndex = CGRect(x: (self.segmentWidth * CGFloat(self.selectedSegmentIndex)), y: 0, width: self.segmentWidth, height: self.frame.height) selectedSegmentOffset = (self.frame.width / 2) - (self.segmentWidth / 2) } else { var i = 0 var offsetter: CGFloat = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } offsetter += width i += 1 } rectForSelectedIndex = CGRect(x: offsetter, y: 0, width: self.segmentWidthsArray[self.selectedSegmentIndex], height: self.frame.height) selectedSegmentOffset = (self.frame.width / 2) - (self.segmentWidthsArray[self.selectedSegmentIndex] / 2) } rectForSelectedIndex.origin.x -= selectedSegmentOffset rectForSelectedIndex.size.width += selectedSegmentOffset * 2 self.scrollView.scrollRectToVisible(rectForSelectedIndex, animated: animated) } //MARK: - Index Change public func setSelected(forIndex index: Int, animated: Bool) { self.setSelected(forIndex: index, animated: animated, shouldNotify: false) } public func setSelected(forIndex index: Int, animated: Bool, shouldNotify: Bool) { self.selectedSegmentIndex = index self.setNeedsDisplay() if index == TZSegmentedControlNoSegment { self.selectionIndicatorBoxLayer.removeFromSuperlayer() self.selectionIndicatorArrowLayer.removeFromSuperlayer() self.selectionIndicatorStripLayer.removeFromSuperlayer() } else { self.scrollToSelectedSegmentIndex(animated: animated) if animated { // If the selected segment layer is not added to the super layer, that means no // index is currently selected, so add the layer then move it to the new // segment index without animating. if self.selectionStyle == .arrow { if self.selectionIndicatorArrowLayer.superlayer == nil { self.scrollView.layer.addSublayer(self.selectionIndicatorArrowLayer) self.setSelected(forIndex: index, animated: false, shouldNotify: true) return } } else { if self.selectionIndicatorStripLayer.superlayer == nil { self.scrollView.layer.addSublayer(self.selectionIndicatorStripLayer) if self.selectionStyle == .box && self.selectionIndicatorBoxLayer.superlayer == nil { self.scrollView.layer.insertSublayer(self.selectionIndicatorBoxLayer, at: 0) } self.setSelected(forIndex: index, animated: false, shouldNotify: true) return } } if shouldNotify { self.notifyForSegmentChange(toIndex: index) } // Restore CALayer animations self.selectionIndicatorArrowLayer.actions = nil self.selectionIndicatorStripLayer.actions = nil self.selectionIndicatorBoxLayer.actions = nil // Animate to new position CATransaction.begin() CATransaction.setAnimationDuration(0.15) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) self.setArrowFrame() self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() CATransaction.commit() } else { // Disable CALayer animations self.selectionIndicatorArrowLayer.actions = nil self.setArrowFrame() self.selectionIndicatorStripLayer.actions = nil self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() self.selectionIndicatorBoxLayer.actions = nil self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() if shouldNotify { self.notifyForSegmentChange(toIndex: index) } } } } private func notifyForSegmentChange(toIndex index:Int){ if self.superview != nil { self.sendActions(for: .valueChanged) } self.indexChangeBlock?(index) } //MARK: - Styliing Support private func finalTitleAttributes() -> [String:Any] { var defaults : [String:Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.black] if self.titleTextAttributes != nil { defaults.merge(dict: self.titleTextAttributes!) } return defaults } private func finalSelectedTitleAttributes() -> [String:Any] { var defaults : [String:Any] = self.finalTitleAttributes() if self.selectedTitleTextAttributes != nil { defaults.merge(dict: self.selectedTitleTextAttributes!) } return defaults } } extension Dictionary { mutating func merge<K, V>(dict: [K: V]){ for (k, v) in dict { self.updateValue(v as! Value, forKey: k as! Key) } } }
mit
a3848080df38286cff89b4a9b43d1940
42.056738
185
0.583665
5.55807
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Common/KBRoundedButton.swift
1
4489
// // KBRoundedButton.swift // CleanStore // // Created by hoi on 19/6/17. // Copyright © 2017 hoi. All rights reserved. // import UIKit import QuartzCore enum KBRoundedButtonBorder: Int { case all case top case bottom case left case right case topBottom case leftRight } @IBDesignable class KBRoundedButton: UIButton { @IBInspectable var borderType: Int { get { return self.border.rawValue } set(index) { self.border = KBRoundedButtonBorder(rawValue: index) ?? .all } } private var border: KBRoundedButtonBorder = .all { didSet { setNeedsDisplay() } } @IBInspectable var borderWidth: CGFloat = 1.0 { didSet { setNeedsDisplay() } } @IBInspectable var borderRadius:CGFloat = 3.0 { didSet { setNeedsDisplay() } } @IBInspectable var borderColor: UIColor = UIColor(red: 207.0/255.0, green: 208.0/255.0, blue: 209.0/255.0, alpha: 1) { didSet { setNeedsDisplay() } } @IBInspectable var backgroundColorForStateNormal:UIColor = UIColor(red: 18.0/255.0, green: 151.0/255.0, blue: 147.0/255.0, alpha: 1) { didSet { } } @IBInspectable var backgroundColorForStateSelected: UIColor = UIColor.clear { didSet { } } @IBInspectable var backgroundColorForStateHighlighted: UIColor = UIColor.clear { didSet { } } @IBInspectable var backgroundColorForStateSelectedAndHighlighted: UIColor = UIColor.clear { didSet { } } @IBInspectable var backgroundColorForStateDisabled: UIColor = UIColor.clear { didSet { } } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func draw(_ rect: CGRect) { super.draw(rect) guard border != .all else { setLayerProperties() return } let context = UIGraphicsGetCurrentContext() context?.setStrokeColor(borderColor.cgColor) context?.setLineWidth(borderWidth) drawBorder(context, rect: rect) context?.strokePath() } func setup() { // TO-DO } func setLayerProperties() { layer.backgroundColor = backgroundColorForStateNormal.cgColor layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth layer.cornerRadius = borderRadius } func resetLayerPeroperties() { layer.backgroundColor = backgroundColorForStateNormal.cgColor layer.borderColor = UIColor.clear.cgColor layer.borderWidth = 0.0 layer.cornerRadius = 0.0 } func drawBorder(_ context: CGContext?, rect: CGRect) { switch border { case .top: drawTopBorder(context, rect: rect) case .bottom: drawBottomBorder(context, rect: rect) case .right: drawRightBorder(context, rect: rect) case .left: drawLeftBorder(context, rect: rect) case .topBottom: drawTopBorder(context, rect: rect) drawBottomBorder(context, rect: rect) case .leftRight: drawLeftBorder(context, rect: rect) drawRightBorder(context, rect: rect) case .all: break } } func drawTopBorder(_ context: CGContext?, rect: CGRect) { context?.move(to: CGPoint(x: rect.minX, y: rect.minY)) context?.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) } func drawBottomBorder(_ context: CGContext?, rect: CGRect) { context?.move(to: CGPoint(x: rect.minX, y: rect.maxY)) context?.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) } func drawLeftBorder(_ context: CGContext?, rect: CGRect) { context?.move(to: CGPoint(x: rect.minX, y: rect.minY)) context?.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) } func drawRightBorder(_ context: CGContext?, rect: CGRect) { context?.move(to: CGPoint(x: rect.maxX, y: rect.minY)) context?.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) } }
mit
fa9f5a1ce7b771e6a6aa5ded21548a67
24.645714
138
0.574198
4.528759
false
false
false
false
googlecreativelab/justaline-ios
Model/Stroke.swift
1
14582
// Copyright 2018 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 ARKit import FirebaseDatabase final class Stroke: NSObject, NSCopying, FBModel { var points = [SCNVector3]() var drawnLocally = true public var mTaperLookup = [Float]() public var mTapperPoints = Int(0) var mTapperSlope = Float(0) var lineWidth = Radius.medium.rawValue var anchor: ARAnchor? var node: SCNNode? var touchStart: CGPoint = CGPoint.zero var mLineWidth: Float = 0 var positionsVec3 = [SCNVector3]() var mSide = [Float]() var mLength = [Float]() let smoothingCount = 1500 let biquadFilter = BiquadFilter(0.07, dimensions: 3) let animationFilter = BiquadFilter(0.025, dimensions: 1) var totalLength: Float = 0 var animatedLength: Float = 0 var fbReference: DatabaseReference? var creatorUid: String? var previousPoints: [String: [String: NSNumber]]? = nil public func size() -> Int { return points.count } func updateAnimatedStroke() -> Bool { var renderNeedsUpdate = false; if(!drawnLocally) { let previousLength = animatedLength animatedLength = animationFilter.update(totalLength) if(abs(animatedLength - previousLength) > 0.001){ renderNeedsUpdate = true } } return renderNeedsUpdate } deinit { print("Stroke deinit") } public func add( point: SCNVector3)->Bool { let s = points.count // Filter the point let p = biquadFilter.update(point) // Check distance, and only add if moved far enough if(s > 0){ let lastPoint = points[s - 1]; let result = point.distance(to: lastPoint) if result < lineWidth / 10 { return false } } // if(points.count <= 1){ // for _ in 0..<smoothingCount { // p = biquadFilter.update(point) // } // } totalLength += points[points.count-1].distance(to: p) // Add the point points.append(p) // Cleanup vertices that are redundant if(s > 3) { let angle = calculateAngle(index: s-2) // Remove points that have very low angle change if (angle < 0.05) { points.remove(at: (s - 2)) } else { subdivideSection(s: s - 3, maxAngle: 0.3, iteration: 0); } } prepareLine() return true } func scaleVec(vec: SCNVector3, factor: Float) -> SCNVector3{ let sX = vec.x * factor let sY = vec.y * factor let sZ = vec.z * factor return SCNVector3(sX, sY, sZ) } func addVecs(lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 { let x = lhs.x + rhs.x let y = lhs.y + rhs.y let z = lhs.z + rhs.z return SCNVector3(x, y, z) } func normalizeVec(vec: SCNVector3) -> SCNVector3 { let x = vec.x let y = vec.y let z = vec.z let sqLen = x*x + y*y + z*z let len = sqLen.squareRoot() // zero-div may occur. return SCNVector3(x / len, y / len, z / len) } func subVecs(lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 { let x = lhs.x - rhs.x; let y = lhs.y - rhs.y; let z = lhs.z - rhs.z; return SCNVector3(x, y, z); } func calcAngle(n1: SCNVector3, n2: SCNVector3) -> Float { let xx = n1.y*n2.z - n1.z*n2.y; let yy = n1.z*n2.x - n1.x*n2.z; let zz = n1.x*n2.y - n1.y*n2.x; let cross = Float(xx*xx + yy*yy + zz*zz).squareRoot() let dot = n1.x*n2.x + n1.y*n2.y + n1.z*n2.z return abs(atan2(cross, dot)) } func calculateAngle(index : Int) -> Float { let p1 = points[index-1] let p2 = points[index] let p3 = points[index+1] var x = p2.x - p1.x; var y = p2.y - p1.y; var z = p2.z - p1.z; let n1 = SCNVector3(x, y, z); x = p3.x - p2.x; y = p3.y - p2.y; z = p3.z - p2.z; let n2 = SCNVector3(x, y, z); let xx = n1.y*n2.z - n1.z*n2.y; let yy = n1.z*n2.x - n1.x*n2.z; let zz = n1.x*n2.y - n1.y*n2.x; let cross = Float(xx*xx + yy*yy + zz*zz).squareRoot() let dot = n1.x*n2.x + n1.y*n2.y + n1.z*n2.z return abs(atan2(cross, dot)) } func subdivideSection(s: Int, maxAngle: Float, iteration : Int){ if iteration == 6 { return } let p1 = points[s] let p2 = points[s + 1] let p3 = points[s + 2] var n1 = subVecs(lhs: p2, rhs: p1) var n2 = subVecs(lhs: p3, rhs: p2) let angle = calcAngle(n1: n1, n2: n2) // If angle is too big, add points if(angle > maxAngle){ n1 = scaleVec(vec: n1, factor: 0.5) n2 = scaleVec(vec: n2, factor: 0.5) n1 = addVecs(lhs: n1, rhs: p1) n2 = addVecs(lhs: n2, rhs: p2) points.insert(n1, at: s + 1 ) points.insert(n2, at: s + 3 ) subdivideSection(s: s+2, maxAngle: maxAngle, iteration: iteration+1) subdivideSection(s: s, maxAngle: maxAngle, iteration: iteration+1) } } public func get(i: Int) -> SCNVector3 { return points[i] } func setTapper(slope: Float, numPoints: Int) { if mTapperSlope != slope && numPoints != mTapperPoints { mTapperSlope = slope mTapperPoints = numPoints var v = Float(1.0) for i in (0 ... numPoints - 1).reversed() { v *= mTapperSlope; mTaperLookup[i] = v; } } } public func getLineWidth() -> Float { return lineWidth } func prepareLine() { resetMemory() let lineSize = size(); let mLineWidthMax = getLineWidth() var lengthAtPoint: Float = 0 if totalLength <= 0 { for i in 1..<lineSize { totalLength += points[i-1].distance(to: points[i]) } } var ii = 0 for i in 0...lineSize { var iGood = i if iGood < 0 { iGood = 0 } if iGood >= lineSize { iGood = lineSize - 1 } let i_m_1 = (iGood - 1) < 0 ? iGood : iGood - 1 let current = get(i:iGood) let previous = get(i:i_m_1) if (i < mTapperPoints) { mLineWidth = mLineWidthMax * mTaperLookup[i] } else if (i > lineSize - mTapperPoints) { mLineWidth = mLineWidthMax * mTaperLookup[lineSize - i] } else { mLineWidth = getLineWidth() } lengthAtPoint += previous.distance(to: current) // print("Length so far: \(lengthAtPoint)") mLineWidth = max(0, min(mLineWidthMax, mLineWidth)) ii += 1 setMemory(index:ii, pos:current, side:1.0, length: lengthAtPoint) ii += 1 setMemory(index:ii, pos:current, side:-1.0, length: lengthAtPoint) } } func resetMemory() { mSide.removeAll(keepingCapacity: true) mLength.removeAll(keepingCapacity: true) totalLength = 0 mLineWidth = 0 positionsVec3.removeAll(keepingCapacity: true) } func setMemory(index: Int, pos: SCNVector3, side: Float, length: Float) { positionsVec3.append(pos) mLength.append(length) // mNext.append(float3(next.x, next.y, next.z)) // mPrevious.append(float3(prev.x, prev.y, prev.z)) // mCounters.append(counter) mSide.append(side) } func cleanup() { resetMemory() points.removeAll() node?.removeFromParentNode() node = nil anchor = nil mTaperLookup.removeAll() mTapperPoints = 0 mTapperSlope = 0 lineWidth = 0 creatorUid = nil touchStart = .zero fbReference = nil } func copy(with zone: NSZone? = nil) -> Any { let strokeCopy = Stroke() strokeCopy.points = points.map{ (pt) in return SCNVector3Make(pt.x, pt.y, pt.z) } strokeCopy.mTaperLookup = mTaperLookup strokeCopy.mTapperPoints = mTapperPoints strokeCopy.mTapperSlope = mTapperSlope strokeCopy.lineWidth = lineWidth strokeCopy.creatorUid = creatorUid strokeCopy.node = node?.copy() as? SCNNode strokeCopy.anchor = anchor?.copy() as? ARAnchor strokeCopy.touchStart = touchStart strokeCopy.mLineWidth = mLineWidth strokeCopy.mSide = mSide strokeCopy.mLength = mLength // strokeCopy.fbReference is not copied return strokeCopy } // MARK: - FBModel Utility Methods static func from(_ dictionary: [String: Any?]) -> Stroke? { var newStroke: Stroke? if let fbPoints = dictionary[FBKey.val(.points)] as? [[String: NSNumber]], let lineWidth = dictionary[FBKey.val(.lineWidth)] as? NSNumber, let creator = dictionary[FBKey.val(.creator)] as? String { let stroke = Stroke() var anchorTransform = matrix_float4x4(1) if let firstPoint = fbPoints.first { let firstPointCoord = SCNVector3Make((firstPoint["x"]?.floatValue)!, (firstPoint["y"]?.floatValue)!, (firstPoint["z"]?.floatValue)!) anchorTransform.columns.3.x = firstPointCoord.x anchorTransform.columns.3.y = firstPointCoord.y anchorTransform.columns.3.z = firstPointCoord.z var points = [SCNVector3]() for point in fbPoints { if let x = point["x"], let y = point["y"], let z = point["z"] { let vector = SCNVector3Make(x.floatValue - firstPointCoord.x, y.floatValue - firstPointCoord.y, z.floatValue - firstPointCoord.z) points.append(vector) } } stroke.lineWidth = lineWidth.floatValue stroke.points = points stroke.creatorUid = creator stroke.anchor = ARAnchor(transform: anchorTransform) newStroke = stroke } } return newStroke } func dictionaryValue() -> [String : Any?] { guard let node = node else { print("Stroke:dictionaryValue: There was a problem converting stroke \(self) into dictionary values") return [String: Any?]() } var dictionary = [String: Any?]() var pointsDictionary = [String: [String: NSNumber]]() // print("Transform for stroke: \(String(describing: anchor?.transform))") // world space math should be incorporated into the loop below var pointObj = [String: NSNumber]() for (i,point) in points.enumerated() { pointObj["x"] = NSNumber(value: point.x + node.position.x) pointObj["y"] = NSNumber(value: point.y + node.position.y) pointObj["z"] = NSNumber(value: point.z + node.position.z) pointsDictionary[ String(i) ] = pointObj } dictionary[FBKey.val(.creator)] = creatorUid dictionary[FBKey.val(.points)] = pointsDictionary dictionary[FBKey.val(.lineWidth)] = NSNumber(value:lineWidth) previousPoints = pointsDictionary return dictionary } /// Dictionary only containing the points that changed since last call func pointsUpdateDictionaryValue() -> [String : [String: NSNumber]] { guard let node = node else { print("Stroke:pointsUpdateDictionaryValue: There was a problem converting stroke \(self) into dictionary values") return [String: [String: NSNumber]]() } var pointsArray = [String: [String: NSNumber]]() var fullPointsArray = [String: [String: NSNumber]]() // world space math should be incorporated into the loop below var pointObj = [String: NSNumber]() for (i, point) in points.enumerated() { pointObj["x"] = NSNumber(value: point.x + node.position.x) pointObj["y"] = NSNumber(value: point.y + node.position.y) pointObj["z"] = NSNumber(value: point.z + node.position.z) if let previousPoints = previousPoints, previousPoints.count > i, let previousPoint = previousPoints[String(i)] { if( pointObj["x"] != previousPoint["x"] || pointObj["y"] != previousPoint["y"] || pointObj["z"] != previousPoint["z"]){ pointsArray[ String(i) ] = pointObj } } else { pointsArray[ String(i) ] = pointObj } fullPointsArray[ String(i) ] = pointObj } previousPoints = fullPointsArray return pointsArray } }
apache-2.0
512eb8de9f246ce8d3539afff73eeb88
29.95966
125
0.515499
4.355436
false
false
false
false
AnneBlair/Aphrodite
AphroditeTests/ArrayTest.swift
1
1688
// // ArrayTest.swift // AphroditeTests // // Created by AnneBlair on 2017/10/9. // Copyright © 2017年 blog.aiyinyu.com. All rights reserved. // import XCTest class ArrayTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAccumlate() { let arrs: [Int] = [1,2,3,5] XCTAssertEqual(arrs.accumulate(0, +), [1,3,6,11]) } func testAll() { let nums = [1,2,3,4,5,6,7,8,9] XCTAssertEqual(nums.all { $0 % 2 == 0 }, false) let filNums = nums.filter { $0 % 2 == 0 } XCTAssertEqual(filNums.all { $0 % 2 == 0 }, true) } func testLast() { let arrs = ["swift","oc","c++","Java","aa"] XCTAssertEqual(arrs.last { $0.hasSuffix("a") }, arrs.last) XCTAssertEqual(arrs.last { $0.hasSuffix("1") }, nil) XCTAssertEqual(arrs.last { $0.hasPrefix("o") }, "oc") XCTAssertEqual(arrs.last { $0.hasPrefix("f") }, nil) } func testUnique() { let unique = [1,2,3,9,5,6,1,1,4,1,1].unique() XCTAssertEqual(unique, [1, 2, 3, 9, 5, 6, 4]) } func testFibonacci() { // let fibs = Array(fibonacci.prefix(10)) // XCTAssertEqual(fibs, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]) } func testHeadMirrorsTail() { let state = [1,2,3,2,1].headMirrorsTail(2) XCTAssertEqual(state, true) } }
mit
ebd701464e93163edadd8be348d68354
24.530303
111
0.552522
3.336634
false
true
false
false
JohnEstropia/CoreStore
Sources/DiffableDataSource.Target.swift
1
7370
// // DiffableDataSource.Target.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if canImport(UIKit) || canImport(AppKit) import Foundation // MARK: - DiffableDataSourc extension DiffableDataSource { // MARK: - Target /** The `DiffableDataSource.Target` protocol allows custom views to consume `ListSnapshot` diffable data similar to how `DiffableDataSource.TableViewAdapter` and `DiffableDataSource.CollectionViewAdapter` reloads data for their corresponding views. */ public typealias Target = DiffableDataSourceTarget } // MARK: - DiffableDataSource.Target /** The `DiffableDataSource.Target` protocol allows custom views to consume `ListSnapshot` diffable data similar to how `DiffableDataSource.TableViewAdapter` and `DiffableDataSource.CollectionViewAdapter` reloads data for their corresponding views. */ public protocol DiffableDataSourceTarget { // MARK: Public /** Whether `reloadData()` should be executed instead of `performBatchUpdates(updates:animated:)`. */ var shouldSuspendBatchUpdates: Bool { get } /** Deletes one or more sections. */ func deleteSections(at indices: IndexSet, animated: Bool) /** Inserts one or more sections */ func insertSections(at indices: IndexSet, animated: Bool) /** Reloads the specified sections. */ func reloadSections(at indices: IndexSet, animated: Bool) /** Moves a section to a new location. */ func moveSection(at index: IndexSet.Element, to newIndex: IndexSet.Element, animated: Bool) /** Deletes the items specified by an array of index paths. */ func deleteItems(at indexPaths: [IndexPath], animated: Bool) /** Inserts items at the locations identified by an array of index paths. */ func insertItems(at indexPaths: [IndexPath], animated: Bool) /** Reloads the specified items. */ func reloadItems(at indexPaths: [IndexPath], animated: Bool) /** Moves the item at a specified location to a destination location. */ func moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath, animated: Bool) /** Animates multiple insert, delete, reload, and move operations as a group. */ func performBatchUpdates(updates: () -> Void, animated: Bool, completion: @escaping () -> Void) /** Reloads all sections and items. */ func reloadData() } extension DiffableDataSource.Target { // MARK: Internal internal func reload<C, O>( using stagedChangeset: Internals.DiffableDataUIDispatcher<O>.StagedChangeset<C>, animated: Bool, interrupt: ((Internals.DiffableDataUIDispatcher<O>.Changeset<C>) -> Bool)? = nil, setData: (C) -> Void, completion: @escaping () -> Void ) { let group = DispatchGroup() defer { group.notify(queue: .main, execute: completion) } if self.shouldSuspendBatchUpdates, let data = stagedChangeset.last?.data { setData(data) self.reloadData() return } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) self.reloadData() return } group.enter() self.performBatchUpdates( updates: { setData(changeset.data) if !changeset.sectionDeleted.isEmpty { self.deleteSections( at: IndexSet(changeset.sectionDeleted), animated: animated ) } if !changeset.sectionInserted.isEmpty { self.insertSections( at: IndexSet(changeset.sectionInserted), animated: animated ) } if !changeset.sectionUpdated.isEmpty { self.reloadSections( at: IndexSet(changeset.sectionUpdated), animated: animated ) } for (source, target) in changeset.sectionMoved { self.moveSection( at: source, to: target, animated: animated ) } if !changeset.elementDeleted.isEmpty { self.deleteItems( at: changeset.elementDeleted.map { IndexPath(item: $0.element, section: $0.section) }, animated: animated ) } if !changeset.elementInserted.isEmpty { self.insertItems( at: changeset.elementInserted.map { IndexPath(item: $0.element, section: $0.section) }, animated: animated ) } if !changeset.elementUpdated.isEmpty { self.reloadItems( at: changeset.elementUpdated.map { IndexPath(item: $0.element, section: $0.section) }, animated: animated ) } for (source, target) in changeset.elementMoved { self.moveItem( at: IndexPath(item: source.element, section: source.section), to: IndexPath(item: target.element, section: target.section), animated: animated ) } }, animated: animated, completion: group.leave ) } } } #endif
mit
804e1882bb8d3386a21afcee3a1b8335
32.044843
249
0.554214
5.608067
false
false
false
false
devroo/onTodo
Swift/Subscripts.playground/section-1.swift
1
1726
// Playground - noun: a place where people can play import UIKit /* * 서브스크립트 (Subscripts) */ // 서브스크립트 문법(Subscript Syntax) /* subscript(index: Int) -> Int { get { // return an appropriate subscript value here } set(newValue) { // perform a suitable setting action here } } */ struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) println("six times three is \(threeTimesTable[6])") // prints "six times three is 18" // 서브스크립트 사용(Subscript Usage) var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs["bird"] = 2 numberOfLegs // 서브스크립트 옵션(Subscript Options) struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(count: rows * columns, repeatedValue: 0.0) } func indexIsValidForRow(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int, column: Int) -> Double { get { assert(indexIsValidForRow(row, column: column), "Index out of range") return grid[(row * columns) + column] } set { assert(indexIsValidForRow(row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } } } var matrix = Matrix(rows: 2, columns: 2) matrix[0, 1] = 1.5 matrix[1, 0] = 3.2 matrix // let someValue = matrix[2, 2] // this triggers an assert, because [2, 2] is outside of the matrix bounds
gpl-2.0
3652b6eb47e19933d09de54794dbfc60
23.880597
81
0.606843
3.598272
false
false
false
false
DeskConnect/SDCAlertView
Example/DemoViewController.swift
1
6247
import UIKit import SDCAlertView final class DemoViewController: UITableViewController { @IBOutlet private var typeControl: UISegmentedControl! @IBOutlet private var styleControl: UISegmentedControl! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var messageTextField: UITextField! @IBOutlet private var textFieldCountTextField: UITextField! @IBOutlet private var buttonCountTextField: UITextField! @IBOutlet private var buttonLayoutControl: UISegmentedControl! @IBOutlet private var contentControl: UISegmentedControl! @IBAction private func presentAlert() { if self.typeControl.selectedSegmentIndex == 0 { self.presentSDCAlertController() } else { self.presentUIAlertController() } } private func presentSDCAlertController() { let title = self.titleTextField.content let message = self.messageTextField.content let style = SDCAlertControllerStyle(rawValue: self.styleControl.selectedSegmentIndex)! let alert = SDCAlertController(title: title, message: message, preferredStyle: style) let textFields = Int(self.textFieldCountTextField.content ?? "0")! for _ in 0..<textFields { alert.addTextFieldWithConfigurationHandler(nil) } let buttons = Int(self.buttonCountTextField.content ?? "0")! for i in 0..<buttons { if i == 0 { alert.addAction(SDCAlertAction(title: "Cancel", style: .Preferred)) } else if i == 1 { alert.addAction(SDCAlertAction(title: "OK", style: .Default)) } else if i == 2 { alert.addAction(SDCAlertAction(title: "Delete", style: .Destructive)) } else { alert.addAction(SDCAlertAction(title: "Button \(i)", style: .Default)) } } alert.actionLayout = SDCActionLayout(rawValue: self.buttonLayoutControl.selectedSegmentIndex)! if #available(iOS 9, *) { addContentToAlert(alert) } alert.presentAnimated(true, completion: nil) } @available(iOS 9, *) private func addContentToAlert(alert: SDCAlertController) { switch self.contentControl.selectedSegmentIndex { case 1: let contentView = alert.contentView let spinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray) spinner.translatesAutoresizingMaskIntoConstraints = false spinner.startAnimating() contentView.addSubview(spinner) spinner.centerXAnchor.constraintEqualToAnchor(contentView.centerXAnchor).active = true spinner.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true spinner.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true case 2: let contentView = alert.contentView let switchControl = UISwitch() switchControl.on = true switchControl.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(switchControl) switchControl.centerXAnchor.constraintEqualToAnchor(contentView.centerXAnchor).active = true switchControl.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true switchControl.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true alert.message = "Disable switch to prevent alert dismissal" alert.shouldDismissHandler = { [unowned switchControl] _ in return switchControl.on } case 3: let bar = UIProgressView(progressViewStyle: .Default) bar.translatesAutoresizingMaskIntoConstraints = false alert.contentView.addSubview(bar) bar.leadingAnchor.constraintEqualToAnchor(alert.contentView.leadingAnchor, constant: 20).active = true bar.trailingAnchor.constraintEqualToAnchor(alert.contentView.trailingAnchor, constant: -20).active = true bar.topAnchor.constraintEqualToAnchor(alert.contentView.topAnchor).active = true bar.bottomAnchor.constraintEqualToAnchor(alert.contentView.bottomAnchor).active = true NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(updateProgressBar), userInfo: bar, repeats: true) default: break } } @objc private func updateProgressBar(timer: NSTimer) { let bar = timer.userInfo as? UIProgressView bar?.progress += 0.005 if bar?.progress >= 1 { timer.invalidate() } } private func presentUIAlertController() { let title = self.titleTextField.content let message = self.messageTextField.content let style = UIAlertControllerStyle(rawValue: self.styleControl.selectedSegmentIndex)! let alert = UIAlertController(title: title, message: message, preferredStyle: style) let textFields = Int(self.textFieldCountTextField.content ?? "0")! for _ in 0..<textFields { alert.addTextFieldWithConfigurationHandler(nil) } let buttons = Int(self.buttonCountTextField.content ?? "0")! for i in 0..<buttons { if i == 0 { alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) } else if i == 1 { alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) } else if i == 2 { alert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: nil)) } else { alert.addAction(UIAlertAction(title: "Button \(i)", style: .Default, handler: nil)) } } presentViewController(alert, animated: true, completion: nil) } } private extension UITextField { var content: String? { if let text = self.text where !text.isEmpty { return text } return self.placeholder } }
mit
51bbe5672c89c6c20cfaf0fb74fbf6f5
41.787671
108
0.638066
5.59767
false
false
false
false
yulingtianxia/Spiral
Spiral/OrdinaryHelpScene.swift
1
1883
// // HelpScene.swift // Spiral // // Created by 杨萧玉 on 14/10/19. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import SpriteKit class OrdinaryHelpScene: SKScene { func lightWithFinger(_ point:CGPoint){ if let light = self.childNode(withName: "light") as? SKLightNode { light.lightColor = SKColor.white light.position = self.convertPoint(fromView: point) } } func turnOffLight() { (self.childNode(withName: "light") as? SKLightNode)?.lightColor = SKColor.black } func back() { if !Data.sharedData.gameOver { return } DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { () -> Void in Data.sharedData.currentMode = .ordinary Data.sharedData.gameOver = false Data.sharedData.reset() let gvc = UIApplication.shared.keyWindow?.rootViewController as! GameViewController gvc.startRecordWithHandler { () -> Void in DispatchQueue.main.async(execute: { () -> Void in if self.scene is OrdinaryHelpScene { gvc.addGestureRecognizers() let scene = OrdinaryModeScene(size: self.size) let push = SKTransition.push(with: SKTransitionDirection.right, duration: 1) push.pausesIncomingScene = false self.scene?.view?.presentScene(scene, transition: push) } }) } } } override func didMove(to view: SKView) { let bg = childNode(withName: "background") as! SKSpriteNode let w = bg.size.width let h = bg.size.height let scale = max(view.frame.width/w, view.frame.height/h) bg.xScale = scale bg.yScale = scale } }
apache-2.0
878e32b263e80ddb9781806b38f1bfdf
32.981818
100
0.567148
4.614815
false
false
false
false
programmerC/JNews
Pods/Alamofire/Source/Alamofire.swift
1
12559
// // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString! } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest: NSMutableURLRequest if let request = URLString as? NSMutableURLRequest { mutableURLRequest = request } else if let request = URLString as? NSURLRequest { mutableURLRequest = request.URLRequest } else { mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) } mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download( method, URLString, parameters: parameters, encoding: encoding, headers: headers, destination: destination ) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
gpl-3.0
86148b79957ae90e34e661e34a4c049e
33.03523
117
0.709213
5.021591
false
false
false
false
spneshaei/SwiftNotif
SwiftNotif.swift
1
4011
// // SwiftNotif.swift // SwiftNotif // // Created by Seyyed Parsa Neshaei on 8/6/17. // Copyright © 2017 Seyyed Parsa Neshaei. All rights reserved. // import Foundation public class SwiftNotif { private static var allNotifs: [String: (([String: Any]) -> Void)] = [:] private static var pendingNotifs: [[String: Any?]] = [] /** Checks if a notification is observed or not. - Parameters: - key: The unique key for the notification. */ public static func isObserved(key: String) -> Bool { return allNotifs[key] != nil } /** Observes for a notification and runs the neccessary code when the notification is posted. - Parameters: - key: The unique key for the notification. This can be later used to trigger the notification. - code: The code to trigger when a new notification is posted. It receives a `context` property which can be used by the user to pass a context when triggering the notification. */ public static func observe(key: String, code: @escaping (([String: Any]) -> Void)) { allNotifs[key] = code for i in 0..<pendingNotifs.count { let pN = pendingNotifs[i] if pN["key"] as? String ?? "" == key { let context = pN["context"] as? [String: Any] ?? [:] let completion = pN["context"] as? (() -> Void) pendingNotifs.remove(at: i) trigger(key: key, context: context, completion: completion) break } } } /** Stops listening for a specified notification. To continue receiving notifications from the specified notification, it must be observed again. - Parameters: - key: The unique key for the notification to be unobserved. */ public static func unobserve(key: String) { allNotifs.removeValue(forKey: key) for i in 0..<pendingNotifs.count { let pN = pendingNotifs[i] if pN["key"] as? String ?? "" == key { pendingNotifs.remove(at: i) } } } /** Stops listening for all notifications. To continue receiving notifications, they must be observed again. */ public static func unobserveAllNotifications() { allNotifs = [:] pendingNotifs = [] } /** Triggers a notification. If the notification is not yet observed, it will wait to be triggered as soon as it is observed. To pass context and add a completion block, use the other method `trigger(key:context:completion:)` - Parameters: - key: The unique key for the notification to be triggered. */ public static func trigger(key: String) { guard let code = allNotifs[key] else { pendingNotifs.append(["key": key]) return } code([:]) } /** Triggers a notification. If the notification is not yet observed, it will wait to be triggered as soon as it is observed. - Parameters: - key: The unique key for the notification to be triggered. - context: A dictionary which is passed to the `code` block - specified when the notification was observed - as a parameter to indicate the current context. - completion: A block which will run after the notification is triggered and the `code` block - specified when the notification was observed - is called. If the notification is not observed yet, `completion` will run as soon as it is observed. */ public static func trigger(key: String, context: [String: Any], completion: (() -> Void)? = nil) { guard let code = allNotifs[key] else { pendingNotifs.append([ "key": key, "context": context, "completion": completion ]) return } code(context) guard let c = completion else { return } c() } }
mit
134fdfe4b9e6a69d695407fce6a2c71e
34.803571
248
0.598254
4.734357
false
false
false
false
netguru/ResponseDetective
ResponseDetective/Tests/Specs/RequestRepresentationSpec.swift
1
1778
// // RequestRepresentationSpec.swift // // Copyright © 2016-2020 Netguru S.A. All rights reserved. // Licensed under the MIT License. // import Foundation import Nimble import ResponseDetective import Quick internal final class RequestRepresentationSpec: QuickSpec { override func spec() { describe("RequestRepresentation") { context("after initializing with a request") { let fixtureRequest = NSMutableURLRequest( URL: URL(string: "https://httpbin.org/post")!, HTTPMethod: "POST", headerFields: [ "Content-Type": "application/json", "X-Foo": "bar", ], HTTPBody: try! JSONSerialization.data(withJSONObject: ["foo": "bar"], options: []) ) let fixtureIdentifier = "1" var sut: RequestRepresentation! beforeEach { sut = RequestRepresentation(identifier: fixtureIdentifier, request: fixtureRequest as URLRequest, deserializedBody: nil) } it("should have a correct identifier") { expect(sut.identifier).to(equal(fixtureIdentifier)) } it("should have a correct URLString") { expect(sut.urlString).to(equal(fixtureRequest.url!.absoluteString)) } it("should have a correct method") { expect(sut.method).to(equal(fixtureRequest.httpMethod)) } it("should have correct headers") { expect(sut.headers).to(equal(fixtureRequest.allHTTPHeaderFields)) } it("should have a correct body") { expect(sut.body).to(equal(fixtureRequest.httpBody)) } } } } } private extension NSMutableURLRequest { convenience init(URL: Foundation.URL, HTTPMethod: String, headerFields: [String: String], HTTPBody: Data?) { self.init(url: URL) self.httpMethod = HTTPMethod self.allHTTPHeaderFields = headerFields self.httpBody = HTTPBody } }
mit
14b771321330c8c0eadaea70dce52f18
22.381579
125
0.691615
3.922737
false
false
false
false
stevehe-campray/BSBDJ
BSBDJ/BSBDJ/Essence(精华)/Views/BSBTopicCell.swift
1
9915
// // BSBTopicCell.swift // BSBDJ // // Created by hejingjin on 16/6/2. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBTopicCell: UITableViewCell { @IBOutlet weak var cemtentLabels: UILabel! @IBOutlet weak var contentview: UIView! @IBOutlet weak var nameLable: UILabel! @IBOutlet weak var creattimeLable: UILabel! @IBOutlet weak var sinavimageview: UIImageView! @IBOutlet weak var iconImageview: UIImageView! @IBOutlet weak var sharebutton: UIButton! @IBOutlet weak var dingbutton: UIButton! @IBOutlet weak var caibutton: UIButton! @IBOutlet weak var commentbutton: UIButton! @IBOutlet weak var contentLabel: UILabel! var commentH : CGFloat = CGFloat()//最热评论高度 lazy var topicpicview : BSBTopicPicView = { () -> BSBTopicPicView in let temtopicpicview = BSBTopicPicView.topicpicview() self.contentView.addSubview(temtopicpicview) return temtopicpicview }() lazy var topicvoiceview : BSBTopicVoiceView = { () -> BSBTopicVoiceView in let temtopicvoiceview = BSBTopicVoiceView.topicVoiceView() self.contentView.addSubview(temtopicvoiceview) return temtopicvoiceview }() lazy var topicvideoview : BSBTopicVideoView = { () -> BSBTopicVideoView in let topicvideoview = BSBTopicVideoView.topicVideoView() self.contentView.addSubview(topicvideoview) return topicvideoview }() override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func awakeFromNib() { super.awakeFromNib() self.contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 40 self.cemtentLabels.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 40 let bgView = UIImageView() bgView.image = UIImage(named:"mainCellBackground") self.backgroundView = bgView; } /// 重写frame属性 override var frame: CGRect{ get{ return super.frame } set{ super.frame = CGRect(x: 10, y: newValue.origin.y + 10, width: newValue.size.width-20, height: newValue.size.height - 10) } } var topicinfo : BSBTopic?{ didSet{ iconImageview.sd_setImageWithURL(NSURL(string:(topicinfo?.profile_image) as! String), placeholderImage: UIImage(named: "defaultUserIcon")) nameLable.text = topicinfo?.name as? String // let datestr : String = let fmt : NSDateFormatter = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" let creatdate : NSDate = fmt.dateFromString((topicinfo?.create_time)! as String)! var creatimestr : String = String() /** * 格式化时间 可放入BSBTopic属性的get方法中出来 * * @return */ if creatdate.isThisYear() {//今年 if creatdate.isToday() { //今天 let cmps : NSDateComponents = NSDate().deltaFrom(creatdate) if (cmps.hour>=1){//xx 小时前 creatimestr = String(cmps.hour) + " 小时前" creattimeLable.text = creatimestr }else if(cmps.minute>1){//xx分钟前 creatimestr = String(cmps.minute) + " 分钟前" creattimeLable.text = creatimestr }else{//刚刚 creatimestr = "刚刚" creattimeLable.text = creatimestr } }else if creatdate.isYesterday(){//昨天 fmt.dateFormat = "昨天 HH:mm" creatimestr = fmt.stringFromDate(creatdate) creattimeLable.text = creatimestr }else{ //其他 fmt.dateFormat = "MM-dd HH:mm" creatimestr = fmt.stringFromDate(creatdate) creattimeLable.text = creatimestr } }else {//不是今年 creattimeLable.text = (topicinfo?.create_time as! String) } if topicinfo!.sina_v{ sinavimageview.hidden = false }else{ sinavimageview.hidden = true } /** 尼玛哦本宝宝不开心 一个NSInteger转String 尼玛要先转成Int 一个Int转CGFloat 要尼玛先 转FLoat 老子真想伤不起了 */ let dingtitle = String(Int((topicinfo?.ding)!)) let caititle: String = String(Int((topicinfo?.cai)!)) let sharetitle: String = String(Int((topicinfo?.repost)!)) let commenttitle: String = String(Int((topicinfo?.comment)!)) dingbutton.setTitle(dingtitle, forState:UIControlState.Normal) caibutton.setTitle(caititle, forState:UIControlState.Normal) sharebutton.setTitle(sharetitle, forState:UIControlState.Normal) commentbutton.setTitle(commenttitle, forState:UIControlState.Normal) contentLabel.text = topicinfo?.text as? String var cmetentH = CGRectGetHeight(contentview.frame) if topicinfo!.top_cmt.count > 0 { contentview.hidden = false; var contentstr : String = String() for cmt in (topicinfo?.top_cmt)! { let user : BSBUser = cmt.user! contentstr = contentstr + (user.username as String) + " : " + (cmt.content as String) + "\n" } //移除最后追加的一个换行符 let endindex : Int = contentstr.characters.count let str = (contentstr as NSString).substringToIndex(endindex - 1) cemtentLabels.text = str self.layoutIfNeeded() cmetentH = CGRectGetHeight(cemtentLabels.frame) + 10 + 17 }else{ contentview.hidden = true; cmetentH = 0 } self.layoutIfNeeded() var cellheight : CGFloat = CGRectGetMaxY(contentLabel.frame) + 20 + 44 if topicinfo?.type == 10 { //配置图片帖子 topicpicview.hidden = false topicvoiceview.hidden = true topicvideoview.hidden = true let width :CGFloat = UIScreen.mainScreen().bounds.width - 40 var imageheight :CGFloat = CGFloat(Float((topicinfo?.height)! / (topicinfo?.width)!)) * width if imageheight > 1000 { topicpicview.bottomButton.hidden = false imageheight = 300 }else{ topicpicview.bottomButton.hidden = true } topicinfo?.topicpicimageFrame = CGRectMake(10, cellheight - 44, width, imageheight) topicpicview.topic = topicinfo topicpicview.frame = (topicinfo?.topicpicimageFrame)! cellheight = cellheight + imageheight + 20 }else if(topicinfo?.type == 31){ //配置声音帖子 topicvoiceview.hidden = false; topicpicview.hidden = true topicvideoview.hidden = true // topicpicview.frame = (topicinfo?.topicpicimageFrame)! // topicvideoview.frame = (topicinfo?.topicvoideimageFrame)! let width :CGFloat = UIScreen.mainScreen().bounds.width - 40 let imageheight :CGFloat = CGFloat(Float((topicinfo?.height)! / (topicinfo?.width)!)) * width topicinfo?.topicvoiceimageFrame = CGRectMake(10, cellheight - 44, width, imageheight) topicvoiceview.topic = topicinfo topicvoiceview.frame = (topicinfo?.topicvoiceimageFrame)! cellheight = cellheight + imageheight + 20 }else if(topicinfo?.type == 41){ topicvideoview.hidden = false topicpicview.hidden = true topicvoiceview.hidden = true let width :CGFloat = UIScreen.mainScreen().bounds.width - 40 let imageheight :CGFloat = CGFloat(Float((topicinfo?.height)! / (topicinfo?.width)!)) * width topicinfo?.topicvoideimageFrame = CGRectMake(10, cellheight - 44, width, imageheight) topicvideoview.topic = topicinfo topicvideoview.frame = (topicinfo?.topicvoideimageFrame)! cellheight = cellheight + imageheight + 20 }else{ topicpicview.hidden = true topicvoiceview.hidden = true topicvideoview.hidden = true } commentH = cmetentH cellheight = cellheight + cmetentH topicinfo?.commentH = cmetentH topicinfo?.cellHeight = cellheight } } class func cellWithTableView(tableview:UITableView) ->BSBTopicCell{ let topiccell : String = "topicsId" let cell : BSBTopicCell = tableview.dequeueReusableCellWithIdentifier(topiccell) as! BSBTopicCell cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } }
mit
fae2edbbfb5fd07be21a99e77f7c9fed
37.125984
149
0.544093
5.434343
false
false
false
false
shamanskyh/FluidQ
Shared Models/Keystroke.swift
1
2126
// // Keystroke.swift // FluidQ // // Created by Harry Shamansky on 9/29/15. // Copyright © 2015 Harry Shamansky. All rights reserved. // import Foundation /// Modifier key enums based on Windows modifiers, since the console runs Windows /// underneath internal enum ModifierKey { case Shift case Control case Alternate case Function } internal class Keystroke: NSObject, NSCoding { /// the identifier is a unique string that represents the command var identifier: String /// the plaintext string is a human-readable word that is printed during debugging var plaintext: String? /// the key equivalent is the character that is sent to the console via HID imput var keyEquivalent: Character /// any modifier keys that should be sent to the HID // Note that a keystroke with keyEquivalent = "A" and modifierKeys = [] is // equivalent to a keystroke with keyEquivalent = "a" and modifierKeys = [Shift] var modifierKeys: [ModifierKey] = [] init(identifier: String, keyEquivalent: Character) { self.identifier = identifier self.keyEquivalent = keyEquivalent } convenience init(identifier: String, keyEquivalent: Character, plaintext: String) { self.init(identifier: identifier, keyEquivalent: keyEquivalent) self.plaintext = plaintext } // MARK: - NSCoding Protocol Conformance required init(coder aDecoder: NSCoder) { identifier = aDecoder.decodeObjectForKey("identifier") as! String plaintext = aDecoder.decodeObjectForKey("plaintext") as? String keyEquivalent = (aDecoder.decodeObjectForKey("keyEquivalent") as! String).characters.first! //modifierKeys = aDecoder.decodeObjectForKey("modifierKeys") as! [ModifierKey] } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(identifier, forKey: "identifier") aCoder.encodeObject(plaintext, forKey: "plaintext") aCoder.encodeObject(String(keyEquivalent), forKey: "keyEquivalent") //aCoder.encodeObject(modifierKeys, forKey: "modifierKeys") } }
mit
f38af062a3440dcca73bacecd35ef256
34.416667
99
0.696941
4.907621
false
false
false
false
horothesun/ImmutableGraph
Tests/ImmutableGraphTests/Graphs/FindPathTests.swift
1
6235
import XCTest import ImmutableGraph class FindPathTests: XCTestCase { func testFindPath_WithEmptyParentByVertexAndSourceSAndDestinationD_MustReturnEmptyPath() { // given typealias V = String let s = "S" let d = "D" let parentByVertex = [V: V?]() // when let result = findPath( parentByVertex: parentByVertex, source: s, destination: d) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } func testFindPath_WithOneUnparentedVertexSAndSourceSAndDestinationD_MustReturnEmptyPath() { // given typealias V = String let s = "S" let d = "D" let parentByVertex = [s: nil as V?] // when let result = findPath(parentByVertex: parentByVertex, source: s, destination: d) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } func testFindPath_WithOneUnparentedVertexDAndSourceSAndDestinationD_MustReturnEmptyPath() { // given typealias V = String let s = "S" let d = "D" let parentByVertex = [d: nil as V?] // when let result = findPath(parentByVertex: parentByVertex, source: s, destination: d) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } func testFindPath_WithUnparentedSAndSParentOfDAndSourceSAndDestinationD_MustReturnSToDPath() { // given typealias V = String let s = "S" let d = "D" let parentByVertex = [s: nil as V?, d: s] // when let result = findPath(parentByVertex: parentByVertex, source: s, destination: d) // then let expectedResult = [s, d] XCTAssertEqual(result, expectedResult) } func testFindPath_WithV1AndV2AndV3VerticesAndSourceV1AndUnreachableDestinationV3_MustReturnEmptyPath() { // given typealias V = Int let v1 = 1 let v2 = 2 let v3 = 3 let parentByVertex = [v1: v3, v2: v1, v3: nil as V?] // when let result = findPath(parentByVertex: parentByVertex, source: v1, destination: v3) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } func testFindPath_With16VerticesGraphAndSourceSAndReachableDestinationJ_MustReturnSToFToIToJPath() { // given typealias V = String let s = "S", a = "A", b = "B", c = "C", d = "D", e = "E", f = "F", g = "G", h = "H", i = "I", j = "J", k = "K", l = "L", m = "M", n = "N", o = "O" let parentByVertex = [ s: nil as V?, a: b, b: s, c: f, d: h, e: f, f: s, g: b, h: s, i: f, j: i, k: nil as V?, l: m, m: s, n: s, o: nil as V? ] // when let result = findPath(parentByVertex: parentByVertex, source: s, destination: j) // then let expectedResult = [s, f, i, j] XCTAssertEqual(result, expectedResult) } func testFindPath_With16VerticesGraphAndSourceFAndReachableDestinationJ_MustReturnFToIToJPath() { // given typealias V = String let s = "S", a = "A", b = "B", c = "C", d = "D", e = "E", f = "F", g = "G", h = "H", i = "I", j = "J", k = "K", l = "L", m = "M", n = "N", o = "O" let parentByVertex = [ s: nil as V?, a: b, b: s, c: f, d: h, e: f, f: s, g: b, h: s, i: f, j: i, k: nil as V?, l: m, m: s, n: s, o: nil as V? ] // when let result = findPath(parentByVertex: parentByVertex, source: f, destination: j) // then let expectedResult = [f, i, j] XCTAssertEqual(result, expectedResult) } func testFindPath_With16VerticesGraphAndSourceOAndUnreachableDestinationS_MustReturnEmptyPath() { // given typealias V = String let s = "S", a = "A", b = "B", c = "C", d = "D", e = "E", f = "F", g = "G", h = "H", i = "I", j = "J", k = "K", l = "L", m = "M", n = "N", o = "O" let parentByVertex = [ s: nil as V?, a: b, b: s, c: f, d: h, e: f, f: s, g: b, h: s, i: f, j: i, k: nil as V?, l: m, m: s, n: s, o: nil as V? ] // when let result = findPath(parentByVertex: parentByVertex, source: o, destination: s) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } func testFindPath_With16VerticesGraphAndSourceKAndUnreachableDestinationS_MustReturnEmptyPath() { // given typealias V = String let s = "S", a = "A", b = "B", c = "C", d = "D", e = "E", f = "F", g = "G", h = "H", i = "I", j = "J", k = "K", l = "L", m = "M", n = "N", o = "O" let parentByVertex = [ s: nil as V?, a: b, b: s, c: f, d: h, e: f, f: s, g: b, h: s, i: f, j: i, k: nil as V?, l: m, m: s, n: s, o: nil as V? ] // when let result = findPath(parentByVertex: parentByVertex, source: k, destination: s) // then let expectedResult = [V]() XCTAssertEqual(result, expectedResult) } }
mit
f31b295872dfe7e79ee69467c2f262af
29.120773
108
0.440738
4.110086
false
true
false
false
raphacarletti/JiraTracker
JiraTracker/Controllers/RegistrationViewController.swift
1
7323
// // RegistrationViewController.swift // JiraTracker // // Created by Raphael Carletti on 10/24/17. // Copyright © 2017 Raphael Carletti. All rights reserved. // import Foundation import UIKit import FirebaseAuth import FirebaseDatabase class RegistrationViewController : UIViewController { //MARK: - IBOutlets @IBOutlet var nameTextField: LoginTextField! @IBOutlet var emailTextField: LoginTextField! @IBOutlet var passwordTextField: LoginTextField! @IBOutlet var confirmPasswordTextField: LoginTextField! @IBOutlet var createAccountButton: CustomProgressButton! override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() //Settings for layout self.emailTextField.imageView.image = UIImage(named: "ic_email") self.emailTextField.textField.textColor = UIColor.black self.emailTextField.textField.placeholder = "E-mail" self.emailTextField.textField.delegate = self self.passwordTextField.imageView.image = UIImage(named: "ic_lock") self.passwordTextField.textField.textColor = UIColor.black self.passwordTextField.textField.isSecureTextEntry = true self.passwordTextField.textField.placeholder = "Password" self.passwordTextField.textField.delegate = self self.confirmPasswordTextField.imageView.image = UIImage(named: "ic_lock") self.confirmPasswordTextField.textField.textColor = UIColor.black self.confirmPasswordTextField.textField.isSecureTextEntry = true self.confirmPasswordTextField.textField.placeholder = "Confirm Password" self.confirmPasswordTextField.textField.delegate = self self.nameTextField.imageView.image = UIImage(named: "ic_profile") self.nameTextField.textField.textColor = UIColor.black self.nameTextField.textField.placeholder = "Name" self.nameTextField.textField.delegate = self self.createAccountButton.delegate = self } override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false self.createAccountButton.setInitialState(animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { nameTextField.textField.text = "" emailTextField.textField.text = "" passwordTextField.textField.text = "" confirmPasswordTextField.textField.text = "" } func goToJirasScreen(animated: Bool) { let storyboard = UIStoryboard(name: "Application", bundle: nil) let jiraScreen = storyboard.instantiateViewController(withIdentifier: "jirasScreen") self.navigationController?.pushViewController(jiraScreen, animated: animated) } func shouldPaintTextFieldsRed() { self.createAccountButton.enableCTA(enable: true) let color = Colors.progressRed self.createAccountButton.setProgressBar(progress: 1.0, buttonTitle: "Error", progressBarColor: Colors.progressRed, buttonTitleColor: UIColor.white, animated: true, completion: nil) Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { (timer) in self.createAccountButton.setInitialState(animated: true) }) if (nameTextField.textField.text?.isEmpty)! { self.nameTextField.paintBarAndImage(color: color) } if (emailTextField.textField.text?.isEmpty)! || !emailTextField.textField.text!.contains("@") { self.emailTextField.paintBarAndImage(color: color) } if (passwordTextField.textField.text?.isEmpty)! || passwordTextField.textField.text!.characters.count <= 6 { self.passwordTextField.paintBarAndImage(color: color) } if (confirmPasswordTextField.textField.text?.isEmpty)! || confirmPasswordTextField.textField.text!.characters.count <= 6{ self.confirmPasswordTextField.paintBarAndImage(color: color) } } func shouldPaintTextFieldsWhite() { let color = Colors.grayLightColor self.nameTextField.paintBarAndImage(color: color) self.emailTextField.paintBarAndImage(color: color) self.passwordTextField.paintBarAndImage(color: color) self.confirmPasswordTextField.paintBarAndImage(color: color) } } //MARK: - CustomProgressButton Delegate extension RegistrationViewController : CustomProgressButtonDelegate { func didTapCTAButton(_ sender: Any) { let button = sender as! UIButton button.isEnabled = false shouldPaintTextFieldsWhite() if let name = nameTextField.textField.text, let email = emailTextField.textField.text, let password = passwordTextField.textField.text, let confirmPassword = confirmPasswordTextField.textField.text { if name.isEmpty || email.isEmpty || password.isEmpty || confirmPassword.isEmpty { shouldPaintTextFieldsRed() } else if !email.contains("@") { shouldPaintTextFieldsRed() let alertController = self.getAlertWithOkAction(title: "Invalid mail", message: "") self.present(alertController, animated: true, completion: nil) } else if password.characters.count < 6 { shouldPaintTextFieldsRed() let alertController = self.getAlertWithOkAction(title: "Invalid password", message: "Password needs at least 6 characters.") self.present(alertController, animated: true, completion: nil) } else if password != confirmPassword { shouldPaintTextFieldsRed() let alertController = self.getAlertWithOkAction(title: "Passwords don't match", message: "") self.present(alertController, animated: true, completion: nil) } else { Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in if let error = error { button.isEnabled = true let alertController = self.getAlertWithOkAction(title: "Error creating account", message: "\(error.localizedDescription)") self.present(alertController, animated: true, completion: nil) } else { let userValue = ["name": name, "email": email] Database.database().reference().child("users").child(user!.uid).setValue(userValue) self.createAccountButton.setProgressBar(progress: 1.0, buttonTitle: "Success", progressBarColor: Colors.greenColor, buttonTitleColor: UIColor.white, animated: true, completion: nil) Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { (timer) in self.goToJirasScreen(animated: true) }) } }) } } } } //MARK: - TextFieldDelegate extension RegistrationViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } }
mit
6dcfafff129e992be88458cce50878dd
45.935897
205
0.666758
5.456036
false
false
false
false
willhains/Kotoba
code/Kotoba/SettingsViewController.swift
1
5374
// // Created by Will Hains on 2019-11-27. // Copyright © 2019 Will Hains. All rights reserved. // import Foundation import UIKit import MobileCoreServices import LinkPresentation class SettingsViewController: UIViewController, UIDocumentPickerDelegate, UINavigationControllerDelegate { @IBOutlet weak var iCloudEnabledLabel: UILabel! @IBOutlet weak var iCloudExplainerLabel: UILabel! @IBOutlet weak var clipboardImportButton: RoundedView! @IBOutlet weak var clipboardWordCount: UILabel! @IBOutlet weak var fileImportButton: RoundedView! @IBOutlet var clipboardButtonTap: UILongPressGestureRecognizer! @IBOutlet var fileButtonTap: UILongPressGestureRecognizer! @IBOutlet weak var CHOCKTUBA: UIView! @IBOutlet weak var versionInfo: UILabel! override func viewDidLoad() { if let productVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") { if let productBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") { let version = "Version \(productVersion) (\(productBuild))" self.versionInfo.text = version } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) _refreshViews() } @IBAction func closeSettings(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func importFromClipboard(_ gesture: UITapGestureRecognizer) { guard UIPasteboard.general.lines.count > 0 else { return } if gesture.state == .began { clipboardImportButton.backgroundColor = .systemFill } else if gesture.state == .ended { clipboardImportButton.backgroundColor = .tertiarySystemFill debugLog("Importing from clipboard") if let text = UIPasteboard.general.string { _import(newlineDelimitedWords: text) } } } @IBAction func importFromFile(_ gesture: UITapGestureRecognizer) { if gesture.state == .began { fileImportButton.backgroundColor = .systemFill } else if gesture.state == .ended { fileImportButton.backgroundColor = .tertiarySystemFill debugLog("Importing from file") _importFromFile() } } @IBAction func openGithub(_ sender: Any) { if let url = URL(string: "https://github.com/willhains/Kotoba") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func openICloudSettings(_ sender: Any) { if let url = URL(string: "App-prefs:root=CASTLE") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } private func _pluralizedWordCount(_ count: Int) -> String { let format = NSLocalizedString("WordCount", comment: "Count of words available") let wordCount = String.localizedStringWithFormat(format, count) return wordCount } private func _refreshViews() { // iCloud settings self.iCloudEnabledLabel.text = NSUbiquitousKeyValueStore.iCloudEnabledInSettings ? NSLocalizedString("ICLOUD_SYNC_ENABLED", comment: "Title when iCloud Sync is enabled") : NSLocalizedString("ICLOUD_SYNC_DISABLED", comment: "Title when iCloud Sync is disabled") // Import settings let count = UIPasteboard.general.lines.count clipboardWordCount.text = _pluralizedWordCount(count) self.clipboardImportButton.enabled = count > 0 } private func _import(newlineDelimitedWords text: String) { var words = wordListStore.data let countBefore = words.count let importWords = text.split(separator: "\n") .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.isEmpty } .reversed() importWords.forEach { words.add(word: Word(text: $0)) } _refreshViews() let countAfter = words.count let addedWords = countAfter - countBefore let duplicateWords = importWords.count - addedWords if addedWords < 0 { fatalError("Negative added words") } let message = String( format: NSLocalizedString("IMPORT_SUCCESS_MESSAGE", comment: "Message for successful import"), _pluralizedWordCount(importWords.count), _pluralizedWordCount(duplicateWords), _pluralizedWordCount(addedWords)) let alert = UIAlertController( title: NSLocalizedString("IMPORT_SUCCESS_TITLE", comment: "Title for successful import"), message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } private func _importFromFile() { let types: [String] = [kUTTypeText as String] let documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .import) documentPicker.delegate = self documentPicker.modalPresentationStyle = .formSheet self.present(documentPicker, animated: true, completion: nil) } public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let fileURL = urls.first else { return } debugLog("importing: \(fileURL)") do { let text = try String(contentsOf: fileURL, encoding: .utf8) _import(newlineDelimitedWords: text) } catch { debugLog("Import failed: \(error)") let alert = UIAlertController( title: NSLocalizedString("IMPORT_FAIL_TITLE", comment: "Title for failed import"), message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } }
mit
835aec872be496c80e33a03403e1ee01
30.605882
109
0.740927
3.907636
false
false
false
false
smileyborg/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo9ViewController.swift
3
3572
// // iOSDemo9ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/PureLayout/PureLayout // import UIKit import PureLayout @objc(iOSDemo9ViewController) class iOSDemo9ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .blue return view }() let redView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .red return view }() let yellowView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .yellow return view }() let greenView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .green return view }() var didSetupConstraints = false override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) blueView.addSubview(redView) redView.addSubview(yellowView) yellowView.addSubview(greenView) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func updateViewConstraints() { if (!didSetupConstraints) { // Before layout margins were introduced, this is a typical way of giving a subview some padding from its superview's edges blueView.autoPin(toTopLayoutGuideOf: self, withInset: 10.0) blueView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 10.0, bottom: 10.0, right: 10.0), excludingEdge: .top) // Set the layoutMargins of the blueView, which will have an effect on subviews of the blueView that attach to // the blueView's margin attributes -- in this case, the redView blueView.layoutMargins = UIEdgeInsets(top: 10.0, left: 20.0, bottom: 80.0, right: 20.0) redView.autoPinEdgesToSuperviewMargins() // Let the redView inherit the values we just set for the blueView's layoutMargins by setting the below property to YES. // Then, pin the yellowView's edges to the redView's margins, giving the yellowView the same insets from its superview as the redView. redView.preservesSuperviewLayoutMargins = true yellowView.autoPinEdge(toSuperviewMargin: .left) yellowView.autoPinEdge(toSuperviewMargin: .right) // By aligning the yellowView to its superview's horizontal margin axis, the yellowView will be positioned with its horizontal axis // in the middle of the redView's top and bottom margins (causing it to be slightly closer to the top of the redView, since the // redView has a much larger bottom margin than top margin). yellowView.autoAlignAxis(toSuperviewMarginAxis: .horizontal) yellowView.autoMatch(.height, to: .height, of: redView, withMultiplier: 0.5) // Since yellowView.preservesSuperviewLayoutMargins is NO by default, it will not preserve (inherit) its superview's margins, // and instead will just have the default margins of: {8.0, 8.0, 8.0, 8.0} which will apply to its subviews (greenView) greenView.autoPinEdges(toSuperviewMarginsExcludingEdge: .bottom) greenView.autoSetDimension(.height, toSize: 50.0) didSetupConstraints = true } super.updateViewConstraints() } }
mit
9fbe1c5c503c7dc34e64a8af056bd662
42.036145
146
0.648656
5.124821
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift
4
2853
// // ChartDataEntryBase.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 open class ChartDataEntryBase: NSObject { /// the y value @objc open var y = Double(0.0) /// optional spot for additional data this Entry represents @objc open var data: AnyObject? /// optional icon image @objc open var icon: NSUIImage? public override required init() { super.init() } /// An Entry represents one single entry in the chart. /// - parameter y: the y value (the actual value of the entry) @objc public init(y: Double) { super.init() self.y = y } /// - parameter y: the y value (the actual value of the entry) /// - parameter data: Space for additional data this Entry represents. @objc public init(y: Double, data: AnyObject?) { super.init() self.y = y self.data = data } /// - parameter y: the y value (the actual value of the entry) /// - parameter icon: icon image @objc public init(y: Double, icon: NSUIImage?) { super.init() self.y = y self.icon = icon } /// - parameter y: the y value (the actual value of the entry) /// - parameter icon: icon image /// - parameter data: Space for additional data this Entry represents. @objc public init(y: Double, icon: NSUIImage?, data: AnyObject?) { super.init() self.y = y self.icon = icon self.data = data } // MARK: NSObject open override func isEqual(_ object: Any?) -> Bool { if object == nil { return false } if !(object! as AnyObject).isKind(of: type(of: self)) { return false } if (object! as AnyObject).data !== data && !((object! as AnyObject).data??.isEqual(self.data))! { return false } if fabs((object! as AnyObject).y - y) > Double.ulpOfOne { return false } return true } // MARK: NSObject open override var description: String { return "ChartDataEntryBase, y \(y)" } } public func ==(lhs: ChartDataEntryBase, rhs: ChartDataEntryBase) -> Bool { if lhs === rhs { return true } if !lhs.isKind(of: type(of: rhs)) { return false } if lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data) { return false } if fabs(lhs.y - rhs.y) > Double.ulpOfOne { return false } return true }
apache-2.0
59f7eb89049a3e48d762b5eddb67e990
20.613636
103
0.532773
4.322727
false
false
false
false
alienorb/Vectorized
Vectorized/Core/SVGGradient.swift
1
2247
//--------------------------------------------------------------------------------------- // The MIT License (MIT) // // Created by Austin Fitzpatrick on 3/19/15 (the "SwiftVG" project) // Modified by Brian Christensen <[email protected]> // // Copyright (c) 2015 Seedling // Copyright (c) 2016 Alien Orb Software LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //--------------------------------------------------------------------------------------- import CoreGraphics /// the SVGGradient protocol extends SVGFillable to specify that the conforming type should /// be able to supply an CGGradient and modify it with a given opacity when asked public protocol SVGGradient: SVGFillable { var id: String { get } var stops: [GradientStop] { get } func addStop(offset: CGFloat, color: SVGColor, opacity: CGFloat) func removeStop(stop: GradientStop) func drawGradientWithOpacity(opacity: CGFloat) } /// Structure defining a gradient stop - contains an offset and a color public struct GradientStop: Equatable { var offset: CGFloat var color: SVGColor var opacity: CGFloat = 1.0 } public func ==(lhs: GradientStop, rhs: GradientStop) -> Bool { return lhs.offset == rhs.offset && lhs.color == rhs.color }
mit
e8d8400e6cc10ea81d928ec4960b544d
43.058824
91
0.696039
4.363107
false
false
false
false
TylerKuster/MeetAnotherTeam
MeetAnotherTeam/MeetAnotherTeam/Theme.swift
1
3874
// // Theme.swift // MeetAnotherTeam // // Created by Tyler Kuster on 10/9/17. // Copyright © 2017 12 Triangles. All rights reserved. // import UIKit class Theme: NSObject { func themeGrey() -> UIColor { return UIColor(red:0.392, green:0.392, blue:0.392, alpha:1.0) } func styleCellNameLabelWith(text:String) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString.init(string: text) let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) attributedString.addAttributes([NSAttributedString.Key.font : UIFont(name: "Lato-Regular", size: 17.0)!, NSAttributedString.Key.foregroundColor : themeGrey(), NSAttributedString.Key.kern : -0.1], range: textRange) return attributedString } func styleCellPositionLabelWith(text:String) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString.init(string: text) let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Lato-Regular", size: 14.0)!, range:textRange) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: themeGrey(), range:textRange) attributedString.addAttribute(NSAttributedString.Key.kern, value:-0.2, range:textRange) return attributedString } func styleProfileNameLabelWith(text:String) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString.init(string: text) let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Lato-Bold", size: 27.0)!, range:textRange) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: themeGrey(), range:textRange) attributedString.addAttribute(NSAttributedString.Key.kern, value:-0.5, range:textRange) return attributedString } func styleProfilePositionLabelWith(text:String) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString.init(string: text) let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Lato-Semibold", size: 20.0)!, range:textRange) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: themeGrey(), range:textRange) attributedString.addAttribute(NSAttributedString.Key.kern, value:-0.5, range:textRange) return attributedString } func styleProfileBioTextViewWith(text:String) -> NSMutableAttributedString { let paragraphStyle = NSMutableParagraphStyle.init() paragraphStyle.alignment = NSTextAlignment.justified let attributedString = NSMutableAttributedString.init(string: text) let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Lato-Regular", size: 18.0)!, range:textRange) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: themeGrey(), range:textRange) attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range:textRange) attributedString.addAttribute(NSAttributedString.Key.kern, value:-0.56, range:textRange) attributedString.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range:textRange) return attributedString } }
mit
ca4be4f3bf21d16a84a127ae73525866
46.814815
134
0.698683
5.226721
false
false
false
false
leosimas/ios_KerbalCampaigns
Kerbal Campaigns/Models/Bean/Task.swift
1
470
// // Task.swift // Kerbal Campaigns // // Created by SSA on 15/09/17. // Copyright © 2017 Simas Team. All rights reserved. // import RealmSwift class Task : Object { dynamic var id = "" dynamic var completed : Bool = false dynamic var name = "" let subTasks = List<SubTask>() let mission = LinkingObjects(fromType: Mission.self, property: "tasks") override static func primaryKey() -> String? { return "id" } }
apache-2.0
b46c51a3f27763922117dbf02d7356a3
19.391304
75
0.614072
3.782258
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/VASTTests/PBMVastLoaderTestOMVerificationOneInline.swift
1
3663
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import XCTest @testable import PrebidMobile class PBMVastLoaderTestOMVerificationOneInline: XCTestCase { var vastRequestSuccessfulExpectation:XCTestExpectation! override func setUp() { self.continueAfterFailure = true MockServer.shared.reset() } override func tearDown() { MockServer.shared.reset() self.vastRequestSuccessfulExpectation = nil } func testRequest() { self.vastRequestSuccessfulExpectation = self.expectation(description: "Expected VAST Load to be successful") //Make an ServerConnection and redirect its network requests to the Mock Server let conn = UtilitiesForTesting.createConnectionForMockedTest() //Make an AdConfiguration let adConfiguration = AdConfiguration() adConfiguration.adFormats = [.video] let adLoadManager = MockPBMAdLoadManagerVAST(bid: RawWinningBidFabricator.makeWinningBid(price: 0.1, bidder: "bidder", cacheID: "cache-id"), connection:conn, adConfiguration: adConfiguration) adLoadManager.mock_requestCompletedSuccess = { response in self.requestCompletedSuccess(response) } adLoadManager.mock_requestCompletedFailure = { error in XCTFail("\(error)") } let requester = PBMAdRequesterVAST(serverConnection:conn, adConfiguration: adConfiguration) requester.adLoadManager = adLoadManager if let data = UtilitiesForTesting.loadFileAsDataFromBundle("vast_om_verification_one_inline_ad.xml") { requester.buildAdsArray(data) } self.waitForExpectations(timeout: 2.0, handler: nil) } func requestCompletedSuccess(_ vastResponse: PBMAdRequestResponseVAST) { //There should be 1 ad. //An Ad can be either inline or wrapper; this should be inline. PBMAssertEq(vastResponse.ads?.count, 1) guard let ad = vastResponse.ads?.first as? PBMVastInlineAd else { XCTFail() return; } XCTAssertNotNil(ad.verificationParameters) XCTAssertEqual(ad.verificationParameters.verificationResources.count, 2) let resource1 = ad.verificationParameters.verificationResources[0] as! PBMVideoVerificationResource PBMAssertEq(resource1.url, "https://measurement.domain.com/tag.js") PBMAssertEq(resource1.vendorKey, "OpenX1") PBMAssertEq(resource1.params, "{1}") PBMAssertEq(resource1.apiFramework, "omidOpenx1") let resource2 = ad.verificationParameters.verificationResources[1] as! PBMVideoVerificationResource PBMAssertEq(resource2.url, "https://measurement.domain.com/tag2.js") PBMAssertEq(resource2.vendorKey, "OpenX2") PBMAssertEq(resource2.params, "{2}") PBMAssertEq(resource2.apiFramework, "omidOpenx2") // Must be in the end of the method self.vastRequestSuccessfulExpectation.fulfill() } }
apache-2.0
3396a26cedb97585d25d9453e280c7c6
38.268817
199
0.68483
4.955224
false
true
false
false
hikelee/cinema
Sources/App/Models/Setting.swift
1
1188
import Vapor import Fluent import HTTP final class Setting: ChannelBasedModel { static var entity: String { return "c_setting" } var id: Node? var channelId: Node? var wallpaper : String? var exists: Bool = false //used in fluent init(node: Node, in context: Context) throws { id = try? node.extract("id") channelId = try? node.extract("channel_id") wallpaper = try node.extract("wallpaper") } func makeNode() throws->Node { return try Node( node:[ "id": id, "channel_id" : channelId, "wallpaper": wallpaper, ]) } func makeLeafNode() throws -> Node { var node = try makeNode() node["parent"]=try Channel.node(channelId) return node } func validate(isCreate: Bool) throws -> [String:String] { var result:[String:String]=[:] if (channelId?.int ?? 0) == 0 { result["channel_id"] = "必选项"; }else if try (Channel.query().filter("id", .equals, channelId!).first()) == nil { result["channel_id"] = "找不到所选的渠道" } return result } }
mit
d1b0af6219772c6729abf6e5480f7027
26.116279
90
0.549743
4.062718
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/model/scene/Image.swift
1
1530
import Foundation open class Image: Node { open let srcVar: Variable<String> open var src: String { get { return srcVar.value } set(val) { srcVar.value = val } } open let xAlignVar: Variable<Align> open var xAlign: Align { get { return xAlignVar.value } set(val) { xAlignVar.value = val } } open let yAlignVar: Variable<Align> open var yAlign: Align { get { return yAlignVar.value } set(val) { yAlignVar.value = val } } open let aspectRatioVar: Variable<AspectRatio> open var aspectRatio: AspectRatio { get { return aspectRatioVar.value } set(val) { aspectRatioVar.value = val } } open let wVar: Variable<Int> open var w: Int { get { return wVar.value } set(val) { wVar.value = val } } open let hVar: Variable<Int> open var h: Int { get { return hVar.value } set(val) { hVar.value = val } } public init(src: String, xAlign: Align = .min, yAlign: Align = .min, aspectRatio: AspectRatio = .none, w: Int = 0, h: Int = 0, place: Transform = Transform.identity, opaque: Bool = true, opacity: Double = 1, clip: Locus? = nil, effect: Effect? = nil, visible: Bool = true, tag: [String] = []) { self.srcVar = Variable<String>(src) self.xAlignVar = Variable<Align>(xAlign) self.yAlignVar = Variable<Align>(yAlign) self.aspectRatioVar = Variable<AspectRatio>(aspectRatio) self.wVar = Variable<Int>(w) self.hVar = Variable<Int>(h) super.init( place: place, opaque: opaque, opacity: opacity, clip: clip, effect: effect, visible: visible, tag: tag ) } }
mit
eae9e8fa9f3f054760c6d5435e00eb4c
24.932203
295
0.668627
2.953668
false
false
false
false
proversity-org/edx-app-ios
Source/VideoTranscript.swift
1
3873
// // VideoTranscript.swift // edX // // Created by Danial Zahid on 12/19/16. // Copyright © 2016 edX. All rights reserved. // import UIKit protocol VideoTranscriptDelegate: class { func didSelectSubtitleAtInterval(time: TimeInterval) } class VideoTranscript: NSObject, UITableViewDelegate, UITableViewDataSource{ typealias Environment = DataManagerProvider & OEXInterfaceProvider & ReachabilityProvider let transcriptTableView = UITableView(frame: CGRect.zero, style: .plain) var transcripts = [TranscriptObject]() let environment : Environment weak var delegate : VideoTranscriptDelegate? //Maintain the cell index highlighted currently var highlightedIndex = 0 //Flag to toggle if tableview has been dragged in the last few seconds var isTableDragged : Bool = false //Timer to reset the isTableDragged flag so automatic scrolling can kick back in var draggingTimer = Timer() //Delay after which automatic scrolling should kick back in let dragDelay : TimeInterval = 5.0 init(environment : Environment) { self.environment = environment super.init() setupTable(tableView: transcriptTableView) transcriptTableView.dataSource = self transcriptTableView.delegate = self } private func setupTable(tableView: UITableView) { tableView.register(VideoTranscriptTableViewCell.self, forCellReuseIdentifier: VideoTranscriptTableViewCell.cellIdentifier) tableView.separatorColor = UIColor.clear tableView.separatorStyle = UITableViewCell.SeparatorStyle.none tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.isHidden = true } //MARK: - UITableview methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return transcripts.count } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: VideoTranscriptTableViewCell.cellIdentifier) as! VideoTranscriptTableViewCell cell.applyStandardSeparatorInsets() cell.setTranscriptText(text: transcripts[indexPath.row].text.decodingHTMLEntities, highlighted: indexPath.row == highlightedIndex) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.didSelectSubtitleAtInterval(time: transcripts[indexPath.row].start) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isTableDragged = true draggingTimer.invalidate() draggingTimer = Timer.scheduledTimer(timeInterval: dragDelay, target: self, selector: #selector(invalidateDragging), userInfo: nil, repeats: false) } func updateTranscript(transcript: [TranscriptObject]) { if transcript.count > 0 { transcripts = transcript transcriptTableView.reloadData() transcriptTableView.isHidden = false } } func highlightSubtitle(for time: TimeInterval?) { if let index = getTranscriptIndex(for: time), index != highlightedIndex{ highlightedIndex = index transcriptTableView.reloadData() if !isTableDragged { transcriptTableView.scrollToRow(at: IndexPath(row: index, section: 0), at: UITableView.ScrollPosition.middle, animated: true) } } } func getTranscriptIndex(for time: TimeInterval?) -> Int? { guard let time = time else { return nil } return transcripts.index(where: { time >= $0.start && time <= $0.end }) } @objc func invalidateDragging(){ isTableDragged = false } }
apache-2.0
83b7e1076d54ee15178182c7e01c3453
35.87619
155
0.690857
5.531429
false
false
false
false
NicolasKim/Roy
Example/Pods/GRDB.swift/GRDB/Record/FetchedRecordsController.swift
1
44274
import Foundation #if os(iOS) import UIKit #endif /// You use FetchedRecordsController to track changes in the results of an /// SQLite request. /// /// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for /// more information. public final class FetchedRecordsController<Record: RowConvertible> { // MARK: - Initialization /// Creates a fetched records controller initialized from a SQL query and /// its eventual arguments. /// /// let controller = FetchedRecordsController<Wine>( /// dbQueue, /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// /// - parameters: /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - queue: A serial dispatch queue (defaults to the main queue) /// /// The fetched records controller tracking callbacks will be /// notified of changes in this queue. The controller itself must be /// used from this queue. /// /// - isSameRecord: Optional function that compares two records. /// /// This function should return true if the two records have the /// same identity. For example, they have the same id. public convenience init( _ databaseWriter: DatabaseWriter, sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws { try self.init( databaseWriter, request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), queue: queue, isSameRecord: isSameRecord) } /// Creates a fetched records controller initialized from a fetch request /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). /// /// let request = Wine.order(Column("name")) /// let controller = FetchedRecordsController( /// dbQueue, /// request: request, /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// /// - parameters: /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) /// - request: A fetch request. /// - queue: A serial dispatch queue (defaults to the main queue) /// /// The fetched records controller tracking callbacks will be /// notified of changes in this queue. The controller itself must be /// used from this queue. /// /// - isSameRecord: Optional function that compares two records. /// /// This function should return true if the two records have the /// same identity. For example, they have the same id. public convenience init<Request>( _ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws where Request: TypedRequest, Request.RowDecoder == Record { let itemsAreIdenticalFactory: ItemComparatorFactory<Record> if let isSameRecord = isSameRecord { itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } } } else { itemsAreIdenticalFactory = { _ in { _,_ in false } } } try self.init( databaseWriter, request: request, queue: queue, itemsAreIdenticalFactory: itemsAreIdenticalFactory) } private init<Request>( _ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue, itemsAreIdenticalFactory: @escaping ItemComparatorFactory<Record>) throws where Request: TypedRequest, Request.RowDecoder == Record { self.itemsAreIdenticalFactory = itemsAreIdenticalFactory self.request = request (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) } self.databaseWriter = databaseWriter self.queue = queue } /// Executes the controller's fetch request. /// /// After executing this method, you can access the the fetched objects with /// the `fetchedRecords` property. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func performFetch() throws { // If some changes are currently processed, make sure they are // discarded. But preserve eventual changes processing for future // changes. let fetchAndNotifyChanges = observer?.fetchAndNotifyChanges observer?.invalidate() observer = nil // Fetch items on the writing dispatch queue, so that the transaction // observer is added on the same serialized queue as transaction // callbacks. try databaseWriter.write { db in let initialItems = try Item<Record>.fetchAll(db, request) fetchedItems = initialItems if let fetchAndNotifyChanges = fetchAndNotifyChanges { let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer observer.items = initialItems db.add(transactionObserver: observer) } } } // MARK: - Configuration /// The database writer used to fetch records. /// /// The controller registers as a transaction observer in order to respond /// to changes. public let databaseWriter: DatabaseWriter /// The dispatch queue on which the controller must be used. /// /// Unless specified otherwise at initialization time, it is the main queue. public let queue: DispatchQueue /// Updates the fetch request, and eventually notifies the tracking /// callbacks if performFetch() has been called. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record { self.request = request (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) } // No observer: don't look for changes guard let observer = observer else { return } // If some changes are currently processed, make sure they are // discarded. But preserve eventual changes processing. let fetchAndNotifyChanges = observer.fetchAndNotifyChanges observer.invalidate() self.observer = nil // Replace observer so that it tracks a new set of columns, // and notify eventual changes let initialItems = fetchedItems databaseWriter.write { db in let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer observer.items = initialItems db.add(transactionObserver: observer) observer.fetchAndNotifyChanges(observer) } } /// Updates the fetch request, and eventually notifies the tracking /// callbacks if performFetch() has been called. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self)) } /// Registers changes notification callbacks. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). /// /// - parameters: /// - willChange: Invoked before records are updated. /// - onChange: Invoked for each record that has been added, /// removed, moved, or updated. /// - didChange: Invoked after records have been updated. public func trackChanges( willChange: ((FetchedRecordsController<Record>) -> ())? = nil, onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil, didChange: ((FetchedRecordsController<Record>) -> ())? = nil) { // I hate you SE-0110. let wrappedWillChange: ((FetchedRecordsController<Record>, Void) -> ())? if let willChange = willChange { wrappedWillChange = { (controller, _) in willChange(controller) } } else { wrappedWillChange = nil } let wrappedDidChange: ((FetchedRecordsController<Record>, Void) -> ())? if let didChange = didChange { wrappedDidChange = { (controller, _) in didChange(controller) } } else { wrappedDidChange = nil } trackChanges( fetchAlongside: { _ in }, willChange: wrappedWillChange, onChange: onChange, didChange: wrappedDidChange) // Without bloody SE-0110: // trackChanges( // fetchAlongside: { _ in }, // willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, // onChange: onChange, // didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) } /// Registers changes notification callbacks. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). /// /// - parameters: /// - fetchAlongside: The value returned from this closure is given to /// willChange and didChange callbacks, as their /// `fetchedAlongside` argument. The closure is guaranteed to see the /// database in the state it has just after eventual changes to the /// fetched records have been performed. Use it in order to fetch /// values that must be consistent with the fetched records. /// - willChange: Invoked before records are updated. /// - onChange: Invoked for each record that has been added, /// removed, moved, or updated. /// - didChange: Invoked after records have been updated. public func trackChanges<T>( fetchAlongside: @escaping (Database) throws -> T, willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil, onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil, didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil) { // If some changes are currently processed, make sure they are // discarded because they would trigger previously set callbacks. observer?.invalidate() observer = nil guard (willChange != nil) || (onChange != nil) || (didChange != nil) else { // Stop tracking return } var willProcessTransaction: () -> () = { } var didProcessTransaction: () -> () = { } #if os(iOS) if let application = application { var backgroundTaskID: UIBackgroundTaskIdentifier! = nil willProcessTransaction = { backgroundTaskID = application.beginBackgroundTask { application.endBackgroundTask(backgroundTaskID) } } didProcessTransaction = { application.endBackgroundTask(backgroundTaskID) } } #endif let initialItems = fetchedItems databaseWriter.write { db in let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction( controller: self, fetchAlongside: fetchAlongside, itemsAreIdentical: itemsAreIdentical, willProcessTransaction: willProcessTransaction, willChange: willChange, onChange: onChange, didChange: didChange, didProcessTransaction: didProcessTransaction) let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer if let initialItems = initialItems { observer.items = initialItems db.add(transactionObserver: observer) observer.fetchAndNotifyChanges(observer) } } } /// Registers an error callback. /// /// Whenever the controller could not look for changes after a transaction /// has potentially modified the tracked request, this error handler is /// called. /// /// The request observation is not stopped, though: future transactions may /// successfully be handled, and the notified changes will then be based on /// the last successful fetch. /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController<Record>, Error) -> ()) { self.errorHandler = errorHandler } #if os(iOS) /// Call this method when changes performed while the application is /// in the background should be processed before the application enters the /// suspended state. /// /// Whenever the tracked request is changed, the fetched records controller /// sets up a background task using /// `UIApplication.beginBackgroundTask(expirationHandler:)` which is ended /// after the `didChange` callback has completed. public func allowBackgroundChangesTracking(in application: UIApplication) { self.application = application } #endif // MARK: - Accessing Records /// The fetched records. /// /// The value of this property is nil until performFetch() has been called. /// /// The records reflect the state of the database after the initial /// call to performFetch, and after each database transaction that affects /// the results of the fetch request. /// /// This property must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public var fetchedRecords: [Record] { guard let fetchedItems = fetchedItems else { fatalError("the performFetch() method must be called before accessing fetched records") } return fetchedItems.map { $0.record } } // MARK: - Not public #if os(iOS) /// Support for allowBackgroundChangeTracking(in:) var application: UIApplication? #endif /// The items fileprivate var fetchedItems: [Item<Record>]? /// The record comparator private var itemsAreIdentical: ItemComparator<Record> /// The record comparator factory (support for request change) private let itemsAreIdenticalFactory: ItemComparatorFactory<Record> /// The request fileprivate var request: Request /// The observed database region private var region : DatabaseRegion /// The eventual current database observer private var observer: FetchedRecordsObserver<Record>? /// The eventual error handler fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())? private static func fetchRegionAndComparator( _ db: Database, request: Request, itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws -> (DatabaseRegion, ItemComparator<Record>) { let region = try request.fetchedRegion(db) let itemsAreIdentical = try itemsAreIdenticalFactory(db) return (region, itemsAreIdentical) } } extension FetchedRecordsController where Record: TableMapping { // MARK: - Initialization /// Creates a fetched records controller initialized from a SQL query and /// its eventual arguments. /// /// let controller = FetchedRecordsController<Wine>( /// dbQueue, /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", /// arguments: [Color.red]) /// /// The records are compared by primary key (single-column primary key, /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// /// // Assuming the wines table has an `id` primary key: /// let controller = FetchedRecordsController<Wine>( /// dbQueue, /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// /// - parameters: /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - queue: A serial dispatch queue (defaults to the main queue) /// /// The fetched records controller tracking callbacks will be /// notified of changes in this queue. The controller itself must be /// used from this queue. public convenience init( _ databaseWriter: DatabaseWriter, sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, queue: DispatchQueue = .main) throws { try self.init( databaseWriter, request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), queue: queue) } /// Creates a fetched records controller initialized from a fetch request /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). /// /// let request = Wine.order(Column("name")) /// let controller = FetchedRecordsController( /// dbQueue, /// request: request) /// /// The records are compared by primary key (single-column primary key, /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// /// // Assuming the wines table has an `id` primary key: /// let controller = FetchedRecordsController<Wine>( /// dbQueue, /// request: request, /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// /// - parameters: /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) /// - request: A fetch request. /// - queue: A serial dispatch queue (defaults to the main queue) /// /// The fetched records controller tracking callbacks will be /// notified of changes in this queue. The controller itself must be /// used from this queue. public convenience init<Request>( _ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main) throws where Request: TypedRequest, Request.RowDecoder == Record { // Builds a function that returns true if and only if two items // have the same primary key and primary keys contain at least one // non-null value. let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in // Extract primary key columns from database table let columns = try db.primaryKey(Record.databaseTableName).columns // Compare primary keys assert(!columns.isEmpty) return { (lItem, rItem) in var notNullValue = false for column in columns { let lValue: DatabaseValue = lItem.row[column] let rValue: DatabaseValue = rItem.row[column] if lValue != rValue { // different primary keys return false } if !lValue.isNull || !rValue.isNull { notNullValue = true } } // identical primary keys iff at least one value is not null return notNullValue } } try self.init( databaseWriter, request: request, queue: queue, itemsAreIdenticalFactory: itemsAreIdenticalFactory) } } // MARK: - FetchedRecordsObserver /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. private final class FetchedRecordsObserver<Record: RowConvertible> : TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions let queue: DispatchQueue // protects items let region: DatabaseRegion var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> () init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) { self.isValid = true self.items = nil self.needsComputeChanges = false self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver") self.region = region self.fetchAndNotifyChanges = fetchAndNotifyChanges } func invalidate() { isValid = false } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return region.isModified(byEventsOfKind: eventKind) } /// Part of the TransactionObserverType protocol func databaseDidChange(with event: DatabaseEvent) { if region.isModified(by: event) { needsComputeChanges = true stopObservingDatabaseChangesUntilNextTransaction() } } /// Part of the TransactionObserverType protocol func databaseDidRollback(_ db: Database) { needsComputeChanges = false } /// Part of the TransactionObserverType protocol func databaseDidCommit(_ db: Database) { // The databaseDidCommit callback is called in the database writer // dispatch queue, which is serialized: it is guaranteed to process the // last database transaction. // Were observed tables modified? guard needsComputeChanges else { return } needsComputeChanges = false fetchAndNotifyChanges(self) } } // MARK: - Changes private func makeFetchFunction<Record, T>( controller: FetchedRecordsController<Record>, fetchAlongside: @escaping (Database) throws -> T, willProcessTransaction: @escaping () -> (), completion: @escaping (Result<(fetchedItems: [Item<Record>], fetchedAlongside: T, observer: FetchedRecordsObserver<Record>)>) -> () ) -> (FetchedRecordsObserver<Record>) -> () { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: // // controller.trackChanges { [unowned self] ... } // // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. return { [weak controller] observer in // Return if observer has been invalidated guard observer.isValid else { return } // Return if fetched records controller has been deallocated guard let request = controller?.request, let databaseWriter = controller?.databaseWriter else { return } willProcessTransaction() // Fetch items. // // This method is called from the database writer's serialized // queue, so that we can fetch items before other writes have the // opportunity to modify the database. // // However, we don't have to block the writer queue for all the // duration of the fetch. We just need to block the writer queue // until we can perform a fetch in isolation. This is the role of // the readFromCurrentState method (see below). // // However, our fetch will last for an unknown duration. And since // we release the writer queue early, the next database modification // will triggers this callback while our fetch is, maybe, still // running. This next callback will also perform its own fetch, that // will maybe end before our own fetch. // // We have to make sure that our fetch is processed *before* the // next fetch: let's immediately dispatch the processing task in our // serialized FIFO queue, but have it wait for our fetch to // complete, with a semaphore: let semaphore = DispatchSemaphore(value: 0) var result: Result<(fetchedItems: [Item<Record>], fetchedAlongside: T)>? = nil do { try databaseWriter.readFromCurrentState { db in result = Result { try ( fetchedItems: Item<Record>.fetchAll(db, request), fetchedAlongside: fetchAlongside(db)) } semaphore.signal() } } catch { result = .failure(error) semaphore.signal() } // Process the fetched items observer.queue.async { [weak observer] in // Wait for the fetch to complete: _ = semaphore.wait(timeout: .distantFuture) // Return if observer has been invalidated guard let strongObserver = observer else { return } guard strongObserver.isValid else { return } completion(result!.map { (fetchedItems, fetchedAlongside) in (fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: strongObserver) }) } } } private func makeFetchAndNotifyChangesFunction<Record, T>( controller: FetchedRecordsController<Record>, fetchAlongside: @escaping (Database) throws -> T, itemsAreIdentical: @escaping ItemComparator<Record>, willProcessTransaction: @escaping () -> (), willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())?, onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())?, didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())?, didProcessTransaction: @escaping () -> () ) -> (FetchedRecordsObserver<Record>) -> () { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: // // controller.trackChanges { [unowned self] ... } // // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. return makeFetchFunction(controller: controller, fetchAlongside: fetchAlongside, willProcessTransaction: willProcessTransaction) { [weak controller] result in // Return if fetched records controller has been deallocated guard let callbackQueue = controller?.queue else { return } switch result { case .failure(let error): callbackQueue.async { // Now we can retain controller guard let strongController = controller else { return } strongController.errorHandler?(strongController, error) didProcessTransaction() } case .success((fetchedItems: let fetchedItems, fetchedAlongside: let fetchedAlongside, observer: let observer)): // Return if there is no change let changes: [ItemChange<Record>] if onChange != nil { // Compute table view changes changes = computeChanges(from: observer.items, to: fetchedItems, itemsAreIdentical: itemsAreIdentical) if changes.isEmpty { return } } else { // Don't compute changes: just look for a row difference: if identicalItemArrays(fetchedItems, observer.items) { return } changes = [] } // Ready for next check observer.items = fetchedItems callbackQueue.async { [weak observer] in // Return if observer has been invalidated guard let strongObserver = observer else { return } guard strongObserver.isValid else { return } // Now we can retain controller guard let strongController = controller else { return } // Notify changes willChange?(strongController, fetchedAlongside) strongController.fetchedItems = fetchedItems if let onChange = onChange { for change in changes { onChange(strongController, change.record, change.fetchedRecordChange) } } didChange?(strongController, fetchedAlongside) didProcessTransaction() } } } } private func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] { let m = s.count let n = t.count // Fill first row and column of insertions and deletions. var d: [[[ItemChange<Record>]]] = Array(repeating: Array(repeating: [], count: n + 1), count: m + 1) var changes = [ItemChange<Record>]() for (row, item) in s.enumerated() { let deletion = ItemChange.deletion(item: item, indexPath: IndexPath(indexes: [0, row])) changes.append(deletion) d[row + 1][0] = changes } changes.removeAll() for (col, item) in t.enumerated() { let insertion = ItemChange.insertion(item: item, indexPath: IndexPath(indexes: [0, col])) changes.append(insertion) d[0][col + 1] = changes } if m == 0 || n == 0 { // Pure deletions or insertions return d[m][n] } // Fill body of matrix. for tx in 0..<n { for sx in 0..<m { if s[sx] == t[tx] { d[sx+1][tx+1] = d[sx][tx] // no operation } else { var del = d[sx][tx+1] // a deletion var ins = d[sx+1][tx] // an insertion var sub = d[sx][tx] // a substitution // Record operation. let minimumCount = min(del.count, ins.count, sub.count) if del.count == minimumCount { let deletion = ItemChange.deletion(item: s[sx], indexPath: IndexPath(indexes: [0, sx])) del.append(deletion) d[sx+1][tx+1] = del } else if ins.count == minimumCount { let insertion = ItemChange.insertion(item: t[tx], indexPath: IndexPath(indexes: [0, tx])) ins.append(insertion) d[sx+1][tx+1] = ins } else { let deletion = ItemChange.deletion(item: s[sx], indexPath: IndexPath(indexes: [0, sx])) let insertion = ItemChange.insertion(item: t[tx], indexPath: IndexPath(indexes: [0, tx])) sub.append(deletion) sub.append(insertion) d[sx+1][tx+1] = sub } } } } /// Returns an array where deletion/insertion pairs of the same element are replaced by `.move` change. func standardize(changes: [ItemChange<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] { /// Returns a potential .move or .update if *change* has a matching change in *changes*: /// If *change* is a deletion or an insertion, and there is a matching inverse /// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned. /// As a convenience, the index of the matched change is returned as well. func merge(change: ItemChange<Record>, in changes: [ItemChange<Record>], itemsAreIdentical: ItemComparator<Record>) -> (mergedChange: ItemChange<Record>, mergedIndex: Int)? { /// Returns the changes between two rows: a dictionary [key: oldValue] /// Precondition: both rows have the same columns func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] { var changedValues: [String: DatabaseValue] = [:] for (column, newValue) in newRow { let oldValue: DatabaseValue? = oldRow[column] if newValue != oldValue { changedValues[column] = oldValue } } return changedValues } switch change { case .insertion(let newItem, let newIndexPath): // Look for a matching deletion for (index, otherChange) in changes.enumerated() { guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) } else { return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) } } return nil case .deletion(let oldItem, let oldIndexPath): // Look for a matching insertion for (index, otherChange) in changes.enumerated() { guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) } else { return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) } } return nil default: return nil } } // Updates must be pushed at the end var mergedChanges: [ItemChange<Record>] = [] var updateChanges: [ItemChange<Record>] = [] for change in changes { if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) { mergedChanges.remove(at: mergedIndex) switch mergedChange { case .update: updateChanges.append(mergedChange) default: mergedChanges.append(mergedChange) } } else { mergedChanges.append(change) } } return mergedChanges + updateChanges } return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical) } private func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool { guard lhs.count == rhs.count else { return false } for (lhs, rhs) in zip(lhs, rhs) { if lhs.row != rhs.row { return false } } return true } // MARK: - UITableView Support private typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool private typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record> extension FetchedRecordsController { // MARK: - Accessing Records /// Returns the object at the given index path. /// /// - parameter indexPath: An index path in the fetched records. /// /// If indexPath does not describe a valid index path in the fetched /// records, a fatal error is raised. public func record(at indexPath: IndexPath) -> Record { guard let fetchedItems = fetchedItems else { // Programmer error fatalError("performFetch() has not been called.") } return fetchedItems[indexPath[1]].record } // MARK: - Querying Sections Information /// The sections for the fetched records. /// /// You typically use the sections array when implementing /// UITableViewDataSource methods, such as `numberOfSectionsInTableView`. /// /// The sections array is never empty, even when there are no fetched /// records. In this case, there is a single empty section. public var sections: [FetchedRecordsSectionInfo<Record>] { // We only support a single section so far. // We also return a single section when there are no fetched // records, just like NSFetchedResultsController. return [FetchedRecordsSectionInfo(controller: self)] } } extension FetchedRecordsController where Record: MutablePersistable { /// Returns the indexPath of a given record. /// /// - returns: The index path of *record* in the fetched records, or nil /// if record could not be found. public func indexPath(for record: Record) -> IndexPath? { let item = Item<Record>(row: Row(record)) guard let fetchedItems = fetchedItems, let index = fetchedItems.index(where: { itemsAreIdentical($0, item) }) else { return nil } return IndexPath(indexes: [0, index]) } } private enum ItemChange<T: RowConvertible> { case insertion(item: Item<T>, indexPath: IndexPath) case deletion(item: Item<T>, indexPath: IndexPath) case move(item: Item<T>, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) case update(item: Item<T>, indexPath: IndexPath, changes: [String: DatabaseValue]) } extension ItemChange { var record: T { switch self { case .insertion(item: let item, indexPath: _): return item.record case .deletion(item: let item, indexPath: _): return item.record case .move(item: let item, indexPath: _, newIndexPath: _, changes: _): return item.record case .update(item: let item, indexPath: _, changes: _): return item.record } } var fetchedRecordChange: FetchedRecordChange { switch self { case .insertion(item: _, indexPath: let indexPath): return .insertion(indexPath: indexPath) case .deletion(item: _, indexPath: let indexPath): return .deletion(indexPath: indexPath) case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes): return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes) case .update(item: _, indexPath: let indexPath, changes: let changes): return .update(indexPath: indexPath, changes: changes) } } } extension ItemChange: CustomStringConvertible { var description: String { switch self { case .insertion(let item, let indexPath): return "Insert \(item) at \(indexPath)" case .deletion(let item, let indexPath): return "Delete \(item) from \(indexPath)" case .move(let item, let indexPath, let newIndexPath, changes: let changes): return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)" case .update(let item, let indexPath, let changes): return "Update \(item) at \(indexPath) with changes: \(changes)" } } } /// A record change, given by a FetchedRecordsController to its change callback. /// /// The move and update events hold a *changes* dictionary, whose keys are /// column names, and values the old values that have been changed. public enum FetchedRecordChange { /// An insertion event, at given indexPath. case insertion(indexPath: IndexPath) /// A deletion event, at given indexPath. case deletion(indexPath: IndexPath) /// A move event, from indexPath to newIndexPath. The *changes* are a /// dictionary whose keys are column names, and values the old values that /// have been changed. case move(indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) /// An update event, at given indexPath. The *changes* are a dictionary /// whose keys are column names, and values the old values that have /// been changed. case update(indexPath: IndexPath, changes: [String: DatabaseValue]) } extension FetchedRecordChange: CustomStringConvertible { public var description: String { switch self { case .insertion(let indexPath): return "Insertion at \(indexPath)" case .deletion(let indexPath): return "Deletion from \(indexPath)" case .move(let indexPath, let newIndexPath, changes: let changes): return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)" case .update(let indexPath, let changes): return "Update at \(indexPath) with changes: \(changes)" } } } /// A section given by a FetchedRecordsController. public struct FetchedRecordsSectionInfo<Record: RowConvertible> { fileprivate let controller: FetchedRecordsController<Record> /// The number of records (rows) in the section. public var numberOfRecords: Int { guard let items = controller.fetchedItems else { // Programmer error fatalError("the performFetch() method must be called before accessing section contents") } return items.count } /// The array of records in the section. public var records: [Record] { guard let items = controller.fetchedItems else { // Programmer error fatalError("the performFetch() method must be called before accessing section contents") } return items.map { $0.record } } } // MARK: - Item private final class Item<T: RowConvertible> : RowConvertible, Equatable { let row: Row // Records are lazily loaded lazy var record: T = T(row: self.row) init(row: Row) { self.row = row.copy() } } private func ==<T> (lhs: Item<T>, rhs: Item<T>) -> Bool { return lhs.row == rhs.row }
mit
73870c0e362499bd86b7bc3d180314b0
40.886471
182
0.611894
5.316921
false
false
false
false
jhaigler94/cs4720-iOS
Pensieve/Pods/SwiftyDropbox/Source/Client.swift
1
12362
import Foundation import Alamofire public class Box<T> { public let unboxed : T init (_ v : T) { self.unboxed = v } } public class BabelClient { var manager : Manager var baseHosts : [String : String] func additionalHeaders(noauth: Bool) -> [String: String] { return [:] } init(manager: Manager, baseHosts : [String : String]) { self.manager = manager self.baseHosts = baseHosts } } public enum CallError<EType> : CustomStringConvertible { case InternalServerError(Int, String?, String?) case BadInputError(String?, String?) case RateLimitError case HTTPError(Int?, String?, String?) case RouteError(Box<EType>, String?) case OSError(ErrorType?) public var description : String { switch self { case let .InternalServerError(code, message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "Internal Server Error \(code)" if let m = message { ret += ": \(m)" } return ret case let .BadInputError(message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "Bad Input" if let m = message { ret += ": \(m)" } return ret case .RateLimitError: return "Rate limited" case let .HTTPError(code, message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "HTTP Error" if let c = code { ret += "\(c)" } if let m = message { ret += ": \(m)" } return ret case let .RouteError(_, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "API route error - handle programmatically" return ret case let .OSError(err): if let e = err { return "\(e)" } return "An unknown system error" } } } func utf8Decode(data: NSData) -> String { return NSString(data: data, encoding: NSUTF8StringEncoding)! as String } func asciiEscape(s: String) -> String { var out : String = "" for char in s.unicodeScalars { var esc = "\(char)" if !char.isASCII() { esc = NSString(format:"\\u%04x", char.value) as String } else { esc = "\(char)" } out += esc } return out } /// Represents a Babel request /// /// These objects are constructed by the SDK; users of the SDK do not need to create them manually. /// /// Pass in a closure to the `response` method to handle a response or error. public class BabelRequest<RType : JSONSerializer, EType : JSONSerializer> { let errorSerializer : EType let responseSerializer : RType let request : Alamofire.Request init(request: Alamofire.Request, responseSerializer: RType, errorSerializer: EType) { self.errorSerializer = errorSerializer self.responseSerializer = responseSerializer self.request = request } func handleResponseError(response: NSHTTPURLResponse?, data: NSData?, error: ErrorType?) -> CallError<EType.ValueType> { let requestId = response?.allHeaderFields["X-Dropbox-Request-Id"] as? String if let code = response?.statusCode { switch code { case 500...599: var message = "" if let d = data { message = utf8Decode(d) } return .InternalServerError(code, message, requestId) case 400: var message = "" if let d = data { message = utf8Decode(d) } return .BadInputError(message, requestId) case 429: return .RateLimitError case 403, 404, 409: let json = parseJSON(data!) switch json { case .Dictionary(let d): return .RouteError(Box(self.errorSerializer.deserialize(d["error"]!)), requestId) default: fatalError("Failed to parse error type") } case 200: return .OSError(error) default: return .HTTPError(code, "An error occurred.", requestId) } } else { var message = "" if let d = data { message = utf8Decode(d) } return .HTTPError(nil, message, requestId) } } } /// An "rpc-style" request public class BabelRpcRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { init(client: BabelClient, host: String, route: String, params: JSON, responseSerializer: RType, errorSerializer: EType) { let url = "\(client.baseHosts[host]!)\(route)" var headers = ["Content-Type": "application/json"] let noauth = (host == "notify") for (header, val) in client.additionalHeaders(noauth) { headers[header] = val } let request = client.manager.request(.POST, url, parameters: [:], headers: headers, encoding: ParameterEncoding.Custom {(convertible, _) in let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.HTTPBody = dumpJSON(params) return (mutableRequest, nil) }) super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer) request.resume() } /// Called when a request completes. /// /// :param: completionHandler A closure which takes a (response, error) and handles the result of the call appropriately. public func response(completionHandler: (RType.ValueType?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate().response { (request, response, dataObj, error) -> Void in let data = dataObj! if error != nil { completionHandler(nil, self.handleResponseError(response, data: data, error: error)) } else { completionHandler(self.responseSerializer.deserialize(parseJSON(data)), nil) } } return self } } public enum BabelUploadBody { case Data(NSData) case File(NSURL) case Stream(NSInputStream) } public class BabelUploadRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { init( client: BabelClient, host: String, route: String, params: JSON, responseSerializer: RType, errorSerializer: EType, body: BabelUploadBody) { let url = "\(client.baseHosts[host]!)\(route)" var headers = [ "Content-Type": "application/octet-stream", ] let noauth = (host == "notify") for (header, val) in client.additionalHeaders(noauth) { headers[header] = val } if let data = dumpJSON(params) { let value = asciiEscape(utf8Decode(data)) headers["Dropbox-Api-Arg"] = value } let request : Alamofire.Request switch body { case let .Data(data): request = client.manager.upload(.POST, url, headers: headers, data: data) case let .File(file): request = client.manager.upload(.POST, url, headers: headers, file: file) case let .Stream(stream): request = client.manager.upload(.POST, url, headers: headers, stream: stream) } super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer) request.resume() } /// Called as the upload progresses. /// /// :param: closure /// a callback taking three arguments (`bytesWritten`, `totalBytesWritten`, `totalBytesExpectedToWrite`) /// :returns: The request, for chaining purposes public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { self.request.progress(closure) return self } /// Called when a request completes. /// /// :param: completionHandler /// A callback taking two arguments (`response`, `error`) which handles the result of the call appropriately. /// :returns: The request, for chaining purposes. public func response(completionHandler: (RType.ValueType?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate().response { (request, response, dataObj, error) -> Void in let data = dataObj! if error != nil { completionHandler(nil, self.handleResponseError(response, data: data, error: error)) } else { completionHandler(self.responseSerializer.deserialize(parseJSON(data)), nil) } } return self } } public class BabelDownloadRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { var urlPath : NSURL? init(client: BabelClient, host: String, route: String, params: JSON, responseSerializer: RType, errorSerializer: EType, destination: (NSURL, NSHTTPURLResponse) -> NSURL) { let url = "\(client.baseHosts[host]!)\(route)" var headers = [String : String]() urlPath = nil if let data = dumpJSON(params) { let value = asciiEscape(utf8Decode(data)) headers["Dropbox-Api-Arg"] = value } let noauth = (host == "notify") for (header, val) in client.additionalHeaders(noauth) { headers[header] = val } weak var _self : BabelDownloadRequest<RType, EType>! let dest : (NSURL, NSHTTPURLResponse) -> NSURL = { url, resp in let ret = destination(url, resp) _self.urlPath = ret return ret } let request = client.manager.download(.POST, url, headers: headers, destination: dest) super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer) _self = self request.resume() } /// Called as the download progresses /// /// :param: closure /// a callback taking three arguments (`bytesRead`, `totalBytesRead`, `totalBytesExpectedToRead`) /// :returns: The request, for chaining purposes. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { self.request.progress(closure) return self } /// Called when a request completes. /// /// :param: completionHandler /// A callback taking two arguments (`response`, `error`) which handles the result of the call appropriately. /// :returns: The request, for chaining purposes. public func response(completionHandler: ( (RType.ValueType, NSURL)?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate() .response { (request, response, dataObj, error) -> Void in if error != nil { let data = self.urlPath.flatMap { NSData(contentsOfURL: $0) } completionHandler(nil, self.handleResponseError(response, data: data, error: error)) } else { let result = response!.allHeaderFields["Dropbox-Api-Result"] as! String let resultData = result.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let resultObject = self.responseSerializer.deserialize(parseJSON(resultData)) completionHandler( (resultObject, self.urlPath!), nil) } } return self } }
apache-2.0
d3be7cc70a8d73a83c330fa6a66817f8
34.728324
175
0.556706
4.952724
false
false
false
false
Rahulclaritaz/rahul
ixprez/ixprez/TextfieldExtension.swift
1
785
// // TextfieldExtension.swift // ixprez // // Created by Quad on 5/3/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import Foundation import UIKit extension UITextField { func textFieldBoarder ( txtColor : UIColor , txtWidth : CGFloat ) -> UITextField { self.borderStyle = UITextBorderStyle.none let border = CALayer() let borderWidth : CGFloat = txtWidth border.borderWidth = borderWidth border.borderColor = txtColor.cgColor border.frame = CGRect(x: 0, y: CGFloat(self.frame.size.height - borderWidth), width: CGFloat(self.frame.size.width), height: CGFloat(self.frame.size.height - 15)) self.layer.addSublayer(border) return self } }
mit
649af045ace50432dd678cdb05d871d3
23.5
170
0.637755
4.307692
false
false
false
false
codegeeker180/AVFonts
AVFonts/Classes/AVTextViewExtension.swift
1
1221
// * AVTextViewExtension.swift // * AVFonts // * Created by Arnav Gupta on 7/31/17. // *Copyright © 2017 Arnav. All rights reserved. import Foundation import UIKit extension UITextView { @objc public func customFontLayoutSubviews() { self.customFontLayoutSubviews() if AVFonts.changeFontThroughOut.count > 1 { if self.font?.fontName != AVFonts.changeFontThroughOut { if AVFonts.changeFontThroughOutTypes.contains(.textview) { self.font = UIFont(name: AVFonts.changeFontThroughOut, size: (self.font?.pointSize)! + AVFonts.changeFontThroughOutIncremnt) } } } else if AVFonts.attributeFonttv[self.font?.fontName ?? ""] != nil { if AVFonts.attributeFontSizetv[self.font?.fontName ?? ""] != nil { let fontSize = (self.font?.pointSize ?? 0) + AVFonts.attributeFontSizetv[self.font?.fontName ?? ""]! self.font = UIFont(name: AVFonts.attributeFonttv[self.font?.fontName ?? ""]!, size: fontSize) } else { self.font = UIFont(name: AVFonts.attributeFonttv[self.font?.fontName ?? ""]!, size: (self.font?.pointSize ?? 0)) } } } }
mit
908d8ea2fbe6b49ee6e4342bfa83dec1
44.185185
144
0.614754
4.295775
false
false
false
false
guille969/Licensy
Licensy/Sources/Library/Model/LibraryModel.swift
1
906
// // LibraryModel.swift // Licensy // // Created by Guillermo García Rebolo on 27/3/18. // Copyright © 2018 RetoLabs. All rights reserved. // public class LibraryModel: Decodable { /// The name of the library var name: String /// The name of the company / organization var organization: String /// The library url. Usually a github url var url: String /// The copyright (usually in format "Copyright (c) [YEAR] [NAME]") var copyright: String /// The license of the library. var license: String init(entity: LibraryEntity) { self.name = entity.name self.organization = entity.organization self.url = entity.organization self.copyright = entity.copyright self.license = "MIT" guard let licenseEntity: License = entity.license else { return } self.license = licenseEntity.identifier } }
mit
233b1c15d85016d9be11b73e9de30ea7
28.16129
73
0.647124
4.224299
false
false
false
false
koara/koara-swift
Source/Io/FileReader.swift
1
1376
import Foundation public class FileReader { var index: Int var file: URL public init(file: URL) { self.file = file self.index = 0 } public func read(_ buffer: inout [Character], offset: Int, length: Int) -> Int { var charactersRead = 0 do { let handle: FileHandle? = try FileHandle(forReadingFrom: file) if let handle = handle { handle.seek(toFileOffset: UInt64(index)) let fileContent = String(data: handle.readData(ofLength: length * 4), encoding: .utf8)! if fileContent != "" { for (i, c) in fileContent.characters.enumerated() { if((offset + i) < buffer.count) { buffer[offset + i] = c } else { buffer.insert(c, at: offset + i) } charactersRead += 1 index += String(c).utf8.count if(charactersRead >= length) { return charactersRead } } return charactersRead } handle.closeFile() } } catch { return -1 } return -1 } }
apache-2.0
57433b9622bd3eed4c296ade1260d81b
29.577778
103
0.421512
5.354086
false
false
false
false
zcill/SwiftDemoCollection
Project 05-Basic TableView/Project5-Basic TableView/TableViewController.swift
1
2721
// // TableViewController.swift // Project5-Basic TableView // // Created by 朱立焜 on 16/4/13. // Copyright © 2016年 朱立焜. All rights reserved. // import UIKit class TableViewController: UITableViewController { let dataSource = ["Iron Man", "Spider Man", "Bat Man"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel?.text = dataSource[indexPath.row] return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } }
mit
524d43c8aa002fc7b4f1c48922aa1252
35.08
157
0.700665
5.556468
false
false
false
false
royhsu/RHAnimatedTitleView
RHAnimatedTitleView/RHAnimatedTitleView.swift
1
3703
// // RHAnimatedTitleView.swift // UILabel // // Created by Roy Hsu on 2015/3/31. // Copyright (c) 2015年 tinyWorld. All rights reserved. // import UIKit class RHAnimatedTitleView: UIScrollView, UIScrollViewDelegate { private(set) var oldTitleLabel: UILabel? private(set) var newTitleLabel: UILabel? private(set) var oldTitle: String? private(set) var newTitle: String? // Set this property to change the color of title with the specified color. var titleColor: UIColor = UIColor.blackColor() { didSet { oldTitleLabel?.textColor = titleColor newTitleLabel?.textColor = titleColor } } // The effect fade in and out title when the y position of content offset changed. var transition: Bool = true { didSet { if transition { oldTitleLabel?.alpha = 1.0 newTitleLabel?.alpha = 0.0 } else { oldTitleLabel?.alpha = 1.0 newTitleLabel?.alpha = 1.0 } } } private struct Static { static let HorizontalMargin: CGFloat = 70.0 static let FontSize: CGFloat = 17.0 } // MARK: - Init init(oldTitle: String, newTitle: String) { super.init() userInteractionEnabled = false delegate = self let titleFont = UIFont.boldSystemFontOfSize(Static.FontSize) oldTitleLabel = UILabel() if let oldTitleLabel = oldTitleLabel { oldTitleLabel.text = oldTitle oldTitleLabel.sizeToFit() oldTitleLabel.textAlignment = .Center oldTitleLabel.numberOfLines = 1 oldTitleLabel.textColor = titleColor oldTitleLabel.font = titleFont } newTitleLabel = UILabel() if let newTitleLabel = newTitleLabel { newTitleLabel.text = newTitle newTitleLabel.sizeToFit() newTitleLabel.textAlignment = .Center newTitleLabel.numberOfLines = 1 newTitleLabel.textColor = titleColor newTitleLabel.font = titleFont } let width = UIScreen.mainScreen().bounds.width - (2 * Static.HorizontalMargin) let height = oldTitleLabel?.frame.height ?? 0.0 frame = CGRectMake(0.0, 0.0, width, height) contentSize = CGSizeMake(width, 2 * height) oldTitleLabel?.frame = CGRectMake(0.0, 0.0, width, height) newTitleLabel?.frame = CGRectMake(0.0, height, width, height) if let oldTitleLabel = oldTitleLabel { addSubview(oldTitleLabel) } if let newTitleLabel = newTitleLabel { addSubview(newTitleLabel) } } required override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Effect private func fadeInAndOut() { let max = frame.height let distance = contentOffset.y if distance < 0 { oldTitleLabel?.alpha = 1.0 newTitleLabel?.alpha = 0.0 } else if distance > max { oldTitleLabel?.alpha = 0.0 newTitleLabel?.alpha = 1.0 } else { let ratio = distance / max oldTitleLabel?.alpha = (1.0 - ratio) newTitleLabel?.alpha = ratio } } // MARK: - Scroll View Delegate func scrollViewDidScroll(scrollView: UIScrollView) { if transition { fadeInAndOut() } } }
mit
f8f5a44bf9ddd8c0a86addf693b7ac3e
27.689922
86
0.565253
5.212676
false
false
false
false
ocrickard/Theodolite
Theodolite/Core/Lifecycle/MountContext.swift
1
5770
// // MountContext.swift // Theodolite // // Created by Oliver Rickard on 10/25/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import Foundation public class MountContext { /** The view that children should receive as their parent. */ let view: UIView /** The starting position for all children within the view. */ let position: CGPoint /** Whether the recursive mount algorithm should mount the children. If you return false, you will have to call MountRootLayout yourself. */ let shouldMountChildren: Bool init(view: UIView, position: CGPoint, shouldMountChildren: Bool) { self.view = view self.position = position self.shouldMountChildren = shouldMountChildren } } /** IncrementalMountContext is used for bookkeeping. It records which components are mounted so that we can remember to unmount components when they're no longer in the hierarchy. */ public class IncrementalMountContext { private var mounted: Set<Layout> = Set() private var marked: Set<Layout> = Set() internal func isMounted(layout: Layout) -> Bool { return mounted.contains(layout) } internal func markMounted(layout: Layout) { assert(Thread.isMainThread) mounted.insert(layout) marked.insert(layout) } internal func markUnmounted(layout: Layout) { assert(Thread.isMainThread) mounted.remove(layout) marked.remove(layout) } internal func unmarkedMounted() -> [Layout] { assert(Thread.isMainThread) if mounted.count == 0 || mounted == marked { return [] } // todo, this is really slow return Array(mounted.subtracting(marked)) } internal func enumerate(_ closure: (Layout) -> ()) { assert(Thread.isMainThread) for layout in mounted { closure(layout) } } } public func UnmountLayout(layout: Layout, incrementalContext: IncrementalMountContext) { // Call willUnmount before recurring layout.component.componentWillUnmount() for childLayout in layout.children { if (incrementalContext.isMounted(layout: layout)) { UnmountLayout(layout: childLayout.layout, incrementalContext: incrementalContext) } } // Only unmount **after** all children are unmounted. layout.component.unmount(layout: layout) let componentContext = GetContext(layout.component) incrementalContext.markUnmounted(layout: layout) componentContext?.mountInfo.mountContext = nil } public func MountRootLayout(view: UIView, layout: Layout, position: CGPoint, incrementalContext: IncrementalMountContext, mountVisibleOnly: Bool = false) { MountLayout(view: view, layout: layout, position: position, incrementalContext: incrementalContext, mountVisibleOnly: mountVisibleOnly) let toBeUnmounted = incrementalContext.unmarkedMounted() for unmountingLayout in toBeUnmounted { UnmountLayout(layout: unmountingLayout, incrementalContext: incrementalContext) } // Hide any views that remain after we complete the top-level mount operation PendingViewPoolResetList.reset() } internal func MountLayout(view: UIView, layout: Layout, position: CGPoint, incrementalContext: IncrementalMountContext, mountVisibleOnly: Bool) { let component = layout.component // If the component itself is not mounted, we do that first. var needsDidMount = false let componentContext = GetContext(layout.component) if !incrementalContext.isMounted(layout: layout) { component.componentWillMount() let context = component.mount(parentView: view, layout: layout, position: position) componentContext?.mountInfo.mountContext = context needsDidMount = true } // If we mounted, we need to notify the component that it finished mounting *after* its children mount. defer { if needsDidMount { component.componentDidMount() } } incrementalContext.markMounted(layout: layout) guard let mountContext: MountContext = componentContext?.mountInfo.mountContext else { return } // The component may decide to reject mounting of its children if it wants to do so itself. if !mountContext.shouldMountChildren { return } let bounds = mountContext.view.bounds for childLayout in layout.children { let childFrame = CGRect(x: mountContext.position.x + childLayout.position.x, y: mountContext.position.y + childLayout.position.y, width: childLayout.layout.size.width, height: childLayout.layout.size.height) if !mountVisibleOnly || childFrame.intersects(bounds) { // Recur into this layout's children if that child is visible. It's important that we do this even if the // component is already mounted, since some of their children may have been culled in a prior mounting pass. MountLayout(view: mountContext.view, layout: childLayout.layout, position: CGPoint(x: mountContext.position.x + childLayout.position.x, y: mountContext.position.y + childLayout.position.y), incrementalContext: incrementalContext, mountVisibleOnly: mountVisibleOnly) } else if mountVisibleOnly && incrementalContext.isMounted(layout: childLayout.layout) { UnmountLayout(layout: childLayout.layout, incrementalContext: incrementalContext) } } }
mit
20fd799777f779fac8148081327c0829
32.935294
116
0.665627
4.913969
false
false
false
false