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
AndreMuis/FiziksFunhouse
FiziksFunhouse/Library/FFHConstants.swift
1
1400
// // FFHConstants.swift // FiziksFunhouse // // Created by Andre Muis on 5/4/16. // Copyright © 2016 Andre Muis. All rights reserved. // import SceneKit import UIKit struct Constants { static let cameraPosition: SCNVector3 = SCNVector3(x: 8.0, y: 5.0, z: 18.0) static let omnidirectionalLightColor: UIColor = UIColor.init(white: 0.85, alpha: 1.0) static let omnidirectionalLightPosition: SCNVector3 = SCNVector3(x: 10.0, y: 7.0, z: 14.0) static let ambientLightColor: UIColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0) static let roomWidth: Float = 16.0 static let roomHeight: Float = 10.0 static let roomDepth: Float = 10.0 static let roomWallDepth: Float = 1.0 static let floorTextureName: String = "Wood" static let floorTextureScale: Float = 1.0 static let ceilingTextureName: String = "Plaster" static let ceilingTextureScale: Float = 3.0 static let wallTextureName: String = "Concrete" static let wallTextureScale: Float = 2.0 static let ballBaseRadius: CGFloat = 1.0 static let floorCategoryBitMask: Int = 1 static let ballNormalCategoryBitMask: Int = 2 static let ballDestroyerCategoryBitMask: Int = 4 static let allCategoriesBitMask: Int = 7 static let ballImplulseMagnitude: Float = 7.0 static let axisLength: Float = 10.0 static let axisRadius: Float = 0.1 }
mit
23bce6b383e1407357621606a884acfa
29.413043
96
0.696926
3.523929
false
false
false
false
robertfmurdock/Pledges
Pledges/Pledges.swift
1
14660
// // Pledge.swift // Squarmy // // Created by Robert Murdock on 8/14/14. // Copyright (c) 2014 Armoria Software. All rights reserved. // import Foundation public protocol Promise { @discardableResult func when(then : @escaping ( _ value: Any) -> Void) -> Promise @discardableResult func when(fail : @escaping ( _ error : NSError) -> Void) -> Promise } public func runOnBackground<T>(_ action : @escaping Pledge<T>.Action) -> Pledge<T> { func backgroundAction(_ resolve: @escaping Pledge<T>.Resolve, reject : @escaping Pledge<T>.Reject){ let mainQueueResolve : Pledge<T>.Resolve = { value in DispatchQueue.main.async { resolve(value) } } let mainQueueReject : Pledge<T>.Reject = { error in DispatchQueue.main.async { reject(error) } } let globalQueue = DispatchQueue.global() globalQueue.async{ action(mainQueueResolve, mainQueueReject) } } return Pledge(action: backgroundAction) } public var pledgeFallbackReject: Pledge.Reject = { print($0) } open class Pledge <T> : Promise { open class func resolve(_ value: T) -> Pledge<T> { return Pledge { resolve, reject in resolve( value) } } open class func reject(_ error: NSError) -> Pledge<T> { return Pledge { resolve, reject in reject(error)} } open class func isNil(_ value: T?) -> Pledge<T> { return isNil(value, error: NSError(domain: "Value was nil", code: 1, userInfo: nil)) } open class func isNil(_ value: T?, error: NSError) -> Pledge<T> { return Pledge<T> { resolve, reject in if let theValue = value { resolve(theValue) } else { reject(error) } } } public typealias Return = T public typealias Resolve = (_ value: T) -> Void public typealias Reject = (_ error : NSError) -> Void public typealias Action = ( _ resolve : @escaping Resolve, _ reject : @escaping Reject) -> Void open fileprivate(set) var resolve : Resolve = { value in return } open fileprivate(set) var reject : Reject = { error in return } fileprivate let action : Action fileprivate var thenQueue = [Resolve]() fileprivate var failQueue = [Reject]() fileprivate var potentialResult : T? fileprivate var potentialError : NSError? fileprivate var failWasHandled = false public convenience init() { self.init(action: {reject, resolve in return }) } public convenience init(action: @escaping Action){ self.init(timeout: 0.01, action: action) } public convenience init(timeout: Double, timeoutQueue: DispatchQueue = DispatchQueue.main){ self.init(timeout: timeout, action: {reject, resolve in return }) } public init(timeout: Double, timeoutQueue: DispatchQueue = DispatchQueue.main, action : @escaping Action) { self.action = action self.resolve = { (value : T) in self.potentialResult = value for then in self.thenQueue { then(value) } self.thenQueue.removeAll(keepingCapacity: false) } self.reject = { (error : NSError ) in if self.potentialResult == nil { let hasNotAlreadyFailed = self.potentialError == nil if hasNotAlreadyFailed && self.failQueue.count == 0 { timeoutQueue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(timeout * 1000000000)) / Double(NSEC_PER_SEC)) { if !self.failWasHandled { pledgeFallbackReject(Error("Uncaught Pledge failure: \(error.localizedDescription)", code: 12, userInfo: error.userInfo)) } } } self.potentialError = error for fail in self.failQueue { fail(error) } self.failQueue.removeAll(keepingCapacity: false) } } action(self.resolve, self.reject) timeoutQueue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(timeout * 1000000000)) / Double(NSEC_PER_SEC)) { if self.potentialResult == nil && self.potentialError == nil { self.reject(Error("Pledge did not resolve or reject before timeout of \(timeout) second.", code: 2)) } } } @discardableResult open func then(_ then : @escaping Resolve) -> Pledge <T> { if let promiseResult = potentialResult { then(promiseResult) } else { thenQueue.append(then) } return self } @discardableResult open func then<K>(_ errorWrapper: String = "", _ convert: @escaping (_ value: T) -> K) -> Pledge<K> { return Pledge<K> { resolveAgain, rejectAgain in self.then { value in resolveAgain(convert(value)) } self.fail { error in rejectAgain(wrapError(errorWrapper, error: error)) } } } open func thenPledge<K>(_ errorWrapper: String = "", _ convert: @escaping (_ value: T) -> Pledge<K>) -> Pledge<K> { return Pledge<K> { resolveAgain, rejectAgain in self.then { value in let pledge = convert(value) pledge.then(resolveAgain).fail { error in rejectAgain(wrapError(errorWrapper, error: error)) } } self.fail { error in rejectAgain(wrapError(errorWrapper, error: error)) } } } open func thenPledge<K>(_ errorWrapper: String = "", convert: @escaping (_ value: T, _ resolve : Pledge<K>.Resolve, _ reject : Pledge<K>.Reject) -> Void) -> Pledge<K> { return Pledge<K> { resolveAgain, rejectAgain in self.then { value in convert(value, resolveAgain, rejectAgain) } self.fail { error in rejectAgain(wrapError(errorWrapper, error: error)) } } } @discardableResult open func fail(_ fail : @escaping Reject) -> Pledge <T> { if let error = potentialError { failWasHandled = true fail(error) } else { failQueue.append(fail) } return self } open func when(then : @escaping ( _ value: Any) -> Void) -> Promise { let wrappedThen : Resolve = { value in then(value) } return self.then(wrappedThen) } open func when(fail : @escaping ( _ error : NSError) -> Void) -> Promise { return self.fail(fail) } } public func all<T1, T2>(_ failFast: Bool = false, promises : (Pledge<T1>, Pledge<T2>)) -> Pledge<(T1, T2)> { return Pledge() { resolve, reject in all(failFast, promises: [promises.0, promises.1]) .then { value in resolve((value[0] as! T1, value[1] as! T2)) } .fail(reject) return } } public func all<T1, T2, T3>(_ failFast: Bool = false, promises : (Pledge<T1>, Pledge<T2>, Pledge<T3>)) -> Pledge<(T1, T2, T3)> { return Pledge() { resolve, reject in all(failFast, promises: [promises.0, promises.1, promises.2]) .then { value in resolve((value[0] as! T1, value[1] as! T2, value[2] as! T3)) } .fail(reject) return } } public func all<T1, T2, T3, T4>(_ failFast: Bool = false, promises : (Pledge<T1>, Pledge<T2>, Pledge<T3>, Pledge<T4>)) -> Pledge<(T1, T2, T3, T4)> { return Pledge() { resolve, reject in all(promises: [promises.0, promises.1, promises.2, promises.3]) .then { value in resolve((value[0] as! T1, value[1] as! T2, value[2] as! T3, value[3] as! T4)) } .fail(reject) return } } public func all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(_ failFast: Bool = false, promises : (Pledge<T1>, Pledge<T2>, Pledge<T3>, Pledge<T4>, Pledge<T5>, Pledge<T6>, Pledge<T7>, Pledge<T8>, Pledge<T9>, Pledge<T10>)) -> Pledge<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> { return Pledge() { resolve, reject in all(failFast, promises: [promises.0, promises.1, promises.2, promises.3, promises.4, promises.5, promises.6, promises.7, promises.8, promises.9]) .then { value in let value1 = value[0] as! T1 let value2 = value[1] as! T2 let value3 = value[2] as! T3 let value4 = value[3] as! T4 let value5 = value[4] as! T5 let value6 = value[5] as! T6 let value7 = value[6] as! T7 let value8 = value[7] as! T8 let value9 = value[8] as! T9 let value10 = value[9] as! T10 resolve( (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10)) } .fail(reject) return } } public func all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(_ failFast: Bool = false, promises : (Pledge<T1>, Pledge<T2>, Pledge<T3>, Pledge<T4>, Pledge<T5>, Pledge<T6>, Pledge<T7>, Pledge<T8>, Pledge<T9>, Pledge<T10>, Pledge<T11>)) -> Pledge<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> { return Pledge() { resolve, reject in all(promises: [promises.0, promises.1, promises.2, promises.3, promises.4, promises.5, promises.6, promises.7, promises.8, promises.9, promises.10]) .then { value in let value1 = value[0] as! T1 let value2 = value[1] as! T2 let value3 = value[2] as! T3 let value4 = value[3] as! T4 let value5 = value[4] as! T5 let value6 = value[5] as! T6 let value7 = value[6] as! T7 let value8 = value[7] as! T8 let value9 = value[8] as! T9 let value10 = value[9] as! T10 let value11 = value[10] as! T11 resolve( (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11)) } .fail(reject) return } } public typealias AnyErrorDescriber = (_ index: Int, _ errorDescription: String) -> String public func all<T>(_ failFast: Bool = false, pledges : [Pledge<T>], errorWrapper: String = "Array error", describeErr: @escaping AnyErrorDescriber = { index, error in " [\(index)] <\(error)>"}) -> Pledge<[T]> { if pledges.count == 0 { return Pledge.resolve([T]()) } else { return connectPledges(failFast, pledges: pledges, errorWrapper: errorWrapper, describeErr: describeErr) } } private func connectPledges<T>(_ failFast: Bool, pledges : [Pledge<T>], errorWrapper: String, describeErr: @escaping AnyErrorDescriber) -> Pledge<[T]> { return Pledge<[T]> { resolve, reject in var results = [Int : T]() var errors = [Int: NSError]() for (index, promise) in pledges.enumerated() { promise .then { value in results[index] = value if pledges.count == results.count { resolve(convertIndexDictionaryToArray(results)) } else { reportCumulativeError(results, errors: errors, pledgeCount: pledges.count, reject: reject) } } .fail { error in if failFast { reject(wrap(errorWrapper, error: error, index: index, describeErr: describeErr)) } else { errors[index] = wrap(errorWrapper, error: error, index: index, describeErr: describeErr) reportCumulativeError(results, errors: errors, pledgeCount: pledges.count, reject: reject) } } } } } public func wrapError(_ message: String, error: NSError) -> NSError { if message == "" { return error } else { var userInfo = error.userInfo userInfo[NSUnderlyingErrorKey] = error return Error(message + error.localizedDescription, code: error.code, userInfo: userInfo) } } private func wrap(_ message: String, error: NSError, index: Int, describeErr: AnyErrorDescriber) -> NSError { let description = "\(message)\(describeErr(index, error.localizedDescription))" if message == "" || description == error.localizedDescription { return error } else { var userInfo = error.userInfo userInfo[NSUnderlyingErrorKey] = error return Error(description, code: error.code, userInfo: userInfo) } } private func convertIndexDictionaryToArray<T>(_ dictionary: [Int: T]) -> [T] { var finalResults = [T]() var keys = Array(dictionary.keys) keys.sort(by: { $0 < $1 }) for key in keys { if let value = dictionary[key] { finalResults.append(value) } } return finalResults } private func reportCumulativeError<T>(_ results: [Int: T], errors: [Int: NSError], pledgeCount: Int, reject : Pledge<[T]>.Reject) { if (errors.count + results.count) == pledgeCount { if errors.count == 1 { reject(errors.values.first!) } else { var cumulativeError = "[\n" let errorArray = convertIndexDictionaryToArray(errors) for error in errorArray { cumulativeError += error.localizedDescription cumulativeError += "\n" } cumulativeError += "]" reject(Error(cumulativeError,code: 99, userInfo: [NSUnderlyingErrorKey: errorArray])) } } } private func Error(_ description: String, code: Int, userInfo: [String: Any]? = nil) -> NSError { var revisedUserInfo: [String: Any] = userInfo ?? [:] revisedUserInfo[NSLocalizedDescriptionKey] = description return NSError(domain: "Pledges", code: code, userInfo: revisedUserInfo) } public func all(_ failFast: Bool = false, promises : [Promise]) -> Pledge<[Any]> { let pledges = promises.map { promise in Pledge<Any> { resolve, reject in promise.when(then: resolve) promise.when(fail: reject) } } return all(failFast, pledges: pledges, errorWrapper: "", describeErr: { index, error in error }) }
mit
23ec612776315f226cc43da97ef2c43a
38.514825
193
0.559209
4.060942
false
false
false
false
morbrian/udacity-nano-virtualtourist
VirtualTourist/AlbumViewController.swift
1
6940
// // AlbumViewController.swift // VirtualTourist // // Created by Brian Moriarty on 7/6/15. // Copyright (c) 2015 Brian Moriarty. All rights reserved. // import UIKit import CoreData class AlbumViewController: UIViewController { let CollectionCellsPerRowLandscape = 5 let CollectionCellsPerRowPortrait = 3 // CODE: set as 2 in IB, not sure how to reference that value in code, so keep this in sync let CollectionCellSpacing = 2 @IBOutlet weak var newCollectionButton: UIBarButtonItem! var pin: Pin? @IBOutlet weak var collectionView: UICollectionView! private var defaultCount: Int? private var collectionCellCountPerRow: Int { let orientation = UIDevice.currentDevice().orientation switch orientation { case .LandscapeLeft, .LandscapeRight: defaultCount = CollectionCellsPerRowLandscape return CollectionCellsPerRowLandscape case .Portrait: defaultCount = CollectionCellsPerRowPortrait return CollectionCellsPerRowPortrait default: return defaultCount ?? CollectionCellsPerRowPortrait } } // MARK: ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() fetchedResultsController.performFetch(nil) fetchedResultsController.delegate = self } override func viewWillLayoutSubviews() { calculateCollectionCellSize() } // calculates cell size based on cells-per-row for the current device orientation private func calculateCollectionCellSize() { if let collectionView = collectionView { let width = collectionView.frame.width / CGFloat(collectionCellCountPerRow) - CGFloat(CollectionCellSpacing) let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout layout?.itemSize = CGSize(width: width, height: width) } } @IBAction func newCollectionAction(sender: UIBarButtonItem) { sharedContext.performBlockAndWait { for obj in self.fetchedResultsController.fetchedObjects! { let photo = obj as! Photo self.sharedContext.deleteObject(photo) FlickrService.Caches.imageCache.storeImage(nil, withIdentifier: photo.photoPath!) CoreDataStackManager.sharedInstance().saveContext() } } pin?.fetchPhotoList() {fetchedResultsController.performFetch(nil)} } // MARK: - Core Data Convenience var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext! } // Mark: - Fetched Results Controller lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "Photo") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "photoPath", ascending: true)] fetchRequest.predicate = NSPredicate(format: "pin == %@", self.pin!); let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() } // MARK: - UICollectionViewDelegate extension AlbumViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let photo = fetchedResultsController.objectAtIndexPath(indexPath) as! Photo FlickrService.Caches.imageCache.storeImage(nil, withIdentifier: photo.copyPhotoPath!) sharedContext.performBlockAndWait { self.sharedContext.deleteObject(photo) CoreDataStackManager.sharedInstance().saveContext() } } } // MARK: - UICollectionViewDataSource extension AlbumViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Here is how to replace the actors array using objectAtIndexPath let photo = fetchedResultsController.objectAtIndexPath(indexPath) as! Photo let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.AlbumCellIdentifier, forIndexPath: indexPath) as! AlbumCellView // reset the image so we won't see the wrong image during loading when cell is reused cell.imageView?.image = nil cell.photo = photo return cell } } // MARK: - Fetched Results Controller Delegate extension AlbumViewController:NSFetchedResultsControllerDelegate { func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.collectionView.insertSections(NSIndexSet(index: sectionIndex)) case .Delete: self.collectionView.deleteSections(NSIndexSet(index: sectionIndex)) default: return } } // // This is the most interesting method. Take particular note of way the that newIndexPath // parameter gets unwrapped and put into an array literal: [newIndexPath!] // func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: collectionView.insertItemsAtIndexPaths([newIndexPath!]) case .Delete: collectionView.deleteItemsAtIndexPaths([indexPath!]) case .Update: let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! AlbumCellView let photo = controller.objectAtIndexPath(indexPath!) as! Photo //self.configureCell(cell, photo: photo) case .Move: collectionView.deleteItemsAtIndexPaths([indexPath!]) collectionView.insertItemsAtIndexPaths([newIndexPath!]) default: return } } }
mit
349c4c195110f99cea25507bcc8c4783
34.958549
150
0.657493
6.425926
false
false
false
false
dornad/RESTModel
Chillax/Sources/Types/Operations/CRUDOperation.swift
1
3901
// // RESTOperation.swift // Chillax // // Created by Daniel Rodriguez on 4/13/17. // Copyright © 2017 Paperless Post. All rights reserved. // import Foundation /// The default operations provided by the framework for your models. /// /// ## Rationale /// /// These 5 operations are the minimum viable solution for a Create, Retrieve, /// Update and Delete (aka CRUD) implementation. /// /// - seealso: https://en.wikipedia.org/wiki/Create,_read,_update_and_delete /// /// - create: Persist a model /// - retrieveBy: Retrieve a model by its identifier (`Hashable`) /// - retrieveAll: Retrieve all models /// - update: Update a model /// - delete: Delete a model /// public enum CRUDOperation <T: Resource>: ChillaxOperation { case create(model: T) case retrieveBy(id: AnyHashable) case retrieveAll case update(model: T) case delete(model: T) } // MARK: ChillaxOperation implementation extension CRUDOperation { public var httpMethod: HTTPMethod { switch self { case .create(model: _): return .post case .retrieveBy(id: _): return .get case .retrieveAll: return .get case .update(model: _): return .put case .delete(model: _): return .delete } } public var httpHeaderFields: [String:String] { switch self { case .create(model: _): return ["Content-Type" : "application/json"] case .retrieveBy(id: _): return [:] case .retrieveAll: return [:] case .update(model: _): return ["Content-Type" : "application/json"] case .delete(model: _): return [:] } } public var urlComponents: URLComponents { let resource = T.resourceInformation var components = resource.rootURLComponents switch self { case .retrieveBy(let id): components.path = components.path + "/\(id)" return components case .update(let model): components.path = components.path + "/\(model.identifier)" return components case .delete(let model): components.path = components.path + "/\(model.identifier)" return components case .retrieveAll: return components case .create(model: _): return components } } public var httpBody: Data? { switch self { case .create(let model): let encoder = JSONEncoder() return try? encoder.encode(model) case .retrieveBy(id: _): return nil case .retrieveAll: return nil case .update(let model): let encoder = JSONEncoder() return try? encoder.encode(model) case .delete(model: _): return nil } } public var expectsJSONResponse: Bool { switch self { case .retrieveBy(_): return true case .update(_): return true case .delete(_): return false case .retrieveAll: return true case .create(model: _): return true } } } // MARK: CRUDOperation implementation of Equatable extension CRUDOperation: Equatable, Hashable { public var hashValue: Int { switch self { case .create(model: _): return 0 case .retrieveBy(id: _): return 1 case .retrieveAll: return 2 case .update(model: _): return 3 case .delete(model: _): return 4 } } public static func ==(lhs: CRUDOperation<T>, rhs: CRUDOperation<T>) -> Bool { return lhs.hashValue == rhs.hashValue } }
apache-2.0
2773f6a83b98a3299af624588d950337
24.324675
81
0.543333
4.779412
false
false
false
false
obrichak/discounts
discounts/Classes/Managers/CategoryManager/CategoryManager.swift
1
2315
// // CategoryManager.swift // discounts // // Created by Alexandr Chernyy on 9/16/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import Foundation class CategoryManager { class var sharedManager: CategoryManager { struct Static { static var instance: CategoryManager? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = CategoryManager() } return Static.instance! } var categoryArrayData = Array<CategoryObject>() func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? { let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") if (path == nil) { println("Could not find level file: \(filename)") return nil } var error: NSError? let data: NSData? = NSData(contentsOfFile: path!, options: NSDataReadingOptions(), error: &error) if data == nil { println("Could not load level file: \(filename), error: \(error!)") return nil } let dictionary: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(), error: &error) if (dictionary == nil) { println("Level file '\(filename)' is not valid JSON: \(error!)") return nil } return dictionary as? Dictionary<String, AnyObject> } func loadDataFromJSON(filename: String) { if let dictionary = self.loadJSONFromBundle(filename) { let categoryArray: NSArray? = dictionary["category"] as NSArray? if (categoryArray != nil) { for item in categoryArray! { var category:CategoryObject = CategoryObject() // we convert each key to a String category.categoryId = item["categoryId"] as Int category.categoryName = item["categoryName"] as String category.categoryImageName = item["categoryImageName"] as String categoryArrayData.append(category) } } } } }
gpl-3.0
e77462e08dc1e92b7d12e77964156ba0
31.166667
130
0.559827
5.321839
false
false
false
false
themonki/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Carthage/Checkouts/QuickLayout/Example/QuickLayout/Utils/Font.swift
6
896
// // Font.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/23/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit typealias MainFont = FontType.HelveticaNeue enum FontType { enum HelveticaNeue: String { case ultraLightItalic = "UltraLightItalic" case medium = "Medium" case mediumItalic = "MediumItalic" case ultraLight = "UltraLight" case italic = "Italic" case light = "Light" case thinItalic = "ThinItalic" case lightItalic = "LightItalic" case bold = "Bold" case thin = "Thin" case condensedBlack = "CondensedBlack" case condensedBold = "CondensedBold" case boldItalic = "BoldItalic" func with(size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)! } } }
apache-2.0
cc60509df5496634a4b2e3600816e98f
26.151515
73
0.612723
4.287081
false
false
false
false
tomterror666/MyLotto
MyLotto/MyLotto/Manager/HTTPManager.swift
1
2063
// // HTTPManager.swift // MyLotto // // Created by Andre Heß on 18/04/16. // Copyright © 2016 Andre Heß. All rights reserved. // import UIKit typealias RequestCompletion = (NSError?, AnyObject?) -> (Void) typealias RequestProgress = (NSProgress) -> (Void) class HTTPManager: NSObject { var sessionManager:AFHTTPSessionManager let lottoBasePath:NSString = "https://www.lotto.de/bin/" static func sharedManager() -> HTTPManager { let me = HTTPManager() return me } override init() { self.sessionManager = AFHTTPSessionManager(baseURL: NSURL(string: self.lottoBasePath as String)) super.init() self.configureSessionManager() } func configureSessionManager() { self.configureRequestSerializer() self.configureResponseSerializer() } func configureRequestSerializer() { let requestSerializer = AFHTTPRequestSerializer() self.sessionManager.requestSerializer = requestSerializer } func configureResponseSerializer() { let responseSerializer = AFHTTPResponseSerializer() self.sessionManager.responseSerializer = responseSerializer } func GET(urlString:NSString, parameters:NSDictionary?, progress:RequestProgress?, completion:RequestCompletion?) { let requestUrlString = (self.lottoBasePath as String) + (urlString as String) self.sessionManager.GET(requestUrlString, parameters: parameters, progress: { (downloadProgress:NSProgress) in if (progress != nil) { progress!(downloadProgress) } }, success: { (task:NSURLSessionDataTask, responseObject:AnyObject?) in if (completion != nil) { let jsonData = responseObject as! NSData let jsonDict = try? NSJSONSerialization.JSONObjectWithData(jsonData, options:NSJSONReadingOptions.AllowFragments) completion!(nil, jsonDict) } }, failure: { (task:NSURLSessionDataTask?, error:NSError) in if (completion != nil) { completion!(error, nil) } }) } }
mit
8b43ef74b86e8467556c13e07c603bf6
29.746269
123
0.681553
4.449244
false
true
false
false
kdawgwilk/vapor
Sources/Generator/Parameter.swift
1
1248
enum Parameter { struct Wildcard { var name: String var generic: String } struct Path { var name: String } case path(Path) case wildcard(Wildcard) var name: String { switch self { case .path(let path): return path.name case .wildcard(let wildcard): return wildcard.name } } var isPath: Bool { switch self { case.path(_): return true default: return false } } var isWildcard: Bool { switch self { case.wildcard(_): return true default: return false } } static func pathFor(_ array: [Parameter]) -> Parameter { var i = 0 for item in array { if item.isPath { i += 1 } } let path = Path(name: "p\(i)") return .path(path) } static func wildcardFor(_ array: [Parameter]) -> Parameter { var i = 0 for item in array { if item.isWildcard { i += 1 } } let path = Wildcard(name: "w\(i)", generic: "W\(i)") return .wildcard(path) } }
mit
ad9c034ec0205112afcfefee89bb7389
17.924242
64
0.451122
4.639405
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/MapResources.swift
1
5455
import Foundation import Postbox import TelegramCore import MapKit import SwiftSignalKit import TGUIKit public struct MapSnapshotMediaResourceId { public let latitude: Double public let longitude: Double public let width: Int32 public let height: Int32 public let zoom: Int32 public var uniqueId: String { return "map-\(latitude)-\(longitude)-\(width)x\(height)-\(zoom)" } public var hashValue: Int { return self.uniqueId.hashValue } } public class MapSnapshotMediaResource: TelegramMediaResource { public let latitude: Double public let longitude: Double public let width: Int32 public let height: Int32 public let zoom: Int32 public init(latitude: Double, longitude: Double, width: Int32, height: Int32, zoom: Int32) { self.latitude = latitude self.longitude = longitude self.width = width self.height = height self.zoom = zoom } public var size: Int64? { return nil } public required init(decoder: PostboxDecoder) { self.latitude = decoder.decodeDoubleForKey("lt", orElse: 0.0) self.longitude = decoder.decodeDoubleForKey("ln", orElse: 0.0) self.width = decoder.decodeInt32ForKey("w", orElse: 0) self.height = decoder.decodeInt32ForKey("h", orElse: 0) self.zoom = decoder.decodeInt32ForKey("z", orElse: 15) } public func encode(_ encoder: PostboxEncoder) { encoder.encodeDouble(self.latitude, forKey: "lt") encoder.encodeDouble(self.longitude, forKey: "ln") encoder.encodeInt32(self.width, forKey: "w") encoder.encodeInt32(self.height, forKey: "h") encoder.encodeInt32(self.zoom, forKey: "z") } public var id: MediaResourceId { return .init(MapSnapshotMediaResourceId(latitude: self.latitude, longitude: self.longitude, width: self.width, height: self.height, zoom: self.zoom).uniqueId) } public func isEqual(to: MediaResource) -> Bool { if let to = to as? MapSnapshotMediaResource { return self.latitude == to.latitude && self.longitude == to.longitude && self.width == to.width && self.height == to.height && self.zoom == to.zoom } else { return false } } } final class MapSnapshotMediaResourceRepresentation: CachedMediaResourceRepresentation { public let keepDuration: CachedMediaRepresentationKeepDuration = .shortLived public var uniqueId: String { return "cached" } public init() { } public func isEqual(to: CachedMediaResourceRepresentation) -> Bool { if let _ = to as? MapSnapshotMediaResourceRepresentation { return true } else { return false } } } let TGGoogleMapsOffset: Int = 268435456 let TGGoogleMapsRadius = Double(TGGoogleMapsOffset) / Double.pi private func yToLatitude(_ y: Int) -> Double { return ((Double.pi / 2.0) - 2 * atan(exp((Double(y - TGGoogleMapsOffset)) / TGGoogleMapsRadius))) * 180.0 / Double.pi; } private func latitudeToY(_ latitude: Double) -> Int { return Int(round(Double(TGGoogleMapsOffset) - TGGoogleMapsRadius * log((1.0 + sin(latitude * Double.pi / 180.0)) / (1.0 - sin(latitude * Double.pi / 180.0))) / 2.0)) } private func adjustGMapLatitude(_ latitude: Double, offset: Int, zoom: Int) -> Double { let t: Int = (offset << (21 - zoom)) return yToLatitude(latitudeToY(latitude) + t) } func fetchMapSnapshotResource(resource: MapSnapshotMediaResource) -> Signal<CachedMediaResourceRepresentationResult, NoError> { return Signal { subscriber in let disposable = MetaDisposable() Queue.concurrentDefaultQueue().async { let options = MKMapSnapshotter.Options() let latitude = adjustGMapLatitude(resource.latitude, offset: -10, zoom: Int(resource.zoom)) options.region = MKCoordinateRegion(center: CLLocationCoordinate2DMake(latitude, resource.longitude), span: MKCoordinateSpan(latitudeDelta: 0.003, longitudeDelta: 0.003)) options.mapType = .standard options.showsPointsOfInterest = false options.showsBuildings = true options.size = CGSize(width: CGFloat(resource.width + 1), height: CGFloat(resource.height + 24)) // options.scale = 2.0 let snapshotter = MKMapSnapshotter(options: options) snapshotter.start(with: DispatchQueue.global(), completionHandler: { result, error in if let image = result?.image, let data = image.tiffRepresentation(using: .jpeg, factor: 0.6) { let imageRep = NSBitmapImageRep(data: data) let compressedData: Data? = imageRep?.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:]) if let data = compressedData { let tempFile = TempBox.shared.tempFile(fileName: "image.jpg") if let _ = try? data.write(to: URL(fileURLWithPath: tempFile.path), options: .atomic) { subscriber.putNext(.tempFile(tempFile)) subscriber.putCompletion() } } } }) disposable.set(ActionDisposable { snapshotter.cancel() }) } return disposable } }
gpl-2.0
a622feeba0342f13b0ad4308eaf4e685
36.363014
182
0.633364
4.478654
false
false
false
false
mpangburn/RayTracer
RayTracer/Models/Frame.swift
1
3856
// // Frame.swift // RayTracer // // Created by Michael Pangburn on 6/26/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import Foundation /// Represents the view frame for a ray tracing scene. struct Frame { /// The lower x-bound of the view. var minX: Double { didSet { freeMaxX = maxX freeMinY = minY freeMaxY = maxY } } /// The upper x-bound of the view. var maxX: Double { get { return aspectRatio == .freeform ? freeMaxX : -minX } set { if aspectRatio != .freeform { minX = -newValue } freeMaxX = newValue } } /// The max x value to be used with the freeform aspect ratio. private var freeMaxX: Double /// The lower y-bound of the view. var minY: Double { get { return aspectRatio == .freeform ? freeMinY : minX / aspectRatio.ratio } set { if aspectRatio != .freeform { minX = newValue * aspectRatio.ratio } freeMinY = newValue } } /// The min y value to be used with the freeform aspect ratio. private var freeMinY: Double /// The upper y-bound of the view. var maxY: Double { get { return aspectRatio == .freeform ? freeMaxY : -minY } set { if aspectRatio != .freeform { minX = -newValue * aspectRatio.ratio } freeMaxY = newValue } } /// The max y value to be used with the freeform aspect ratio. private var freeMaxY: Double /// The z-plane on which the view is seen. var zPlane: Double /// The width of the frame. var width: Int { didSet { freeHeight = height } } /// The height of the frame. var height: Int { get { return aspectRatio == .freeform ? freeHeight : Int(Double(width) / aspectRatio.ratio) } set { if aspectRatio != .freeform { width = Int(Double(newValue) * aspectRatio.ratio) } freeHeight = newValue } } /// The height of the frame to be used with the freeform aspect ratio. private var freeHeight: Int /// Describes options for the width to height ratio of the frame. enum AspectRatio: Int { case freeform case fourThree case sixteenNine var ratio: Double { switch self { case .freeform: return 0 case .fourThree: return 4.0 / 3.0 case .sixteenNine: return 16.0 / 9.0 } } } /// The enforced aspect ratio of the frame. var aspectRatio: AspectRatio { didSet { freeMaxX = maxX freeMinY = minY freeMaxY = maxY freeHeight = height } } init(minX: Double, maxX: Double, minY: Double, maxY: Double, zPlane: Double, width: Int, height: Int, aspectRatio: AspectRatio) { assert(minX < maxX) assert(minY < maxY) self.minX = minX self.freeMaxX = maxX self.freeMinY = minY self.freeMaxY = maxY self.zPlane = zPlane self.width = width self.freeHeight = height self.aspectRatio = aspectRatio } } extension Frame: CustomStringConvertible, CustomDebugStringConvertible { var description: String { return "Frame(minX: \(self.minX), maxX: \(self.maxX), minY: \(self.minY), maxY: \(self.maxY), zPlane: \(self.zPlane), width: \(self.width), height: \(self.height), aspectRatio: \(self.aspectRatio.ratio))" } var debugDescription: String { return self.description } }
mit
d16f2b0e743e897aa46161a6bdac782f
24.7
212
0.538003
4.524648
false
false
false
false
jaegerpicker/WhatsAMonsterOSX
WhatsAMonster/GameScene.swift
1
2777
// // GameScene.swift // WhatsAMonster // // Created by Shawn Campbell on 8/22/15. // Copyright (c) 2015 Team Awesome McPants. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Arial") myLabel.text = "What's a Monster?" myLabel.fontSize = 45 myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) myLabel.name = "menu" let monsterLabel = SKLabelNode(fontNamed: "Arial") monsterLabel.text = "Monster" monsterLabel.fontSize = 35 monsterLabel.fontColor = NSColor.redColor() monsterLabel.position = CGPoint(x: myLabel.position.x, y: myLabel.position.y - 35) monsterLabel.name = "monster" let robotLabel = SKLabelNode(fontNamed: "Arial") robotLabel.text = "Robot" robotLabel.fontSize = 35 robotLabel.fontColor = NSColor.blueColor() robotLabel.name = "robot" robotLabel.position = CGPoint(x: myLabel.position.x, y: myLabel.position.y - 70) self.addChild(myLabel) self.addChild(monsterLabel) self.addChild(robotLabel) } override func mouseDown(theEvent: NSEvent) { /* Called when a mouse click occurs */ let location = theEvent.locationInNode(self) let node = self.nodeAtPoint(location) if node.name == "monster" { let sprite = SKSpriteNode(imageNamed: "pinkMonster") sprite.position = CGPoint(x: 0 + 20, y:CGRectGetMaxY(self.frame) - 50) sprite.setScale(0.02) self.addChild(sprite) let robotNode = node.parent?.childNodeWithName("robot") robotNode?.removeFromParent() let menuLabel = node.parent?.childNodeWithName("menu") menuLabel?.removeFromParent() node.removeFromParent() } else if node.name == "robot" { let sprite = SKSpriteNode(imageNamed:"blueRobot") sprite.position = CGPoint(x: 0 + 20, y:CGRectGetMaxY(self.frame) - 50) sprite.setScale(0.04) self.addChild(sprite) let monsterLabel = node.parent?.childNodeWithName("monster") monsterLabel?.removeFromParent() let menuLabel = node.parent?.childNodeWithName("menu") menuLabel?.removeFromParent() node.removeFromParent() } //let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) //sprite.runAction(SKAction.repeatActionForever(action)) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
fd1856056972093a8d93a44ea4a89dc5
38.112676
92
0.622254
4.493528
false
false
false
false
u10int/Kinetic
Example/Kinetic/SequenceViewController.swift
1
1737
// // SequenceViewController.swift // Motion // // Created by Nicholas Shipes on 12/31/15. // Copyright © 2015 Urban10 Interactive, LLC. All rights reserved. // import UIKit import Kinetic class SequenceViewController: ExampleViewController { var square: UIView! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) title = "Sequence" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white square = UIView() square.frame = CGRect(x: 50, y: 50, width: 50, height: 50) square.backgroundColor = UIColor.red view.addSubview(square) let moveX = Tween(target: square).to(X(110)).duration(0.5).ease(Cubic.easeInOut) let moveY = Tween(target: square).to(Y(250), BackgroundColor(UIColor.orange)).duration(0.5).ease(Cubic.easeInOut) moveY.on(.started) { (animation) -> Void in print("starting moveY") } let resize = Tween(target: square).to(Size(width: 200), BackgroundColor(UIColor.blue)).duration(0.5).ease(Circular.easeInOut) resize.on(.started) { [weak self] (animation) -> Void in print("starting resize") self?.perform(#selector(SequenceViewController.slower), with: nil, afterDelay: 2.0) self?.perform(#selector(SequenceViewController.faster), with: nil, afterDelay: 4.0) } let timeline = Timeline(tweens: [moveX, moveY, resize], align: .sequence) timeline.yoyo().forever() animation = timeline } func slower() { // animation?.slower() animation?.slowMo(to: 0.3, duration: 0.5) } func faster() { animation?.normal() } }
mit
21dfe07bf9a8464162556730233e2b47
26.125
127
0.701037
3.451292
false
false
false
false
ishkawa/DIKit
Sources/DIGenKit/Declarated/PropertyInjectableType.swift
1
2257
// // PropertyInjectableType.swift // DIGenKit // // Created by Yosuke Ishikawa on 2017/09/22. // import Foundation import SourceKittenFramework struct PropertyInjectableType { struct Error: LocalizedError, Findable { enum Reason { case protocolConformanceNotFound case associatedTypeNotFound case propertyNotFound case nonStructAssociatedType } let type: Type let reason: Reason var file: File { return type.file } var offset: Int64 { return type.offset } var errorDescription: String? { switch reason { case .protocolConformanceNotFound: return "Type is not declared as conformer of 'PropertyInjectableType'" case .associatedTypeNotFound: return "Associated type 'Dependency' declared in 'PropertyInjectableType' is not found" case .propertyNotFound: return "Instance property 'dependency' declared in 'PropertyInjectable' is not found" case .nonStructAssociatedType: return "Associated type 'Dependency' must be a struct" } } } let name: String let dependencyProperties: [Property] init(type: Type) throws { guard type.inheritedTypeNames.contains("PropertyInjectable") || type.inheritedTypeNames.contains("DIKit.PropertyInjectable") else { throw Error(type: type, reason: .protocolConformanceNotFound) } guard let dependencyType = type.nestedTypes.first(where: { $0.name == "Dependency" }) else { throw Error(type: type, reason: .associatedTypeNotFound) } guard dependencyType.kind == .struct else { throw Error(type: type, reason: .nonStructAssociatedType) } guard let property = type.properties.first(where: { $0.name == "dependency" }), !property.isStatic && property.typeName == "Dependency!" else { throw Error(type: type, reason: .propertyNotFound) } name = type.name dependencyProperties = dependencyType.properties.filter { !$0.isStatic } } }
mit
fc88ce46c8861514d8b7c536e75c8cf8
30.347222
103
0.610545
4.993363
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Settings/AppSettingsOptions.swift
1
45453
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var accessibilityIdentifier: String? { return "SignInToSync" } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.imageView?.image = UIImage.templateImageNamed("FxA-Default") cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 cell.imageView?.layer.masksToBounds = true } } class SyncNowSetting: WithAccountSetting { let imageView = UIImageView(frame: CGRect(width: 30, height: 30)) let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear) let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20)) let syncIcon = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20)) // Animation used to rotate the Sync icon 360 degrees while syncing is in progress. let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation") override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil) } fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { if !DeviceInfo.hasConnectivity() { return NSAttributedString( string: Strings.FxANoInternetConnection, attributes: [ NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultMediumFont ] ) } return NSAttributedString( string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [ NSAttributedStringKey.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedStringKey.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)]) func startRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey") } } @objc func stopRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.removeAllAnimations() } } override var accessoryType: UITableViewCellAccessoryType { return .none } override var style: UITableViewCellStyle { return .value1 } override var image: UIImage? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncIcon } switch syncStatus { case .inProgress: return syncBlueIcon default: return syncIcon } } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var enabled: Bool { if !DeviceInfo.hasConnectivity() { return false } return profile.hasSyncableAccount() } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: .roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity() // Animation that loops continously until stopped continuousRotateAnimation.fromValue = 0.0 continuousRotateAnimation.toValue = CGFloat(Double.pi) continuousRotateAnimation.isRemovedOnCompletion = true continuousRotateAnimation.duration = 0.5 continuousRotateAnimation.repeatCount = .infinity // To ensure sync icon is aligned properly with user's avatar, an image is created with proper // dimensions and color, then the scaled sync icon is added as a subview. imageView.contentMode = .center imageView.image = image cell.imageView?.subviews.forEach({ $0.removeFromSuperview() }) cell.imageView?.image = syncIconWrapper cell.imageView?.addSubview(imageView) if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .inProgress: self.startRotateSyncIcon() default: self.stopRotateSyncIcon() } } } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { if !DeviceInfo.hasConnectivity() { return } NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil) } @objc func updateAccount(notification: Notification) { DispatchQueue.main.async { self.settings.tableView.reloadData() } } override var image: UIImage? { if let image = profile.getAccount()?.fxaProfile?.avatar.image { return image.createScaled(CGSize(width: 30, height: 30)) } let image = UIImage(named: "placeholder-avatar") return image?.createScaled(CGSize(width: 30, height: 30)) } override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: // We link to the resend verification email page. return .disclosureIndicator case .needsPassword: // We link to the re-enter password page. return .disclosureIndicator case .none: // We link to FxA web /settings. return .disclosureIndicator case .needsUpgrade: // In future, we'll want to link to an upgrade page. return .none } } return .disclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { if let displayName = account.fxaProfile?.displayName { return NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } if let email = account.fxaProfile?.email { return NSAttributedString(string: email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } return NSAttributedString(string: account.email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { var string: String switch account.actionNeeded { case .none: return nil case .needsVerification: string = Strings.FxAAccountVerifyEmail break case .needsPassword: string = Strings.FxAAccountVerifyPassword break case .needsUpgrade: string = Strings.FxAAccountUpgradeFirefox break } let orange = UIColor.theme.tableView.warningText let range = NSRange(location: 0, length: string.count) let attrs = [NSAttributedStringKey.foregroundColor: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } return nil } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .none: let viewController = SyncContentSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) return case .needsVerification: var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = try? cs?.asURL() { viewController.url = url } case .needsPassword: var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = try? cs?.asURL() { viewController.url = url } case .needsUpgrade: // In future, we'll want to link to an upgrade page. return } } navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let imageView = cell.imageView { imageView.subviews.forEach({ $0.removeFromSuperview() }) imageView.frame = CGRect(width: 30, height: 30) imageView.layer.cornerRadius = (imageView.frame.height) / 2 imageView.layer.masksToBounds = true imageView.image = image } } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.hasPrefix("browser.") || file.hasPrefix("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } class ExportLogDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Logger.copyPreviousLogsToDocuments(); } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class EnableBookmarkMergingSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Enable Bidirectional Bookmark Sync ", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { AppConstants.shouldMergeBookmarks = true } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Sentry.shared.crash() } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController override var accessibilityIdentifier: String? { return "FxVersion" } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } // Opens the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { let statusText = NSMutableAttributedString() statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])) statusText.append(NSAttributedString(string: " ")) statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.highlightBlue])) super.init( prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle), attributedStatusText: statusText, settingDidChange: { AdjustIntegration.setEnabled($0) LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0]) LeanPlumClient.shared.set(enabled: $0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { self.settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) }, cancel: { self.deselectRow() }, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings) self.deselectRow() }) } else { settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let localAuthContext = LAContext() let title: String if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 11, *) class ContentBlockerSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TrackingProtection" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ContentBlockerSettingViewController(prefs: profile.prefs) viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsDataManagementSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) } } class StageSyncServiceDebugSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } var prefKey: String = "useStageSyncService" override var accessibilityIdentifier: String? { return "DebugStageSync" } override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return true } return false } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { // Derive the configuration we display from the profile. Currently, this could be either a custom // FxA server or FxA stage servers. let isOn = prefs.boolForKey(prefKey) ?? false let isCustomSync = prefs.boolForKey(PrefsKeys.KeyUseCustomSyncService) ?? false var configurationURL = ProductionFirefoxAccountConfiguration().authEndpointURL if isCustomSync { configurationURL = CustomFirefoxAccountConfiguration(prefs: profile.prefs).authEndpointURL } else if isOn { configurationURL = StageFirefoxAccountConfiguration().authEndpointURL } return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? false cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) settings.tableView.reloadData() } } class HomePageSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Homepage" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingsViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabContentSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 12.0, *) class SiriPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "SiriSettings" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SiriSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class AdvanceAccountSetting: HiddenSetting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "AdvanceAccount.Setting" } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsAdvanceAccountTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdvanceAccountSettingViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override var hidden: Bool { return !ShowDebugSettings || profile.hasAccount() } } class ThemeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var accessibilityIdentifier: String? { return "DisplayThemeOption" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(ThemeSettingsController(), animated: true) } }
mpl-2.0
d5388c0f4720953deb933841dab45f7c
40.211434
327
0.696928
5.772115
false
false
false
false
lotpb/iosSQLswift
mySQLswift/YQL.swift
1
1627
// // YQL.swift // YQLSwift // // Created by Jake Lee on 1/25/15. // Copyright (c) 2015 JHL. All rights reserved. // import Foundation struct YQL { // Yahoo finance query string private static let prefix:NSString = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=&q=" static func query(statement:String) -> NSDictionary? { // update query to contain symbol of stock to search on let escapedStatement = statement.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) let query = "\(prefix)\(escapedStatement!)" var results:NSDictionary? = nil var jsonError:NSError? = nil var jsonDataError:NSError? = nil let jsonData: NSData? do { jsonData = try NSData(contentsOfURL: NSURL(string: query)!, options: NSDataReadingOptions.DataReadingMappedIfSafe) } catch let error as NSError { jsonError = error jsonData = nil } if jsonData != nil { do { results = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary } catch let error as NSError { results = nil jsonDataError = error } } if jsonError != nil || jsonDataError != nil{ NSLog( "ERROR while fetching/deserializing YQL data. Message \(jsonError!)" ) } return results } }
gpl-2.0
43017a2fd8316194db7af200ef96eb7e
31.54
162
0.601721
4.915408
false
false
false
false
hooman/swift
test/Distributed/distributed_actor_nonisolated.swift
3
2035
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking // REQUIRES: concurrency // REQUIRES: distributed import _Distributed @available(SwiftStdlib 5.5, *) distributed actor DA { let local: Int = 42 // expected-note@-1{{distributed actor state is only available within the actor instance}} // expected-note@-2{{distributed actor state is only available within the actor instance}} nonisolated let nope: Int = 13 // expected-error@-1{{'nonisolated' can not be applied to distributed actor stored properties}} nonisolated var computedNonisolated: Int { // expected-note@-1{{distributed actor state is only available within the actor instance}} // nonisolated computed properties are outside of the actor and as such cannot access local _ = self.local // expected-error{{distributed actor-isolated property 'local' can only be referenced inside the distributed actor}} _ = self.id // ok, special handled and always available _ = self.actorTransport // ok, special handled and always available } distributed func dist() {} nonisolated func access() async throws { _ = self.id // ok _ = self.actorTransport // ok // self is a distributed actor self is NOT isolated _ = self.local // expected-error{{distributed actor-isolated property 'local' can only be referenced inside the distributed actor}} _ = try await self.dist() // ok, was made implicitly throwing and async _ = self.computedNonisolated // expected-error{{only 'distributed' functions can be called from outside the distributed actor}} } nonisolated distributed func nonisolatedDistributed() async { // expected-error@-1{{function 'nonisolatedDistributed()' cannot be both 'nonisolated' and 'distributed'}}{{3-15=}} fatalError() } distributed nonisolated func distributedNonisolated() async { // expected-error@-1{{function 'distributedNonisolated()' cannot be both 'nonisolated' and 'distributed'}}{{15-27=}} fatalError() } }
apache-2.0
ae091d75dc9e90e68a060a1da56059df
40.55102
135
0.72629
4.68894
false
false
false
false
nanthi1990/SwiftDate
SwiftDate/SwiftDate.swift
3
43597
// // SwiftDate.swift // SwiftDate // // Copyright (c) 2015 Daniele Margutti // // 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: STRING EXTENSION SHORTCUTS public extension String { /** Create a new NSDate object with passed custom format string :param: format format as string :returns: a new NSDate instance with parsed date, or nil if it's fail */ func toDate(#formatString: String!) -> NSDate? { return NSDate.date(fromString: self, format: DateFormat.Custom(formatString)) } /** Create a new NSDate object with passed date format :param: format format :returns: a new NSDate instance with parsed date, or nil if it's fail */ func toDate(#format: DateFormat) -> NSDate? { return NSDate.date(fromString: self, format: format) } } //MARK: ACCESS TO DATE COMPONENTS public extension NSDate { // Use this as shortcuts for the most common formats for dates class var commonFormats : [String] { return [ "yyyy-MM-ddTHH:mm:ssZ", // ISO8601 "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy-MM-dd", "h:mm:ss A", "h:mm A", "MM/dd/yyyy", "MMMM d, yyyy", "MMMM d, yyyy LT", "dddd, MMMM D, yyyy LT", "yyyyyy-MM-dd", "yyyy-MM-dd", "GGGG-[W]WW-E", "GGGG-[W]WW", "yyyy-ddd", "HH:mm:ss.SSSS", "HH:mm:ss", "HH:mm", "HH" ] } /// Get the year component of the date var year : Int { return components.year } /// Get the month component of the date var month : Int { return components.month } // Get the week of the month component of the date var weekOfMonth: Int { return components.weekOfMonth } // Get the week of the month component of the date var weekOfYear: Int { return components.weekOfYear } /// Get the weekday component of the date var weekday: Int { return components.weekday } /// Get the weekday ordinal component of the date var weekdayOrdinal: Int { return components.weekdayOrdinal } /// Get the day component of the date var day: Int { return components.day } /// Get the hour component of the date var hour: Int { return components.hour } /// Get the minute component of the date var minute: Int { return components.minute } // Get the second component of the date var second: Int { return components.second } // Get the era component of the date var era: Int { return components.era } // Get the current month name based upon current locale var monthName: String { let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.locale = NSLocale.autoupdatingCurrentLocale() return dateFormatter.monthSymbols[month - 1] as! String } // Get the current weekday name var weekdayName: String { let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.locale = NSLocale.autoupdatingCurrentLocale() dateFormatter.dateFormat = "EEEE" dateFormatter.timeZone = NSTimeZone.localTimeZone() return dateFormatter.stringFromDate(self) } private func firstWeekDate()-> (date : NSDate!, interval: NSTimeInterval) { // Sunday 1, Monday 2, Tuesday 3, Wednesday 4, Friday 5, Saturday 6 var calendar = NSCalendar.currentCalendar() calendar.firstWeekday = NSCalendar.currentCalendar().firstWeekday var startWeek: NSDate? = nil var duration: NSTimeInterval = 0 calendar.rangeOfUnit(NSCalendarUnit.CalendarUnitWeekOfYear, startDate: &startWeek, interval: &duration, forDate: self) return (startWeek,duration) } /// Return the first day of the current date's week var firstDayOfWeek : Int { let (date,interval) = self.firstWeekDate() return date.day } /// Return the last day of the week var lastDayOfWeek : Int { let (startWeek,interval) = self.firstWeekDate() var endWeek = startWeek?.dateByAddingTimeInterval(interval-1) return endWeek!.day } /// Return the nearest hour of the date var nearestHour:NSInteger{ var aTimeInterval = NSDate.timeIntervalSinceReferenceDate() + Double(D_MINUTE) * Double(30); var newDate = NSDate(timeIntervalSinceReferenceDate:aTimeInterval); var components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour, fromDate: newDate); return components.hour; } } //MARK: CREATE AND MANIPULATE DATE COMPONENTS public extension NSDate { /** Create a new NSDate instance from passed string with given format :param: string date as string :param: format parse formate. :returns: a new instance of the string */ class func date(fromString string: String, format: DateFormat) -> NSDate? { if string.isEmpty { return nil } let dateFormatter = NSDate.localThreadDateFormatter() switch format { case .ISO8601: // 1972-07-16T08:15:30-05:00 dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.timeZone = NSTimeZone.localTimeZone() dateFormatter.dateFormat = ISO8601Formatter(fromString: string) return dateFormatter.dateFromString(string) case .AltRSS: // 09 Sep 2011 15:26:08 +0200 var formattedString : NSString = string if formattedString.hasSuffix("Z") { formattedString = formattedString.substringToIndex(formattedString.length-1) + "GMT" } dateFormatter.dateFormat = "d MMM yyyy HH:mm:ss ZZZ" return dateFormatter.dateFromString(formattedString as String) case .RSS: // Fri, 09 Sep 2011 15:26:08 +0200 var formattedString : NSString = string if formattedString.hasSuffix("Z") { formattedString = formattedString.substringToIndex(formattedString.length-1) + "GMT" } dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" return dateFormatter.dateFromString(formattedString as String) case .Custom(let dateFormat): dateFormatter.dateFormat = dateFormat return dateFormatter.dateFromString(string) } } /** Attempts to handle all different ISO8601 formatters and returns correct date format for string http://www.w3.org/TR/NOTE-datetime */ class func ISO8601Formatter(fromString string: String) -> String { enum IS08601Format: Int { // YYYY (eg 1997) case Year = 4 // YYYY-MM (eg 1997-07) case YearAndMonth = 7 // YYYY-MM-DD (eg 1997-07-16) case CompleteDate = 10 // YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) case CompleteDatePlusHoursAndMinutes = 22 //YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) case CompleteDatePlusHoursMinutesAndSeconds = 25 // YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) case CompleteDatePlusHoursMinutesSecondsAndDecimalFractionOfSecond = 28 } var dateFormatter = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" if let dateStringCount = IS08601Format(rawValue: count(string)) { switch dateStringCount { case .Year: dateFormatter = "yyyy" case .YearAndMonth: dateFormatter = "yyyy-MM" case .CompleteDate: dateFormatter = "yyyy-MM-dd" case .CompleteDatePlusHoursAndMinutes: dateFormatter = "yyyy-MM-dd'T'HH:mmZ" case .CompleteDatePlusHoursMinutesAndSeconds: dateFormatter = "yyyy-MM-dd'T'HH:mm:ssZ" default: // YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) dateFormatter = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" } } return dateFormatter } /** Create a new NSDate instance based on refDate (if nil uses current date) and set components :param: refDate reference date instance (nil to use NSDate()) :param: year year component (nil to leave it untouched) :param: month month component (nil to leave it untouched) :param: day day component (nil to leave it untouched) :param: tz time zone component (it's the abbreviation of NSTimeZone, like 'UTC' or 'GMT+2', nil to use current time zone) :returns: a new NSDate with components changed according to passed params */ class func date(#refDate: NSDate?, year: Int?, month: Int?, day: Int?, tz: String?) -> NSDate { let referenceDate = refDate ?? NSDate() return referenceDate.set(year: year, month: month, day: day, hour: 0, minute: 0, second: 0, tz: tz) } /** Create a new NSDate instance based on refDate (if nil uses current date) and set components :param: refDate reference date instance (nil to use NSDate()) :param: year year component (nil to leave it untouched) :param: month month component (nil to leave it untouched) :param: day day component (nil to leave it untouched) :param: hour hour component (nil to leave it untouched) :param: minute minute component (nil to leave it untouched) :param: second second component (nil to leave it untouched) :param: tz time zone component (it's the abbreviation of NSTimeZone, like 'UTC' or 'GMT+2', nil to use current time zone) :returns: a new NSDate with components changed according to passed params */ class func date(#refDate: NSDate?, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, tz: String?) -> NSDate { let referenceDate = refDate ?? NSDate() return referenceDate.set(year: year, month: month, day: day, hour: hour, minute: minute, second: second, tz: tz) } /** Return a new NSDate instance with the current date and time set to 00:00:00 :param: tz optional timezone abbreviation :returns: a new NSDate instance of the today's date */ class func today(tz: String? = nil) -> NSDate! { let nowDate = NSDate() return NSDate.date(refDate: nowDate, year: nowDate.year, month: nowDate.month, day: nowDate.day, tz: tz) } /** Return a new NSDate istance with the current date minus one day :param: tz optional timezone abbreviation :returns: a new NSDate instance which represent yesterday's date */ class func yesterday(tz: String? = nil) -> NSDate! { return today(tz: tz)-1.day } /** Return a new NSDate istance with the current date plus one day :param: tz optional timezone abbreviation :returns: a new NSDate instance which represent tomorrow's date */ class func tomorrow(tz: String? = nil) -> NSDate! { return today(tz: tz)+1.day } /** Individual set single component of the current date instance :param: year a non-nil value to change the year component of the instance :param: month a non-nil value to change the month component of the instance :param: day a non-nil value to change the day component of the instance :param: hour a non-nil value to change the hour component of the instance :param: minute a non-nil value to change the minute component of the instance :param: second a non-nil value to change the second component of the instance :param: tz a non-nil value (timezone abbreviation string as for NSTimeZone) to change the timezone component of the instance :returns: a new NSDate instance with changed values */ func set(#year: Int?, month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?, tz: String?) -> NSDate! { let components = self.components components.year = year ?? self.year components.month = month ?? self.month components.day = day ?? self.day components.hour = hour ?? self.hour components.minute = minute ?? self.minute components.second = second ?? self.second components.timeZone = (tz != nil ? NSTimeZone(abbreviation: tz!) : NSTimeZone.defaultTimeZone()) return NSCalendar.currentCalendar().dateFromComponents(components) } /** Allows you to set individual date components by passing an array of components name and associated values :param: componentsDict components dict. Accepted keys are year,month,day,hour,minute,second :returns: a new date instance with altered components according to passed dictionary */ func set(#componentsDict: [String:Int]!) -> NSDate? { if count(componentsDict) == 0 { return self } let components = self.components for (thisComponent,value) in componentsDict { let unit : NSCalendarUnit = thisComponent._sdToCalendarUnit() components.setValue(value, forComponent: unit); } return NSCalendar.currentCalendar().dateFromComponents(components) } /** Allows you to set a single component by passing it's name (year,month,day,hour,minute,second are accepted). Please note: this method return a new immutable NSDate instance (NSDate are immutable, damn!). So while you can chain multiple set calls, if you need to alter more than one component see the method above which accept different params. :param: name the name of the component to alter (year,month,day,hour,minute,second are accepted) :param: value the value of the component :returns: a new date instance */ func set(name : String!, value : Int!) -> NSDate? { let unit : NSCalendarUnit = name._sdToCalendarUnit() if unit == nil { return nil } let components = self.components components.setValue(value, forComponent: unit); return NSCalendar.currentCalendar().dateFromComponents(components) } /** Add or subtract (via negative values) components from current date instance :param: years nil or +/- years to add or subtract from date :param: months nil or +/- months to add or subtract from date :param: weeks nil or +/- weeks to add or subtract from date :param: days nil or +/- days to add or subtract from date :param: hours nil or +/- hours to add or subtract from date :param: minutes nil or +/- minutes to add or subtract from date :param: seconds nil or +/- seconds to add or subtract from date :returns: a new NSDate instance with changed values */ func add(#years: Int?, months: Int?, weeks: Int?, days: Int?,hours: Int?,minutes: Int?,seconds: Int?) -> NSDate { var components = NSDateComponents() components.year = years ?? 0 components.month = months ?? 0 components.weekOfYear = weeks ?? 0 components.day = days ?? 0 components.hour = hours ?? 0 components.minute = minutes ?? 0 components.second = seconds ?? 0 return self.addComponents(components) } /** Add/substract (based on sign) specified component with value :param: name component name (year,month,day,hour,minute,second) :param: value value of the component :returns: new date with altered component */ func add(name : String!, value : Int!) -> NSDate? { let unit : NSCalendarUnit = name._sdToCalendarUnit() if unit == nil { return nil } let components = NSDateComponents() components.setValue(value, forComponent: unit); return self.addComponents(components) } /** Add value specified by components in passed dictionary to the current date :param: componentsDict dictionary of the component to alter with value (year,month,day,hour,minute,second) :returns: new date with altered components */ func add(#componentsDict: [String:Int]!) -> NSDate? { if count(componentsDict) == 0 { return self } let components = NSDateComponents() for (thisComponent,value) in componentsDict { let unit : NSCalendarUnit = thisComponent._sdToCalendarUnit() components.setValue(value, forComponent: unit); } return self.addComponents(components) } } //MARK: TIMEZONE UTILITIES public extension NSDate { /** Return a new NSDate in UTC format from the current system timezone :returns: a new NSDate instance */ func toUTC() -> NSDate { var tz : NSTimeZone = NSTimeZone.localTimeZone() var secs : Int = tz.secondsFromGMTForDate(self) return NSDate(timeInterval: NSTimeInterval(secs), sinceDate: self) } /** Convert an UTC NSDate instance to a local time NSDate (note: NSDate object does not contains info about the timezone!) :returns: a new NSDate instance */ func toLocalTime() -> NSDate { var tz : NSTimeZone = NSTimeZone.localTimeZone() var secs : Int = -tz.secondsFromGMTForDate(self) return NSDate(timeInterval: NSTimeInterval(secs), sinceDate: self) } /** Convert an UTC NSDate instance to passed timezone (note: NSDate object does not contains info about the timezone!) :param: abbreviation abbreviation of the time zone :returns: a new NSDate instance */ func toTimezone(abbreviation : String!) -> NSDate? { var tz : NSTimeZone? = NSTimeZone(abbreviation: abbreviation) if tz == nil { return nil } var secs : Int = tz!.secondsFromGMTForDate(self) return NSDate(timeInterval: NSTimeInterval(secs), sinceDate: self) } } //MARK: COMPARE DATES public extension NSDate { func secondsAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval) } func secondsBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval) } /** Return the number of minutes between two dates. :param: date comparing date :returns: number of minutes */ func minutesAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSTimeInterval(D_MINUTE)) } func minutesBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSTimeInterval(D_MINUTE)) } func hoursAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSTimeInterval(D_HOUR)) } func hoursBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSTimeInterval(D_HOUR)) } func daysAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSTimeInterval(D_DAY)) } func daysBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSTimeInterval(D_DAY)) } /** Compare two dates and return true if they are equals :param: date date to compare with :param: ignoreTime true to ignore time of the date :returns: true if two dates are equals */ func isEqualToDate(date: NSDate, ignoreTime: Bool) -> Bool { if ignoreTime { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) return ((comp1.year == comp2.year) && (comp1.month == comp2.month) && (comp1.day == comp2.day)) } else { return self.isEqualToDate(date) } } /** Return true if given date's time in passed range :param: minTime min time interval (by default format is "HH:mm", but you can specify your own format in format parameter) :param: maxTime max time interval (by default format is "HH:mm", but you can specify your own format in format parameter) :param: format nil or a valid format string used to parse minTime and maxTime from their string representation (when nil HH:mm is used) :returns: true if date's time component falls into given range */ func isInTimeRange(minTime: String!, maxTime: String!, format: String?) -> Bool { let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.dateFormat = format ?? "HH:mm" dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") let minTimeDate = dateFormatter.dateFromString(minTime) let maxTimeDate = dateFormatter.dateFromString(maxTime) if minTimeDate == nil || maxTimeDate == nil { return false } let inBetween = (self.compare(minTimeDate!) == NSComparisonResult.OrderedDescending && self.compare(maxTimeDate!) == NSComparisonResult.OrderedAscending) return inBetween } /** Return true if the date's year is a leap year :returns: true if date's year is a leap year */ func isLeapYear() -> Bool { var year = self.year return year % 400 == 0 ? true : ((year % 4 == 0) && (year % 100 != 0)) } /** Return the number of days in current date's month :returns: number of days of the month */ func monthDays () -> Int { return NSCalendar.currentCalendar().rangeOfUnit(NSCalendarUnit.CalendarUnitDay, inUnit: NSCalendarUnit.CalendarUnitMonth, forDate: self).length } /** True if the date is the current date :returns: true if date is today */ func isToday() -> Bool { return self.isEqualToDate(NSDate(), ignoreTime: true) } /** True if the date is the current date plus one day (tomorrow) :returns: true if date is tomorrow */ func isTomorrow() -> Bool { return self.isEqualToDate(NSDate()+1.day, ignoreTime:true) } /** True if the date is the current date minus one day (yesterday) :returns: true if date is yesterday */ func isYesterday() -> Bool { return self.isEqualToDate(NSDate()-1.day, ignoreTime:true) } /** Return true if the date falls into the current week :returns: true if date is inside the current week days range */ func isThisWeek() -> Bool { return self.isSameWeekOf(NSDate()) } /** Return true if the date falls into the current month :returns: true if date is inside the current month */ func isThisMonth() -> Bool { return self.isSameMonthOf(NSDate()) } /** Return true if the date falls into the current year :returns: true if date is inside the current year */ func isThisYear() -> Bool { return self.isSameYearOf(NSDate()) } /** Return true if the date is in the same week of passed date :param: date date to compare with :returns: true if both dates falls in the same week */ func isSameWeekOf(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) // Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week if comp1.weekOfYear != comp2.weekOfYear { return false } // Must have a time interval under 1 week let weekInSeconds = NSTimeInterval(D_WEEK) return abs(self.timeIntervalSinceDate(date)) < weekInSeconds } /** Return the first day of the passed date's week (Sunday) :returns: NSDate with the date of the first day of the week */ func dateAtWeekStart() -> NSDate { let flags : NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitWeekday var components = NSCalendar.currentCalendar().components(flags, fromDate: self) components.weekday = 1 // Sunday components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /// Return a date which represent the beginning of the current day (at 00:00:00) var beginningOfDay: NSDate { return set(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, tz: nil) } /// Return a date which represent the end of the current day (at 23:59:59) var endOfDay: NSDate { return set(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, tz: nil) } /// Return the first day of the month of the current date var beginningOfMonth: NSDate { return set(year: nil, month: nil, day: 1, hour: 0, minute: 0, second: 0, tz: nil) } /// Return the last day of the month of the current date var endOfMonth: NSDate { let lastDay = NSCalendar.currentCalendar().rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: self).length return set(year: nil, month: nil, day: lastDay, hour: 23, minute: 59, second: 59, tz: nil) } /// Returns true if the date is in the same month of passed date func isSameMonthOf(date: NSDate) -> Bool { return self >= date.beginningOfMonth && self <= date.endOfMonth } /// Return the first day of the year of the current date var beginningOfYear: NSDate { return set(year: nil, month: 1, day: 1, hour: 0, minute: 0, second: 0, tz: nil) } /// Return the last day of the year of the current date var endOfYear: NSDate { return set(year: nil, month: 12, day: 31, hour: 23, minute: 59, second: 59, tz: nil) } /// Returns true if the date is in the same year of passed date func isSameYearOf(date: NSDate) -> Bool { return self >= date.beginningOfYear && self <= date.endOfYear } /** Return true if current date's day is not a weekend day :returns: true if date's day is a week day, not a weekend day */ func isWeekday() -> Bool { return !self.isWeekend() } /** Return true if the date is the weekend :returns: true or false */ func isWeekend() -> Bool { let range = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.CalendarUnitWeekday) return (self.weekday == range.location || self.weekday == range.length) } } //MARK: CONVERTING DATE TO STRING public extension NSDate { /** Return a formatted string with passed style for date and time :param: dateStyle style of the date component into the output string :param: timeStyle style of the time component into the output string :param: relativeDate true to use relative date style :returns: string representation of the date */ public func toString(#dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, relativeDate: Bool = false) -> String { let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.dateStyle = dateStyle dateFormatter.timeStyle = timeStyle dateFormatter.doesRelativeDateFormatting = relativeDate return dateFormatter.stringFromDate(self) } /** Return a new string which represent the NSDate into passed format :param: format format of the output string. Choose one of the available format or use a custom string :returns: a string with formatted date */ public func toString(#format: DateFormat) -> String { var dateFormat: String switch format { case .ISO8601: dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" case .RSS: dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" case .AltRSS: dateFormat = "d MMM yyyy HH:mm:ss ZZZ" case .Custom(let string): dateFormat = string } let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.dateFormat = dateFormat return dateFormatter.stringFromDate(self) } /** Return an ISO8601 formatted string from the current date instance :returns: string with date in ISO8601 format */ public func toISOString() -> String { let dateFormatter = NSDate.localThreadDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" return dateFormatter.stringFromDate(self).stringByAppendingString("Z") } /** Return a relative string which represent the date instance :param: fromDate comparison date (by default is the current NSDate()) :param: abbreviated true to use abbreviated unit forms (ie. "ys" instead of "years") :param: maxUnits max detail units to print (ie. "1 hour 47 minutes" is maxUnit=2, "1 hour" is maxUnit=1) :returns: formatted string */ public func toRelativeString(fromDate: NSDate = NSDate(), abbreviated : Bool = false, maxUnits: Int = 1) -> String { let seconds = fromDate.timeIntervalSinceDate(self) if fabs(seconds) < 1 { return "just now"._sdLocalize } let significantFlags : NSCalendarUnit = NSDate.componentFlags() let components = NSCalendar.currentCalendar().components(significantFlags, fromDate: fromDate, toDate: self, options: nil) var string = String() var isApproximate:Bool = false var numberOfUnits:Int = 0 let unitList : [String] = ["year", "month", "weekOfYear", "day", "hour", "minute", "second"] for unitName in unitList { let unit : NSCalendarUnit = unitName._sdToCalendarUnit() if ((significantFlags.rawValue & unit.rawValue) != 0) && (_sdCompareCalendarUnit(NSCalendarUnit.CalendarUnitSecond, other: unit) != .OrderedDescending) { let number:NSNumber = NSNumber(float: fabsf(components.valueForKey(unitName)!.floatValue)) if Bool(number.integerValue) { let singular = (number.unsignedIntegerValue == 1) let suffix = String(format: "%@ %@", arguments: [number, _sdLocalizeStringForValue(singular, unit: unit, abbreviated: abbreviated)]) if string.isEmpty { string = suffix } else if numberOfUnits < maxUnits { string += String(format: " %@", arguments: [suffix]) } else { isApproximate = true } numberOfUnits += 1 } } } if string.isEmpty == false { if seconds > 0 { string = String(format: "%@ %@", arguments: [string, "ago"._sdLocalize]) } else { string = String(format: "%@ %@", arguments: [string, "from now"._sdLocalize]) } if (isApproximate) { string = String(format: "about %@", arguments: [string]) } } return string } /** Return a string representation of the date where both date and time are in short style format :returns: date's string representation */ public func toShortString() -> String { return toString(dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle) } /** Return a string representation of the date where both date and time are in medium style format :returns: date's string representation */ public func toMediumString() -> String { return toString(dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.MediumStyle) } /** Return a string representation of the date where both date and time are in long style format :returns: date's string representation */ public func toLongString() -> String { return toString(dateStyle: NSDateFormatterStyle.LongStyle, timeStyle: NSDateFormatterStyle.LongStyle) } /** Return a string representation of the date with only the date in short style format (no time) :returns: date's string representation */ public func toShortDateString() -> String { return toString(dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.NoStyle) } /** Return a string representation of the date with only the time in short style format (no date) :returns: date's string representation */ public func toShortTimeString() -> String { return toString(dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle) } /** Return a string representation of the date with only the date in medium style format (no date) :returns: date's string representation */ public func toMediumDateString() -> String { return toString(dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle) } /** Return a string representation of the date with only the time in medium style format (no date) :returns: date's string representation */ public func toMediumTimeString() -> String { return toString(dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.MediumStyle) } /** Return a string representation of the date with only the date in long style format (no date) :returns: date's string representation */ public func toLongDateString() -> String { return toString(dateStyle: NSDateFormatterStyle.LongStyle, timeStyle: NSDateFormatterStyle.NoStyle) } /** Return a string representation of the date with only the time in long style format (no date) :returns: date's string representation */ public func toLongTimeString() -> String { return toString(dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.LongStyle) } } //MARK: PRIVATE ACCESSORY METHODS private extension NSDate { private class func components(#fromDate: NSDate) -> NSDateComponents! { return NSCalendar.currentCalendar().components(NSDate.componentFlags(), fromDate: fromDate) } private func addComponents(components: NSDateComponents) -> NSDate { let cal = NSCalendar.currentCalendar() return cal.dateByAddingComponents(components, toDate: self, options: nil)! } private class func componentFlags() -> NSCalendarUnit { return NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitWeekdayOrdinal | NSCalendarUnit.CalendarUnitWeekOfYear } /// Return the NSDateComponents which represent current date private var components: NSDateComponents { return NSCalendar.currentCalendar().components(NSDate.componentFlags(), fromDate: self) } /** This function uses NSThread dictionary to store and retrive a thread-local object, creating it if it has not already been created :param: key identifier of the object context :param: create create closure that will be invoked to create the object :returns: a cached instance of the object */ private class func cachedObjectInCurrentThread<T: AnyObject>(key: String, create: () -> T) -> T { if let threadDictionary = NSThread.currentThread().threadDictionary as NSMutableDictionary? { if let cachedObject = threadDictionary[key] as! T? { return cachedObject } else { let newObject = create() threadDictionary[key] = newObject return newObject } } else { assert(false, "Current NSThread dictionary is nil. This should never happens, we will return a new instance of the object on each call") return create() } } /** Return a thread-cached NSDateFormatter instance :returns: instance of NSDateFormatter */ private class func localThreadDateFormatter() -> NSDateFormatter { return NSDate.cachedObjectInCurrentThread("com.library.swiftdate.dateformatter") { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" return dateFormatter } } } //MARK: RELATIVE NSDATE CONVERSION PRIVATE METHODS private extension NSDate { func _sdCompareCalendarUnit(unit:NSCalendarUnit, other:NSCalendarUnit) -> NSComparisonResult { let nUnit = _sdNormalizedCalendarUnit(unit) let nOther = _sdNormalizedCalendarUnit(other) if (nUnit == NSCalendarUnit.CalendarUnitWeekOfYear) != (nOther == NSCalendarUnit.CalendarUnitWeekOfYear) { if nUnit == NSCalendarUnit.CalendarUnitWeekOfYear { switch nUnit { case NSCalendarUnit.CalendarUnitYear, NSCalendarUnit.CalendarUnitMonth: return .OrderedAscending default: return .OrderedDescending } } else { switch nOther { case NSCalendarUnit.CalendarUnitYear, NSCalendarUnit.CalendarUnitMonth: return .OrderedDescending default: return .OrderedAscending } } } else { if nUnit.rawValue > nOther.rawValue { return .OrderedAscending } else if (nUnit.rawValue < nOther.rawValue) { return .OrderedDescending } else { return .OrderedSame } } } private func _sdNormalizedCalendarUnit(unit:NSCalendarUnit) -> NSCalendarUnit { switch unit { case NSCalendarUnit.CalendarUnitWeekOfMonth, NSCalendarUnit.CalendarUnitWeekOfYear: return NSCalendarUnit.CalendarUnitWeekOfYear case NSCalendarUnit.CalendarUnitWeekday, NSCalendarUnit.CalendarUnitWeekdayOrdinal: return NSCalendarUnit.CalendarUnitDay default: return unit; } } func _sdLocalizeStringForValue(singular : Bool, unit: NSCalendarUnit, abbreviated: Bool = false) -> String { var toTranslate : String = "" switch unit { case NSCalendarUnit.CalendarUnitYear where singular: toTranslate = (abbreviated ? "yr" : "year") case NSCalendarUnit.CalendarUnitYear where !singular: toTranslate = (abbreviated ? "yrs" : "years") case NSCalendarUnit.CalendarUnitMonth where singular: toTranslate = (abbreviated ? "mo" : "month") case NSCalendarUnit.CalendarUnitMonth where !singular: toTranslate = (abbreviated ? "mos" : "months") case NSCalendarUnit.CalendarUnitWeekOfYear where singular: toTranslate = (abbreviated ? "wk" : "week") case NSCalendarUnit.CalendarUnitWeekOfYear where !singular: toTranslate = (abbreviated ? "wks" : "weeks") case NSCalendarUnit.CalendarUnitDay where singular: toTranslate = "day" case NSCalendarUnit.CalendarUnitDay where !singular: toTranslate = "days" case NSCalendarUnit.CalendarUnitHour where singular: toTranslate = (abbreviated ? "hr" : "hour") case NSCalendarUnit.CalendarUnitHour where !singular: toTranslate = (abbreviated ? "hrs" : "hours") case NSCalendarUnit.CalendarUnitMinute where singular: toTranslate = (abbreviated ? "min" : "minute") case NSCalendarUnit.CalendarUnitMinute where !singular: toTranslate = (abbreviated ? "mins" : "minutes") case NSCalendarUnit.CalendarUnitSecond where singular: toTranslate = (abbreviated ? "s" : "second") case NSCalendarUnit.CalendarUnitSecond where !singular: toTranslate = (abbreviated ? "s" : "seconds") default: toTranslate = "" } return toTranslate._sdLocalize } func localizedSimpleStringForComponents(components:NSDateComponents) -> String { if (components.year == -1) { return "last year"._sdLocalize } else if (components.month == -1 && components.year == 0) { return "last month"._sdLocalize } else if (components.weekOfYear == -1 && components.year == 0 && components.month == 0) { return "last week"._sdLocalize } else if (components.day == -1 && components.year == 0 && components.month == 0 && components.weekOfYear == 0) { return "yesterday"._sdLocalize } else if (components == 1) { return "next year"._sdLocalize } else if (components.month == 1 && components.year == 0) { return "next month"._sdLocalize } else if (components.weekOfYear == 1 && components.year == 0 && components.month == 0) { return "next week"._sdLocalize } else if (components.day == 1 && components.year == 0 && components.month == 0 && components.weekOfYear == 0) { return "tomorrow"._sdLocalize } return "" } } //MARK: OPERATIONS WITH DATES (==,!=,<,>,<=,>=) extension NSDate : Comparable, Equatable {} public func == (left: NSDate, right: NSDate) -> Bool { return (left.compare(right) == NSComparisonResult.OrderedSame) } public func != (left: NSDate, right: NSDate) -> Bool { return !(left == right) } public func < (left: NSDate, right: NSDate) -> Bool { return (left.compare(right) == NSComparisonResult.OrderedAscending) } public func > (left: NSDate, right: NSDate) -> Bool { return (left.compare(right) == NSComparisonResult.OrderedDescending) } public func <= (left: NSDate, right: NSDate) -> Bool { return !(left > right) } public func >= (left: NSDate, right: NSDate) -> Bool { return !(left < right) } //MARK: ARITHMETIC OPERATIONS WITH DATES (-,-=,+,+=) public func - (left : NSDate, right: NSTimeInterval) -> NSDate { return left.dateByAddingTimeInterval(-right) } public func -= (inout left: NSDate, right: NSTimeInterval) { left = left.dateByAddingTimeInterval(-right) } public func + (left: NSDate, right: NSTimeInterval) -> NSDate { return left.dateByAddingTimeInterval(right) } public func += (inout left: NSDate, right: NSTimeInterval) { left = left.dateByAddingTimeInterval(right) } public func - (left: NSDate, right: CalendarType) -> NSDate { let calendarType = right.copy() calendarType.amount = -calendarType.amount let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let dateComponents = calendarType.dateComponents() let finalDate = calendar.dateByAddingComponents(dateComponents, toDate: left, options: NSCalendarOptions.allZeros)! return finalDate } public func -= (inout left: NSDate, right: CalendarType) { left = left - right } public func + (left: NSDate, right: CalendarType) -> NSDate { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! return calendar.dateByAddingComponents(right.dateComponents(), toDate: left, options: NSCalendarOptions.allZeros)! } public func += (inout left: NSDate, right: CalendarType) { left = left + right } //MARK: SUPPORTING STRUCTURES public class CalendarType { var calendarUnit : NSCalendarUnit var amount : Int init(amount : Int) { self.calendarUnit = NSCalendarUnit.allZeros self.amount = amount } init(amount: Int, calendarUnit: NSCalendarUnit) { self.calendarUnit = calendarUnit self.amount = amount } func dateComponents() -> NSDateComponents { return NSDateComponents() } func copy() -> CalendarType { return CalendarType(amount: self.amount, calendarUnit: self.calendarUnit) } } public class MonthCalendarType : CalendarType { override init(amount : Int) { super.init(amount: amount) self.calendarUnit = NSCalendarUnit.CalendarUnitMonth } override func dateComponents() -> NSDateComponents { let components = super.dateComponents() components.month = self.amount return components } override func copy() -> MonthCalendarType { let objCopy = MonthCalendarType(amount: self.amount) objCopy.calendarUnit = self.calendarUnit return objCopy; } } public class YearCalendarType : CalendarType { override init(amount : Int) { super.init(amount: amount, calendarUnit: NSCalendarUnit.CalendarUnitYear) } override func dateComponents() -> NSDateComponents { let components = super.dateComponents() components.year = self.amount return components } override func copy() -> YearCalendarType { let objCopy = YearCalendarType(amount: self.amount) objCopy.calendarUnit = self.calendarUnit return objCopy } } public extension Int { var seconds : NSTimeInterval { return NSTimeInterval(self) } var second : NSTimeInterval { return (self.seconds) } var minutes : NSTimeInterval { return (self.seconds*60) } var minute : NSTimeInterval { return self.minutes } var hours : NSTimeInterval { return (self.minutes*60) } var hour : NSTimeInterval { return self.hours } var days : NSTimeInterval { return (self.hours*24) } var day : NSTimeInterval { return self.days } var weeks : NSTimeInterval { return (self.days*7) } var week : NSTimeInterval { return self.weeks } var workWeeks : NSTimeInterval { return (self.days*5) } var workWeek : NSTimeInterval { return self.workWeeks } var months : MonthCalendarType { return MonthCalendarType(amount: self) } var month : MonthCalendarType { return self.months } var years : YearCalendarType { return YearCalendarType(amount: self) } var year : YearCalendarType { return self.years } } //MARK: PRIVATE STRING EXTENSION private extension String { var _sdLocalize: String { return NSBundle.mainBundle().localizedStringForKey(self, value: nil, table: "SwiftDates") } func _sdToCalendarUnit() -> NSCalendarUnit { switch self { case "year": return NSCalendarUnit.CalendarUnitYear case "month": return NSCalendarUnit.CalendarUnitMonth case "weekOfYear": return NSCalendarUnit.CalendarUnitWeekOfYear case "day": return NSCalendarUnit.CalendarUnitDay case "hour": return NSCalendarUnit.CalendarUnitHour case "minute": return NSCalendarUnit.CalendarUnitMinute case "second": return NSCalendarUnit.CalendarUnitSecond default: return nil } } } public enum DateFormat { case ISO8601, RSS, AltRSS case Custom(String) } let D_SECOND = 1 let D_MINUTE = 60 let D_HOUR = 3600 let D_DAY = 86400 let D_WEEK = 604800 let D_YEAR = 31556926
mit
eabb3358063a6b6694e8b0e7ec0e0bd6
31.608078
145
0.722068
3.813927
false
false
false
false
diejmon/SwiftyImageIO
Sources/GIF.swift
1
4044
#if canImport(UIKit) import Foundation import UIKit import MobileCoreServices import ImageIO public final class GIF { /// Errors for UIImage.makeGIF(atPath:) /// /// - InvalidPath: path parameter is incorrect file path /// - NotAnimatedImage: target image isn't animated image /// - InvalidImage: images do not have cgImage propery. CIImage backed UIImage not supported. Convert to CGImage first public enum MakeError: Error { case invalidPath case notAnimatedImage case invalidImage case imageIOError } public struct FrameProperties { var delayTime: TimeInterval? var imageColorMap: Data? // TODO: Wrap color maps var unclampedDelayTime: TimeInterval? public init(delayTime: TimeInterval? = nil, imageColorMap: Data? = nil, unclampedDelayTime: TimeInterval? = nil) { self.delayTime = delayTime self.imageColorMap = imageColorMap self.unclampedDelayTime = unclampedDelayTime } } public struct Properties { var loopCount: Int? var hasGlobalColorMap: Bool? public init(loopCount: Int? = nil, hasGlobalColorMap: Bool? = nil) { self.loopCount = loopCount self.hasGlobalColorMap = hasGlobalColorMap } } public init() { } public func makeGIF(fromAnimatedImage animatedImage: UIImage, writeTo path: String, properties: Properties? = nil, frameProperties: FrameProperties? = nil) throws { guard let images = animatedImage.images else { throw MakeError.notAnimatedImage } guard let imageDestination = ImageDestination(url: URL(fileURLWithPath: path), UTI: UTI(kUTTypeGIF), imageCount: images.count) else { throw MakeError.invalidPath } if let properties = properties { var imageDestinationProperties = ImageDestination.Properties() imageDestinationProperties.imageProperties = [properties] imageDestination.setProperties(imageDestinationProperties) } for image in images { guard let cgImage = image.cgImage else { throw MakeError.invalidImage } var frameImageDestinationProperties = ImageDestination.Properties() if let frameProperties = frameProperties { frameImageDestinationProperties.imageProperties = [frameProperties] } imageDestination.addImage(cgImage, properties: frameImageDestinationProperties) } let gifSaved = imageDestination.finalize() guard gifSaved else { throw MakeError.imageIOError } } } extension GIF.Properties: ImageProperties { public static var imageIOKey: CFString { return kCGImagePropertyGIFDictionary } public var cfValues: CFValues { return [ kCGImagePropertyGIFLoopCount: loopCount, kCGImagePropertyGIFHasGlobalColorMap: hasGlobalColorMap, ] } public init(_ cfValues: RawCFValues) { if let loopCount = cfValues[kCGImagePropertyGIFLoopCount] as? NSNumber { self.loopCount = loopCount.intValue } if let hasGlobalColorMap = cfValues[kCGImagePropertyGIFHasGlobalColorMap] as? NSNumber { self.hasGlobalColorMap = hasGlobalColorMap.boolValue } } } extension GIF.FrameProperties: ImageProperties { public static var imageIOKey: CFString { return kCGImagePropertyGIFDictionary } public var cfValues: CFValues { return [ kCGImagePropertyGIFDelayTime: delayTime, kCGImagePropertyGIFImageColorMap: imageColorMap, kCGImagePropertyGIFUnclampedDelayTime: unclampedDelayTime, ] } public init(_ cfValues: RawCFValues) { if let delayTime = cfValues[kCGImagePropertyGIFDelayTime] as? NSNumber { self.delayTime = delayTime.doubleValue } } } #endif
mit
c75f3137648783706f3bfa06ac526d9e
29.636364
126
0.655045
5.158163
false
false
false
false
duliodenis/blocstagram2
Blocstagram/Blocstagram/Services/AuthService.swift
1
3177
// // AuthService.swift // Blocstagram // // Created by ddenis on 1/10/17. // Copyright © 2017 ddApps. All rights reserved. // import UIKit import FirebaseAuth import FirebaseStorage import Firebase class AuthService { static func signIn(email: String, password: String, onSuccess: @escaping () -> Void, onError: @escaping (_ errorMessage: String?) -> Void) { // Use Firebase Authentication with email and password FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in if error != nil { onError("Authentication Error: \(error!.localizedDescription)") return } onSuccess() }) } static func signUp(username: String, email: String, password: String, imageData: Data, onSuccess: @escaping () -> Void, onError: @escaping (_ errorMessage: String?) -> Void) { // create a Firebase user FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user:FIRUser?, error: Error?) in if error != nil { onError("Create User Error: \(error!.localizedDescription)") return } let uid = user?.uid // get a reference to our file store let storeRef = FIRStorage.storage().reference(forURL: Constants.fileStoreURL).child("profile_image").child(uid!) storeRef.put(imageData, metadata: nil, completion: { (metaData, error) in if error != nil { print("Profile Image Error: \(error?.localizedDescription)") return } // if there's no error // get the URL of the profile image in the file store let profileImageURL = metaData?.downloadURL()?.absoluteString // set the user information with the profile image URL self.setUserInformation(profileImageURL: profileImageURL!, username: username, email: email, uid: uid!, onSuccess: onSuccess) }) }) } static func signOut(onSuccess: @escaping () -> Void, onError: @escaping (_ errorMessage: String?) -> Void) { // Log out user from Firebase do { try FIRAuth.auth()?.signOut() onSuccess() } catch let signOutError { onError(signOutError.localizedDescription) } } // MARK: - Firebase Saving Methods static func setUserInformation(profileImageURL: String, username: String, email: String, uid: String, onSuccess: @escaping () -> Void) { // create the new user in the user node and store username, email, and profile image URL let ref = FIRDatabase.database().reference() let userReference = ref.child("users") let newUserReference = userReference.child(uid) newUserReference.setValue(["username": username, "email": email, "profileImageURL": profileImageURL]) onSuccess() } }
mit
23874e9d9847685386bafaac35cee254
37.26506
179
0.573363
5.258278
false
false
false
false
feighter09/Cloud9
Pods/Bond/Bond/Bond+UIActivityIndicatorView.swift
4
2159
// // Bond+UIActivityIndicatorView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit private var animatingDynamicHandleUIActivityIndicatorView: UInt8 = 0; extension UIActivityIndicatorView: Bondable { public var dynIsAnimating: Dynamic<Bool> { if let d: AnyObject = objc_getAssociatedObject(self, &animatingDynamicHandleUIActivityIndicatorView) { return (d as? Dynamic<Bool>)! } else { let d = InternalDynamic<Bool>(self.isAnimating()) let bond = Bond<Bool>() { [weak self] v in if let s = self { if v { s.startAnimating() } else { s.stopAnimating() } } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &animatingDynamicHandleUIActivityIndicatorView, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var designatedBond: Bond<Bool> { return self.dynIsAnimating.designatedBond } }
lgpl-3.0
187204becf9cee937886b367bc03d2aa
36.224138
145
0.705419
4.397149
false
false
false
false
fabiomassimo/eidolon
Kiosk/Bid Fulfillment/PlaceBidViewController.swift
1
9749
import UIKit import Artsy_UILabels import ReactiveCocoa import Swift_RAC_Macros import Artsy_UIButtons import Artsy_UILabels import ORStackView public class PlaceBidViewController: UIViewController { public dynamic var bidDollars: Int = 0 public var hasAlreadyPlacedABid: Bool = false @IBOutlet public var bidAmountTextField: TextField! @IBOutlet public var cursor: CursorView! @IBOutlet public var keypadContainer: KeypadContainerView! @IBOutlet public var currentBidTitleLabel: UILabel! @IBOutlet public var yourBidTitleLabel: UILabel! @IBOutlet public var currentBidAmountLabel: UILabel! @IBOutlet public var nextBidAmountLabel: UILabel! @IBOutlet public var artworkImageView: UIImageView! @IBOutlet weak var detailsStackView: ORTagBasedAutoStackView! @IBOutlet public var bidButton: Button! @IBOutlet weak var conditionsOfSaleButton: UIButton! @IBOutlet weak var privacyPolictyButton: UIButton! public var showBuyersPremiumCommand = { () -> RACCommand in appDelegate().showBuyersPremiumCommand() } var showPrivacyPolicyCommand = { () -> RACCommand in appDelegate().showPrivacyPolicyCommand() } var showConditionsOfSaleCommand = { () -> RACCommand in appDelegate().showConditionsOfSaleCommand() } public lazy var bidDollarsSignal: RACSignal = { self.keypadContainer.intValueSignal }() public var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium } class public func instantiateFromStoryboard(storyboard: UIStoryboard) -> PlaceBidViewController { return storyboard.viewControllerWithID(.PlaceYourBid) as! PlaceBidViewController } override public func viewDidLoad() { super.viewDidLoad() if !hasAlreadyPlacedABid { self.fulfillmentNav().reset() } currentBidTitleLabel.font = UIFont.serifSemiBoldFontWithSize(17) yourBidTitleLabel.font = UIFont.serifSemiBoldFontWithSize(17) conditionsOfSaleButton.rac_command = showConditionsOfSaleCommand() privacyPolictyButton.rac_command = showPrivacyPolicyCommand() RAC(self, "bidDollars") <~ bidDollarsSignal RAC(bidAmountTextField, "text") <~ bidDollarsSignal.map(dollarsToCurrencyString) if let nav = self.navigationController as? FulfillmentNavigationController { RAC(nav.bidDetails, "bidAmountCents") <~ bidDollarsSignal.map { $0 as! Float * 100 }.takeUntil(viewWillDisappearSignal()) if let saleArtwork = nav.bidDetails.saleArtwork { let minimumNextBidSignal = RACObserve(saleArtwork, "minimumNextBidCents") let bidCountSignal = RACObserve(saleArtwork, "bidCount") let openingBidSignal = RACObserve(saleArtwork, "openingBidCents") let highestBidSignal = RACObserve(saleArtwork, "highestBidCents") RAC(currentBidTitleLabel, "text") <~ bidCountSignal.map(toCurrentBidTitleString) RAC(nextBidAmountLabel, "text") <~ minimumNextBidSignal.map(toNextBidString) RAC(currentBidAmountLabel, "text") <~ RACSignal.combineLatest([bidCountSignal, highestBidSignal, openingBidSignal]).map { let tuple = $0 as! RACTuple let bidCount = tuple.first as? Int ?? 0 return (bidCount > 0 ? tuple.second : tuple.third) ?? 0 }.map(centsToPresentableDollarsString).takeUntil(viewWillDisappearSignal()) RAC(bidButton, "enabled") <~ RACSignal.combineLatest([bidDollarsSignal, minimumNextBidSignal]).map { let tuple = $0 as! RACTuple return (tuple.first as? Int ?? 0) * 100 >= (tuple.second as? Int ?? 0) } enum LabelTags: Int { case LotNumber = 1 case ArtistName case ArtworkTitle case ArtworkPrice case BuyersPremium case Gobbler } let lotNumber = nav.bidDetails.saleArtwork?.lotNumber if let lotNumber = lotNumber { let lotNumberLabel = smallSansSerifLabel() lotNumberLabel.tag = LabelTags.LotNumber.rawValue detailsStackView.addSubview(lotNumberLabel, withTopMargin: "10", sideMargin: "0") RAC(lotNumberLabel, "text") <~ saleArtwork.lotNumberSignal.takeUntil(viewWillDisappearSignal()) } let artistNameLabel = sansSerifLabel() artistNameLabel.tag = LabelTags.ArtistName.rawValue detailsStackView.addSubview(artistNameLabel, withTopMargin: "15", sideMargin: "0") let artworkTitleLabel = serifLabel() artworkTitleLabel.tag = LabelTags.ArtworkTitle.rawValue detailsStackView.addSubview(artworkTitleLabel, withTopMargin: "15", sideMargin: "0") let artworkPriceLabel = serifLabel() artworkPriceLabel.tag = LabelTags.ArtworkPrice.rawValue detailsStackView.addSubview(artworkPriceLabel, withTopMargin: "15", sideMargin: "0") if let _ = buyersPremium() { let buyersPremiumView = UIView() buyersPremiumView.tag = LabelTags.BuyersPremium.rawValue let buyersPremiumLabel = ARSerifLabel() buyersPremiumLabel.font = buyersPremiumLabel.font.fontWithSize(16) buyersPremiumLabel.text = "This work has a " buyersPremiumLabel.textColor = UIColor.artsyHeavyGrey() let buyersPremiumButton = ARUnderlineButton() buyersPremiumButton.titleLabel?.font = buyersPremiumLabel.font buyersPremiumButton.setTitle("buyers premium", forState: .Normal) buyersPremiumButton.setTitleColor(UIColor.artsyHeavyGrey(), forState: .Normal) buyersPremiumButton.rac_command = showBuyersPremiumCommand() buyersPremiumView.addSubview(buyersPremiumLabel) buyersPremiumView.addSubview(buyersPremiumButton) buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: buyersPremiumView) buyersPremiumLabel.alignBaselineWithView(buyersPremiumButton, predicate: nil) buyersPremiumButton.alignAttribute(.Left, toAttribute: .Right, ofView: buyersPremiumLabel, predicate: "0") detailsStackView.addSubview(buyersPremiumView, withTopMargin: "15", sideMargin: "0") } let gobbler = WhitespaceGobbler() gobbler.tag = LabelTags.Gobbler.rawValue detailsStackView.addSubview(gobbler, withTopMargin: "0") if let artist = saleArtwork.artwork.artists?.first { RAC(artistNameLabel, "text") <~ RACObserve(artist, "name") } RAC(artworkTitleLabel, "attributedText") <~ RACObserve(saleArtwork.artwork, "titleAndDate").takeUntil(rac_willDeallocSignal()) RAC(artworkPriceLabel, "text") <~ RACObserve(saleArtwork.artwork, "price").takeUntil(viewWillDisappearSignal()) RACObserve(saleArtwork, "artwork").subscribeNext { [weak self] (artwork) -> Void in if let url = (artwork as? Artwork)?.defaultImage?.thumbnailURL() { self?.artworkImageView.sd_setImageWithURL(url) } else { self?.artworkImageView.image = nil } } } } } @IBAction func bidButtonTapped(sender: AnyObject) { let identifier = hasAlreadyPlacedABid ? SegueIdentifier.PlaceAnotherBid : SegueIdentifier.ConfirmBid performSegue(identifier) } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .PlaceAnotherBid { let nextViewController = segue.destinationViewController as! LoadingViewController nextViewController.placingBid = true } } } private extension PlaceBidViewController { func smallSansSerifLabel() -> UILabel { let label = sansSerifLabel() label.font = label.font.fontWithSize(12) return label } func sansSerifLabel() -> UILabel { let label = ARSansSerifLabel() label.numberOfLines = 1 return label } func serifLabel() -> UILabel { let label = ARSerifLabel() label.numberOfLines = 1 label.font = label.font.fontWithSize(16) return label } } /// These are for RAC only private extension PlaceBidViewController { func dollarsToCurrencyString(input: AnyObject!) -> AnyObject! { let dollars = input as! Int if dollars == 0 { return "" } let formatter = NSNumberFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US") formatter.numberStyle = .DecimalStyle return formatter.stringFromNumber(dollars) } func toCurrentBidTitleString(input: AnyObject!) -> AnyObject! { if let count = input as? Int { return count > 0 ? "Current Bid:" : "Opening Bid:" } else { return "" } } func toNextBidString(cents: AnyObject!) -> AnyObject! { if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) { return "Enter \(dollars) or more" } return "" } }
mit
17ded2876ce0eee140ef2892acd61676
41.021552
142
0.631449
5.532917
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Dynamic Programming/256_Paint House.swift
1
2204
// 256_Paint House // https://leetcode.com/problems/paint-house/ // // Created by Honghao Zhang on 10/18/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // //The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses. // //Note: //All costs are positive integers. // //Example: // //Input: [[17,2,17],[16,16,5],[14,3,19]] //Output: 10 //Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. // Minimum cost: 2 + 5 + 3 = 10. // // 房子涂颜色,有三种不同价格颜色,相邻的两个房子不能涂同样的颜色 // 求最小cost import Foundation class Num256 { // MARK: - DP // state是在i房子涂不同颜色的min cost, // 转移方程,根据涂的不同颜色,结合之前i-1个房子min cost,推导下一个min cost // 经验:这里state可以简化为三个数字,这样可以节省空间 func minCost(_ costs: [[Int]]) -> Int { let n = costs.count guard n > 0 else { return 0 } // state // s[i][0...2]: the min cost for choose different colors at index i var s: [[Int]] = Array(repeating: Array(repeating: 0, count: 3), count: n) // initialize s[0][0] = costs[0][0]//min(costs[0][1], costs[0][2]) s[0][1] = costs[0][1]//min(costs[0][0], costs[0][2]) s[0][2] = costs[0][2]//min(costs[0][0], costs[0][1]) // transition function for i in 1..<n { // i choose 0, find the min of s[i - 1][1] and s[i - 1][2] s[i][0] = costs[i][0] + min(s[i - 1][1], s[i - 1][2]) s[i][1] = costs[i][1] + min(s[i - 1][0], s[i - 1][2]) s[i][2] = costs[i][2] + min(s[i - 1][0], s[i - 1][1]) } // answer return s[n - 1].min()! } }
mit
ce8fa21fa231ef841baa16f625409821
33.118644
284
0.611525
2.831224
false
false
false
false
airspeedswift/swift
test/IRGen/objc_class_export.swift
2
6062
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK-DAG: %swift.refcounted = type // CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK-DAG: [[INT:%TSi]] = type <{ i64 }> // CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }> // CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }> // CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }> // CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK-SAME: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = internal constant {{.*\*}} } { // CHECK-SAME: i32 129, // CHECK-SAME: i32 40, // CHECK-SAME: i32 40, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = internal constant {{.*\*}} } { // CHECK-SAME: i32 128, // CHECK-SAME: i32 16, // CHECK-SAME: i32 24, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: @_IVARS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: _PROPERTIES__TtC17objc_class_export3Foo // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*}} }> <{ // CHECK-SAME: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD", // CHECK-SAME: i8** @"$sBOWV", // CHECK-SAME: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK-SAME: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 {{1|2}}), // CHECK-SAME: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ", // CHECK-SAME: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF" // CHECK-SAME: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN" import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { @objc var x = 0 @objc class func create() -> Foo { return Foo() } @objc func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]* %0, i8* %1, [[NSRECT]]* byval align 8 %2) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @objc func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE4:%.*]]* %1, i8* %2) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]]) @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE5:%.*]]* %1, i8* %2, [[NSRECT]]* byval align 8 %3) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo" func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_ @objc init() { } }
apache-2.0
5dc4f58d9ec2b6135b4eca048a82a6d8
51.258621
219
0.638073
3.052367
false
false
false
false
RiBj1993/CodeRoute
DemoExpandingCollection/AppDelegate.swift
1
1456
// // AppDelegate.swift // DemoExpandingCollection // // Created by Alex K. on 25/05/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { configureNavigationTabBar() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } } extension AppDelegate { fileprivate func configureNavigationTabBar() { //transparent background UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().isTranslucent = true let shadow = NSShadow() shadow.shadowOffset = CGSize(width: 0, height: 2) shadow.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1) UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.white, NSShadowAttributeName: shadow ] } }
apache-2.0
07726414ca8deffca27ee318cfc1e57e
24.526316
142
0.725773
5.271739
false
false
false
false
makezwl/zhao
Nimble/Matchers/BeGreaterThan.swift
80
1564
import Foundation /// A Nimble matcher that succeeds when the actual value is greater than the expected value. public func beGreaterThan<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" return actualExpression.evaluate() > expectedValue } } /// A Nimble matcher that succeeds when the actual value is greater than the expected value. public func beGreaterThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" let actualValue = actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending return matches } } public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThan(rhs)) } public func >(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) { lhs.to(beGreaterThan(rhs)) } extension NMBObjCMatcher { public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in let expr = actualExpression.cast { $0 as NMBComparable? } return beGreaterThan(expected).matches(expr, failureMessage: failureMessage) } } }
apache-2.0
493c721bf65105ecd9039295741f4d69
41.27027
123
0.730818
5.319728
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TalkPageCoffeeRollView.swift
1
3969
import UIKit final class TalkPageCoffeeRollView: SetupView { // MARK: - Properties var theme: Theme var viewModel: TalkPageCoffeeRollViewModel weak var linkDelegate: TalkPageTextViewLinkHandling? // MARK: - UI Elements lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: .zero) scrollView.translatesAutoresizingMaskIntoConstraints = false return scrollView }() lazy var textView: UITextView = { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false textView.isEditable = false textView.textContainerInset = .zero textView.textContainer.lineFragmentPadding = 0 textView.setContentCompressionResistancePriority(.required, for: .vertical) textView.setContentHuggingPriority(.required, for: .vertical) textView.delegate = self return textView }() // MARK: - Lifecycle required init(theme: Theme, viewModel: TalkPageCoffeeRollViewModel, frame: CGRect) { self.theme = theme self.viewModel = viewModel super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setup() { addSubview(scrollView) scrollView.addSubview(textView) NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: topAnchor), scrollView.bottomAnchor.constraint(equalTo: bottomAnchor), scrollView.leadingAnchor.constraint(equalTo: leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: trailingAnchor), textView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16), textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -16), textView.leadingAnchor.constraint(equalTo: scrollView.readableContentGuide.leadingAnchor, constant: 16), textView.trailingAnchor.constraint(equalTo: scrollView.readableContentGuide.trailingAnchor, constant: -16), textView.widthAnchor.constraint(equalTo: scrollView.readableContentGuide.widthAnchor, constant: -32) ]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } // MARK: - Configure func configure(viewModel: TalkPageCoffeeRollViewModel) { self.viewModel = viewModel updateFonts() updateSemanticContentAttribute(viewModel.semanticContentAttribute) } private func updateFonts() { textView.attributedText = viewModel.coffeeRollText?.byAttributingHTML(with: .callout, boldWeight: .semibold, matching: traitCollection, color: theme.colors.primaryText, linkColor: theme.colors.link, handlingLists: true, handlingSuperSubscripts: true).removingInitialNewlineCharacters() } private func updateSemanticContentAttribute(_ semanticContentAttribute: UISemanticContentAttribute) { textView.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left } } extension TalkPageCoffeeRollView: Themeable { func apply(theme: Theme) { self.theme = theme backgroundColor = theme.colors.paperBackground textView.backgroundColor = theme.colors.paperBackground updateFonts() updateSemanticContentAttribute(viewModel.semanticContentAttribute) } } extension TalkPageCoffeeRollView: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { linkDelegate?.tappedLink(URL, sourceTextView: textView) return false } }
mit
635c4921d34e987ba86cbabc219d7b32
35.081818
293
0.707483
5.752174
false
false
false
false
MA806P/SwiftDemo
SwiftTestDemo/SwiftTestDemo/Protocols.swift
1
12262
// // Protocols.swift // SwiftTestDemo // // Created by MA806P on 2018/8/31. // Copyright © 2018年 myz. All rights reserved. // import Foundation /* protocol SomeProtocol { } struct SomeStructure: FirstProtocol, AnotherProtocol { } 父类名称需要写在协议名之前 class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { } */ //属性 //协议可以要求遵循协议的类型提供特定名称和实例属性或类型属性。 //协议只指定属性的名称和类型,而不指定属性为储存属性或计算属性。 /* 协议属性通常会以 var 关键字来声明变量属性。 在类型声明后加上 { get set } 来表示属性是可读可写的,用 { get } 来表示可读属性。 定义类型属性要求时,始终使用 static 关键字作为前缀。 */ protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } static var someTypeProperty: Int { get set } } /* FullyNamed 协议要求遵循协议的类型提供一个全名 Person 的每个实例都有一个名为 fullName 的存储属性,它的类型为 String。 这符合 FullyNamed 协议的单一要求,意味着 Person 已正确遵循该协议 */ protocol FullyNamed { var fullName: String { get } } struct Person12: FullyNamed { var fullName: String } //let john = Person(fullName: "John Appleseed") // john.fullName 是 "John Appleseed" //方法 //协议可能需要通过遵循类型来实现特定的实例方法和类型方法。 protocol RandomNumberGenerator { func random() -> Double } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m)) return lastRandom / m } } //let generator = LinearCongruentialGenerator() //print("Here's a random number: \(generator.random())") //// 打印 "Here's a random number: 0.3746499199817101" //print("And another one: \(generator.random())") //// 打印 "And another one: 0.729023776863283" /* 有时需要有一个方法来修改(或 异变)它所属的实例。例如,对值类型(即结构体和枚举)的方法, 将 mutating 关键字放在方法 func 关键字之前, 以指示允许该方法修改它所属的实例以及该实例的任何属性。 如果将协议实例方法要求标记为 mutating,则在为类编写该方法的实现时, 不需要写 mutating 关键字。mutating 关键字仅由结构体和枚举使用。 */ protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case off, on mutating func toggle() { switch self { case .off: self = .on case .on: self = .off } } } //var lightSwitch = OnOffSwitch.off //lightSwitch.toggle() //// lightSwitch 现在是 .on //协议可能要求通过遵循类型来实现特定的构造器。 protocol SomeProtocol11 { init(someParameter: Int) } class SomeClass11: SomeProtocol11 { //你可以通过实现指定构造器或便利构造器来使遵循协议的类满足协议的构造器要求。 //在这两种情况下,你必须使用 required 修饰符标记构造器实现: required init(someParameter: Int) { // 下面是构造器的实现 } //使用 required 修饰符可确保你在遵循协议类的所有子类上提供构造器要求的 //显式或继承实现,以便它们也符合协议。 } //你并不需要在使用 final 修饰符标记的类上使用 required 修饰符来标记协议构造器的实现, //因为这样的类是不能进行子类化。 protocol SomeProtocol12 { init() } class SomeSuperClass12 { init() { // 下面是构造器的实现 } } class SomeSubClass12: SomeSuperClass12, SomeProtocol12 { // 添加「required」修饰符是因为遵循了 SomeProtocol 协议; //添加「override」修饰符是因为该类继承自 SomeSuperClass required override init() { // 下面是构造器的实现 } } //将协议作为类型 /* 创建的任何协议都可以变为一个功能完备的类型在代码中使用 作为函数、方法或构造器的参数类型或返回类型 作为常量、变量或属性的类型 作为数组、字典或其他容器的元素类型 */ class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } /* 委托 是一种设计模式,它使类或结构体能够将其某些职责交给(或 委托)到另一种类型的实例。 通过定义封装委托职责的协议来实现此设计模式,从而保证遵循协议类型(称为委托)提供被委托的功能。 委托可用于响应特定操作,或从外部源检索数据,而无需了解该源的具体类型。 */ //让扩展添加协议遵循 /* 可以通过扩展这个已存在的类型并让它遵循并实现一个新的协议。扩展可以为已存在的类型添加新属性,方法和下标 */ protocol TextRepresentable { var textualDescription: String { get } } extension Dice: TextRepresentable { var textualDescription: String { return "A \(sides)-sided dice" } } //extension Dice: TextRepresentable { // var textualDescription: String { // return "A \(sides)-sided dice" // } //} //有条件地遵循协议 /* 泛型类型可能只能在特定条件下满足协议的要求,例如类的泛型参数遵循一个协议。 你可以通过在扩展类型时列出条件约束,让泛型类型有条件的遵循一个协议。 通过编写一个泛型 where 分句,在遵循的协议名称后面写上约束条件。 */ extension Array: TextRepresentable where Element: TextRepresentable { var textualDescription: String { let itemsAsText = self.map { $0.textualDescription } return "[" + itemsAsText.joined(separator: ", ") + "]" } } //let myDice = [d6, d12] //print(myDice.textualDescription) //// "[A 6-sided dice, A 12-sided dice]" //通过扩展申明采纳协议 /* 如果一个类型已经满足遵循一个协议的所有要求,但它没有申明遵循了这个协议,你可以通过一个空的扩展遵循该协议 */ struct Hamster { var name: String var textualDescription: String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} //协议可以用作诸如数组或字典之类的集合类型的元素类型 //let things: [TextRepresentable] = [game, d12, simonTheHamster] //for thing in things { print(thing.textualDescription) } //协议可以 继承 一个或多个协议,并且可以在其继承的协议的基础上添加更多的要求。 //协议继承的语法类似于类继承的语法,但是协议继承支持同时继承多个协议,并用逗号隔开: //protocol InheritingProtocol: SomeProtocol, AnotherProtocol { } //类专属协议 //你可以通过将 AnyObject 协议添加到协议的继承列表,来将协议限定为仅类类型(而不是结构体或枚举)可用。 //protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol { } //SomeClassOnlyProtocol 只能被类类型遵循。 如果尝试编写遵循 SomeClassOnlyProtocol 协议的结构体或枚举,会出现编译时错误。 //协议组合 protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person34: Named, Aged { var name: String var age: Int } //func wishHappyBirthday(to celebrator: Named & Aged) { // print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!") //} //let birthdayPerson = Person34(name: "Malcolm", age: 21) //wishHappyBirthday(to: birthdayPerson) //// "Happy birthday, Malcolm, you're 21!" //wishHappyBirthday 参数的类型是 Named & Aged,这意味着「任何同时遵循 Named 和 Aged 协议的类型。」 //只要遵循这两个协议,将具体什么类型传递给函数并不重要。 //协议遵循的检查 /* 可以使用 类型转换 中描述的 is 和 as 运算符来检查协议遵循,和转换成特定协议。 如果实例遵循协议,则 is 运算符返回 true,如果不遵循则返回 false。 向下转换运算符的 as? 返回协议类型的可选值,如果实例不遵循该协议,则该值为 nil。 向下转换运算符的 as! 强制向下转换为协议类型,如果向下转换不成功则触发运行时错误。 */ //可选协议要求 /* 你可以为协议定义 可选要求,这些要求不强制遵循类型的实现。可选要求以 optional 修饰符为前缀,作为协议定义的一部分。 可选要求允许你的代码与 Objective-C 交互。协议和可选要求都必须用 @objc 属性标记。 请注意,@objc 协议只能由继承自 Objective-C 类或其他 @objc 类的类遵循。结构体或枚举不能遵循它们。 考虑到遵循协议的类型可能未实现要求,你应该使用可选链来调用可选协议要求。 你通过在调用方法名称后面写一个问号来检查可选方法的实现,例如 someOptionalMethod?(someArgument)。 */ @objc protocol CounterDataSource { @objc optional func increment(forCount count: Int) -> Int @objc optional var fixedIncrement: Int { get } } class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.increment?(forCount: count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } } } class TowardsZeroSource: NSObject, CounterDataSource { func increment(forCount count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } //counter.count = -4 //counter.dataSource = TowardsZeroSource() //for _ in 1...5 { // counter.increment() // print(counter.count) //} //// -3 //// -2 //// -1 //// 0 //// 0 //协议扩展 /* 通过协议扩展,我们可以向符合协议的类型提供方法、构造器、下标和计算属性的实现。 这允许你基于协议本身来实现行为,而无需再让每个遵循协议的类型都重复实现,或是使用全局函数。 可以通过扩展 RandomNumberGenerator 协议来实现 randomBool() 方法,该方法使用 random() 的结果来返回一个随机的 Bool 值: extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } let generator = LinearCongruentialGenerator() print("Here's a random number: \(generator.random())") // 打印 "Here's a random number: 0.3746499199817101" print("And here's a random Boolean: \(generator.randomBool())") // 打印 "And here's a random Boolean: true" */ //提供默认实现 /* 可以使用协议扩展来为任何方法或计算属性提供默认实现。 如果一个符合的类型本身就实现了协议中要求的方法或属性,那么这个实现会代替协议扩展中的实现。 extension PrettyTextRepresentable { var prettyTextualDescription: String { return textualDescription } } */ //为协议扩展添加条件约束 //当我们定义一个协议扩展时,我们可以通过where关键字在被扩展的协议名称后指定一个任意类型在遵循协议前必须满足的约束条件。 //可以在Collection协议的扩展中指定集合中的所有元素必须先遵循Equatable这个协议。 //通过Equatable这个基础协议,我们便可以使用==或者!=操作符来检查任意两个元素是否相等。 extension Collection where Element: Equatable { func allEqual() -> Bool { for element in self { if element != self.first { return false } } return true } } //allEqual()这个方法只有当集合中的所有元素都相等时才会返回true
apache-2.0
160944c689d62700d324764ffe5033a5
19.685786
86
0.691501
3.035126
false
false
false
false
lucianomarisi/LoadIt
Sources/LoadIt/Operations/BaseOperation.swift
1
1681
// // BaseOperation.swift // LoadIt // // Created by Luciano Marisi on 25/06/2016. // Copyright © 2016 Luciano Marisi. All rights reserved. // import Foundation public class BaseOperation: NSOperation { public override var asynchronous: Bool { get{ return true } } private var _executing: Bool = false public override var executing:Bool { get { return _executing } set { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") if _cancelled == true { self.finished = true } } } private var _finished: Bool = false public override var finished: Bool { get { return _finished } set { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } private var _cancelled: Bool = false public override var cancelled: Bool { get { return _cancelled } set { willChangeValueForKey("isCancelled") _cancelled = newValue didChangeValueForKey("isCancelled") } } public final override func start() { super.start() self.executing = true } public final override func main() { if cancelled { executing = false finished = true return } execute() } public func execute() { assertionFailure("execute must overriden") finish() } public final func finish(errors: [NSError] = []) { self.finished = true self.executing = false } public final override func cancel() { super.cancel() cancelled = true if executing { executing = false finished = true } } }
mit
edb9fffa64927206eca314488f369b10
19.240964
57
0.623214
4.666667
false
false
false
false
swift102016team5/mefocus
MeFocus/Pods/HGCircularSlider/HGCircularSlider/Classes/CircularSlider.swift
1
8138
// // CircularSlider.swift // Pods // // Created by Hamza Ghazouani on 19/10/2016. // // import UIKit /** * A visual control used to select a single value from a continuous range of values. * Can also be used like a circular progress view * CircularSlider use the target-action mechanism to report changes made during the course of editing: * ValueChanged, EditingDidBegin and EditingDidEnd */ @IBDesignable open class CircularSlider: UIControl { // MARK: Changing the Slider’s Appearance /** * The color shown for the portion of the disk of slider that is filled. (between start and end values) * The default value is a transparent color. */ @IBInspectable open var diskFillColor: UIColor = UIColor.clear /** * The color shown for the portion of the disk of slider that is unfilled. (outside start and end values) * The default value of this property is the black color with alpha = 0.3. */ @IBInspectable open var diskColor: UIColor = UIColor.gray /** * The color shown for the portion of the slider that is filled. (between start and end values) * The default value of this property is the tint color. */ @IBInspectable open var trackFillColor: UIColor = UIColor.clear /** * The color shown for the portion of the slider that is unfilled. (outside start and end values) * The default value of this property is the white color. */ @IBInspectable open var trackColor: UIColor = UIColor.white /** * The width of the circular line * * The default value of this property is 5.0. */ @IBInspectable open var lineWidth: CGFloat = 5.0 /** * The width of the thumb stroke line * * The default value of this property is 4.0. */ @IBInspectable open var thumbLineWidth: CGFloat = 4.0 /** * The radius of thumb * * The default value of this property is 13.0. */ @IBInspectable open var thumbRadius: CGFloat = 13.0 /** * The color used to tint thumb * Ignored if the endThumbImage != nil * * The default value of this property is the groupTableViewBackgroundColor. */ @IBInspectable open var endThumbTintColor: UIColor = UIColor.groupTableViewBackground /** * The stroke highlighted color of end thumb * The default value of this property is blue color */ @IBInspectable open var endThumbStrokeHighlightedColor: UIColor = UIColor.blue /** * The color used to tint the stroke of the end thumb * Ignored if the endThumbImage != nil * * The default value of this property is the red color. */ @IBInspectable open var endThumbStrokeColor: UIColor = UIColor.red /** * The image of the end thumb * Clears any custom color you may have provided for end thumb. * * The default value of this property is nil */ open var endThumbImage: UIImage? // MARK: Accessing the Slider’s Value Limits /** * The minimum value of the receiver. * * If you change the value of this property, and the end value of the receiver is below the new minimum, the end point value is adjusted to match the new minimum value automatically. * The default value of this property is 0.0. */ @IBInspectable open var minimumValue: CGFloat = 0.0 { didSet { if endPointValue < minimumValue { endPointValue = minimumValue } } } /** * The maximum value of the receiver. * * If you change the value of this property, and the end value of the receiver is above the new maximum, the end value is adjusted to match the new maximum value automatically. * The default value of this property is 1.0. */ @IBInspectable open var maximumValue: CGFloat = 1.0 { didSet { if endPointValue > maximumValue { endPointValue = maximumValue } } } /** * The value of the endThumb (changed when the user change the position of the end thumb) * * If you try to set a value that is above the maximum value, the maximum value is set instead. * If you try to set a value that is below the minimum value, the minimum value is set instead. * * The default value of this property is 0.5 */ open var endPointValue: CGFloat = 0.5 { didSet { if oldValue == endPointValue { return } if endPointValue > maximumValue { endPointValue = maximumValue } setNeedsDisplay() } } /** * The radius of circle */ internal var radius: CGFloat { get { // the minimum between the height/2 and the width/2 var radius = min(bounds.center.x, bounds.center.y) // all elements should be inside the view rect, for that we should subtract the highest value between the radius of thumb and the line width radius -= max(lineWidth, (thumbRadius + thumbLineWidth)) return radius } } /// See superclass documentation override open var isHighlighted: Bool { didSet { setNeedsDisplay() } } // MARK: init methods /** See superclass documentation */ override public init(frame: CGRect) { super.init(frame: frame) setup() } /** See superclass documentation */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } internal func setup() { trackFillColor = tintColor } // MARK: Drawing methods /** See superclass documentation */ override open func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } drawCircularSlider(inContext: context) let valuesInterval = Interval(min: minimumValue, max: maximumValue) // get end angle from end value let endAngle = CircularSliderHelper.scaleToAngle(value: endPointValue, inInterval: valuesInterval) + CircularSliderHelper.circleInitialAngle drawFilledArc(fromAngle: CircularSliderHelper.circleInitialAngle, toAngle: endAngle, inContext: context) // draw end thumb endThumbTintColor.setFill() (isHighlighted == true) ? endThumbStrokeHighlightedColor.setStroke() : endThumbStrokeColor.setStroke() guard let image = endThumbImage else { drawThumb(withAngle: endAngle, inContext: context) return } drawThumb(withImage: image, angle: endAngle, inContext: context) } // MARK: User interaction methods /** See superclass documentation */ override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { sendActions(for: .editingDidBegin) return true } /** See superclass documentation */ override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { // the position of the pan gesture let touchPosition = touch.location(in: self) let startPoint = CGPoint(x: bounds.center.x, y: 0) let angle = CircularSliderHelper.angle(betweenFirstPoint: startPoint, secondPoint: touchPosition, inCircleWithCenter: bounds.center) let interval = Interval(min: minimumValue, max: maximumValue) let newValue = CircularSliderHelper.value(inInterval: interval, fromAngle: angle) endPointValue = newValue sendActions(for: .valueChanged) return true } /** See superclass documentation */ open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { sendActions(for: .editingDidEnd) } }
mit
59ec7ea9aac7821298b43c92f883deab
29.237918
186
0.617408
4.9507
false
false
false
false
yoonhg84/ModalPresenter
Example/RxModalityStackExample/ViewControllers/ImageVC.swift
1
1021
// // Created by Chope on 2018. 4. 18.. // Copyright (c) 2018 Chope Industry. All rights reserved. // import UIKit import RxModalityStack class ImageVC: TransparentToolViewController { var image: UIImage? private let imageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() view.insertSubview(imageView, at: 0) imageView.image = image } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() imageView.frame = view.bounds } } extension ImageVC: ModalPresentable { class func viewControllerOf(_ modal: Modal, with data: ModalData) -> (UIViewController & ModalityPresentable)? { switch (modal, data) { case (.image, .image(let image)): let vc = ImageVC() vc.image = image return vc default: return nil } } class func transitionOf(_ modal: Modal, with data: ModalData) -> ModalityTransition? { return .system } }
mit
e97a7e51863c902a3f9442c98de56a48
22.227273
116
0.623898
4.497797
false
false
false
false
polymr/polymyr-api
Sources/App/Stripe/Models/StripeCustomer.swift
1
2400
// // Customer.swift // Stripe // // Created by Hakon Hanesand on 12/2/16. // // import Node import Vapor import Foundation public final class StripeCustomer: NodeConvertible { static let type = "customer" public let id: String public let account_balance: Int public let created: Date public let currency: Currency? public let default_source: String public let delinquent: Bool public let metadata: Node public let description: String? public let discount: Discount? public let email: String? public let livemode: Bool public let sources: [Card] public let subscriptions: [StripeSubscription] public init(node: Node) throws { guard try node.extract("object") == StripeCustomer.type else { throw NodeError.unableToConvert(input: node, expectation: StripeCustomer.type, path: ["object"]) } id = try node.extract("id") account_balance = try node.extract("account_balance") created = try node.extract("created") currency = try? node.extract("currency") default_source = try node.extract("default_source") delinquent = try node.extract("delinquent") description = try? node.extract("description") discount = try? node.extract("discount") email = try? node.extract("email") livemode = try node.extract("livemode") sources = try node.extractList("sources") subscriptions = try node.extractList("subscriptions") metadata = try node.extract("metadata") } public func makeNode(in context: Context?) throws -> Node { return try Node(node: [ "id" : .string(id), "account_balance" : .number(.int(account_balance)), "created" : .number(.double(created.timeIntervalSince1970)), "default_source" : .string(default_source), "delinquent" : .bool(delinquent), "livemode" : .bool(livemode), "sources" : .array(sources.map { try $0.makeNode(in: context) }), "subscriptions" : .array(subscriptions.map { try $0.makeNode(in: context) }), "metadata" : metadata ] as [String : Node]).add(objects: [ "discount" : discount, "currency" : currency, "description" : description, "email" : email ]) } }
mit
fb3d9a46d7fea18ab65c0aee15979778
33.285714
108
0.608333
4.301075
false
false
false
false
BerrySang/BSCarouselFigureView
BSCarouselFigureView/ViewController.swift
1
1888
// // ViewController.swift // BSCarouselFigureView // // Created by Berry on 2017/1/7. // Copyright © 2017年 Berry. All rights reserved. // import UIKit class ViewController: UIViewController { /// 顶部轮播图 var carouselView = BSCarouselFigureView() /// 轮播图的图片链接 网络的 var imageViewAryStrs = [String]() /// 轮播图的图片点击详情链接 网络的 var imageViewDetailAryStrs = [String]() override func viewDidLoad() { super.viewDidLoad() setupHomeViewBaseUI() } /// 顶部轮播视图 fileprivate func setupHomeViewBaseUI() { // 设置轮播图 setupCarouselImageViewUI() } } extension ViewController: BSCarouselFigureViewDelegate { /// 设置滚动轮播视图 fileprivate func setupCarouselImageViewUI(){ let carlFrame = CGRect(x: 0, y: 20, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width*0.5) let carlView = BSCarouselFigureView(frame: carlFrame) //carouselView.backgroundColor = UIColor.blue carlView.delegate = self view.addSubview(carlView) carouselView = carlView carouselView.imageStrs = [ "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1070382435,4049757214&fm=23&gp=0.jpg", "http://img-cdn.d1ev.com/d/file/attachment/2017/01/58761ff1c7cda.jpg", "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2080316174,763532303&fm=23&gp=0.jpg", "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=222298094,2713061086&fm=23&gp=0.jpg"] carouselView.titles = ["0011 ","0022 ","0033 ", "0044 "] } public func carouselFigureView(carouselFigureView: BSCarouselFigureView, didSelectAt index: Int) { print("imageIndex: \(index)") } }
mit
5dfe5aaffd1a4f4425bf226dbe69d7d5
29.254237
128
0.656022
3.227848
false
false
false
false
Farteen/ios-charts
Charts/Classes/Charts/HorizontalBarChartView.swift
1
7328
// // HorizontalBarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched. public class HorizontalBarChartView: BarChartView { internal override func initialize() { super.initialize(); _leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler); _rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler); renderer = HorizontalBarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler); _leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer); _rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer); _xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self); } internal override func calculateOffsets() { var offsetLeft: CGFloat = 0.0, offsetRight: CGFloat = 0.0, offsetTop: CGFloat = 0.0, offsetBottom: CGFloat = 0.0; // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0; } else if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0; } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { var yOffset = _legend.textHeightMax * 2.0; // It's possible that we do not need this offset anymore as it is available through the extraOffsets offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent); } } // offsets for y-labels if (_leftAxis.needsOffset) { offsetTop += _leftAxis.getRequiredHeightSpace(); } if (_rightAxis.needsOffset) { offsetBottom += _rightAxis.getRequiredHeightSpace(); } var xlabelwidth = _xAxis.labelWidth; if (_xAxis.isEnabled) { // offsets for x-labels if (_xAxis.labelPosition == .Bottom) { offsetLeft += xlabelwidth; } else if (_xAxis.labelPosition == .Top) { offsetRight += xlabelwidth; } else if (_xAxis.labelPosition == .BothSided) { offsetLeft += xlabelwidth; offsetRight += xlabelwidth; } } offsetTop += self.extraTopOffset; offsetRight += self.extraRightOffset; offsetBottom += self.extraBottomOffset; offsetLeft += self.extraLeftOffset; var minOffset: CGFloat = 10.0; _viewPortHandler.restrainViewPort( offsetLeft: max(minOffset, offsetLeft), offsetTop: max(minOffset, offsetTop), offsetRight: max(minOffset, offsetRight), offsetBottom: max(minOffset, offsetBottom)); prepareOffsetMatrix(); prepareValuePxMatrix(); } internal override func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis.axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin); _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis.axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin); } internal override func calcModulus() { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d))); if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1; } } public override func getBarBounds(e: BarChartDataEntry) -> CGRect! { var set = _data.getDataSetForEntry(e) as! BarChartDataSet!; if (set === nil) { return nil; } var barspace = set.barSpace; var y = CGFloat(e.value); var x = CGFloat(e.xIndex); var spaceHalf = barspace / 2.0; var top = x - 0.5 + spaceHalf; var bottom = x + 0.5 - spaceHalf; var left = y >= 0.0 ? y : 0.0; var right = y <= 0.0 ? y : 0.0; var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top); getTransformer(set.axisDependency).rectValueToPixel(&bounds); return bounds; } public override func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex)); getTransformer(axis).pointValueToPixel(&vals); return vals; } public override func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } _leftAxisTransformer.pixelToValue(&pt); if (pt.y < CGFloat(_chartXMin) || pt.y > CGFloat(_chartXMax)) { return nil; } return getHighlight(xPosition: pt.y, yPosition: pt.x); } public override var lowestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0); } public override var highestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div)); } }
apache-2.0
3737d7f40f54cfa38a9ceaaea7ac5415
35.645
165
0.594569
5.142456
false
false
false
false
LoopKit/LoopKit
LoopKitUI/ViewModels/CorrectionRangeOverridesEditorViewModel.swift
1
1829
// // CorrectionRangeOverridesEditorViewModel.swift // LoopKitUI // // Created by Nathaniel Hamming on 2021-03-15. // Copyright © 2021 LoopKit Authors. All rights reserved. // import Foundation import HealthKit import LoopKit struct CorrectionRangeOverridesEditorViewModel { let correctionRangeOverrides: CorrectionRangeOverrides let suspendThreshold: GlucoseThreshold? let correctionRangeScheduleRange: ClosedRange<HKQuantity> let preset: CorrectionRangeOverrides.Preset let guardrail: Guardrail<HKQuantity> var saveCorrectionRangeOverride: (_ correctionRangeOverrides: CorrectionRangeOverrides) -> Void public init(therapySettingsViewModel: TherapySettingsViewModel, preset: CorrectionRangeOverrides.Preset, didSave: (() -> Void)? = nil) { self.correctionRangeOverrides = therapySettingsViewModel.correctionRangeOverrides self.suspendThreshold = therapySettingsViewModel.suspendThreshold self.correctionRangeScheduleRange = therapySettingsViewModel.correctionRangeScheduleRange self.guardrail = Guardrail.correctionRangeOverride( for: preset, correctionRangeScheduleRange: therapySettingsViewModel.correctionRangeScheduleRange, suspendThreshold: therapySettingsViewModel.suspendThreshold) self.preset = preset self.saveCorrectionRangeOverride = { [weak therapySettingsViewModel] correctionRangeOverrides in guard let therapySettingsViewModel = therapySettingsViewModel else { return } therapySettingsViewModel.saveCorrectionRangeOverride(preset: preset, correctionRangeOverrides: correctionRangeOverrides) didSave?() } } }
mit
197949010c33625464346f58ebd0f55e
36.306122
116
0.718818
5.7125
false
false
false
false
crewupinc/vapor-postgresql
Sources/VaporPostgreSQL/Update.swift
1
3679
// The MIT License (MIT) // // Copyright (c) 2016 Formbound // // 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. public protocol UpdateQuery: FilteredQuery, TableQuery { var valuesByField: [DeclaredField: SQLData?] { get set } } extension UpdateQuery { public var queryComponents: QueryComponents { var components = QueryComponents(components: [ "UPDATE", QueryComponents(tableName), "SET", valuesByField.map({ $0 }).queryComponentsForSettingValues(useQualifiedNames: false) ]) if let condition = condition { components.append("WHERE") components.append(condition.queryComponents) } return components } public mutating func set(_ value: SQLData?, forField field: DeclaredField) { valuesByField[field] = value } public mutating func set(_ value: SQLDataConvertible?, forField field: DeclaredField) { self.set(value?.sqlData, forField: field) } } public struct Update: UpdateQuery { public let tableName: String public var valuesByField: [DeclaredField: SQLData?] public var condition: Condition? public init(_ tableName: String, set valuesByField: [DeclaredField: SQLData?] = [:]) { self.tableName = tableName self.valuesByField = valuesByField } public init(_ tableName: String, set valuesByField: [DeclaredField: SQLDataConvertible?] = [:]) { var dict = [DeclaredField: SQLData?]() for (key, value) in valuesByField { dict[key] = value?.sqlData } self.init(tableName, set: dict) } public init(_ tableName: String, set valuesByField: [String: SQLDataConvertible?] = [:]) { var dict = [DeclaredField: SQLData?]() for (key, value) in valuesByField { dict[DeclaredField(name: key)] = value?.sqlData } self.init(tableName, set: dict) } } public struct ModelUpdate<T: Model>: UpdateQuery { public typealias ModelType = T public var tableName: String { return T.tableName } public var valuesByField: [DeclaredField: SQLData?] = [:] public var condition: Condition? public init(_ values: [ModelType.Field: SQLDataConvertible?]) { var dict = [DeclaredField: SQLData?]() for (key, value) in values { dict[ModelType.field(key)] = value?.sqlData ?? Optional(nil) } self.valuesByField = dict } public mutating func set(_ value: SQLData?, forField field: ModelType.Field) { set(value, forField: ModelType.field(field)) } public mutating func set(_ value: SQLDataConvertible?, forField field: ModelType.Field) { set(value?.sqlData, forField: field) } }
mit
160ed2e7e245b487692851debf59f71b
32.144144
99
0.692308
4.333333
false
false
false
false
WeHUD/app
weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/ButtonBarViewCell.swift
6
1907
// ButtonBarViewCell.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class ButtonBarViewCell: UICollectionViewCell { @IBOutlet open var imageView: UIImageView! @IBOutlet open lazy var label: UILabel! = { [unowned self] in let label = UILabel(frame: self.contentView.bounds) label.autoresizingMask = [.flexibleWidth, .flexibleHeight] label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 14.0) return label }() open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if label.superview != nil { contentView.addSubview(label) } } }
bsd-3-clause
980870e1615a1d686569978db2ad9c72
41.377778
80
0.722077
4.743781
false
false
false
false
hyacinthxinxin/Apprentice
Checklist/Checklist/Checklist.swift
1
1427
// // Checklist.swift // Checklist // // Created by 新 范 on 16/3/8. // Copyright © 2016年 fanxin. All rights reserved. // import UIKit class Checklist: NSObject { var name = "" var iconName: String var items = [ChecklistItem]() convenience init(name: String) { self.init(name: name, iconName: "No Icon") } init(name: String, iconName: String) { self.name = name self.iconName = iconName super.init() } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("Name") as! String iconName = aDecoder.decodeObjectForKey("IconName") as! String items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem] super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "Name") aCoder.encodeObject(iconName, forKey: "IconName") aCoder.encodeObject(items, forKey: "Items") } func sortChecklistItem() { items.sortInPlace({item1, item2 in return item1.dueDate.compare(item2.dueDate) == .OrderedAscending }) } func countUncheckedItems() -> Int { /* var count = 0 for item in items where !item.checked { count += 1 } return count */ return items.reduce(0) {cnt, item in cnt + (item.checked ? 0: 1)} } }
mit
d4429957f7e732ef4e2581c2e0d70e8e
24.818182
73
0.583099
4.238806
false
false
false
false
gmilos/swift
test/SILGen/objc_protocols.swift
2
12311
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @_TF14objc_protocols12objc_generic func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS1:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS2:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS2]] } // CHECK-LABEL: sil hidden @_TF14objc_protocols26objc_generic_partial_applyuRxS_9NSRuncingrFxT_ : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]]) // CHECK: destroy_value [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<T>() // CHECK: destroy_value [[METHOD]] _ = T.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_TTOZFP14objc_protocols9NSRuncing5minceFT_CSo8NSObject]] // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK: destroy_value [[METHOD:%.*]] _ = T.mince // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_TF14objc_protocols26objc_generic_partial_applyuRxS_9NSRuncingrFxT_' // CHECK: sil shared [thunk] @[[THUNK1]] : // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_TTOFP14objc_protocols9NSRuncing5runcefT_CSo8NSObject]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>([[SELF]]) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK1]]' // CHECK: sil shared [thunk] @[[THUNK1_THUNK]] // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign // CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]]) // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK1_THUNK]]' // CHECK: sil shared [thunk] @[[THUNK2]] : // CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_TTOZFP14objc_protocols9NSRuncing5mincefT_CSo8NSObject]] // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK2]]' // CHECK: sil shared [thunk] @[[THUNK2_THUNK]] : // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '[[THUNK2_THUNK]]' // CHECK-LABEL: sil hidden @_TF14objc_protocols13objc_protocol func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS1_ORIG:%.*]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS2_ORIG:%.*]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS2_ORIG]] } // CHECK-LABEL: sil hidden @_TF14objc_protocols27objc_protocol_partial_applyFPS_9NSRuncing_T_ : $@convention(thin) (@owned NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : $NSRuncing): // CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]]) // CHECK: destroy_value [[RESULT]] // CHECK: destroy_value [[ARG]] _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK : } // end sil function '_TF14objc_protocols27objc_protocol_partial_applyFPS_9NSRuncing_T_' // CHECK-LABEL: sil hidden @_TF14objc_protocols25objc_protocol_composition func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo3foo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar3foo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas3foo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim3foo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas4Zang3foo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols19StoredPropertyCountg5countSi class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols21ComputedPropertyCountg5countSi // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_TF14objc_protocols28testInitializableExistentialFTPMPS_13Initializable_1iSi_PS0__ : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable } // CHECK: [[PB:%.*]] = project_box [[I2_BOX]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_COPY:%.*]] = copy_value [[I2_ALLOC]] // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_COPY]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[PB]] : $*Initializable // CHECK: destroy_value [[I2_BOX]] : ${ var Initializable } // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '_TF14objc_protocols28testInitializableExistentialFTPMPS_13Initializable_1iSi_PS0__' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols22InitializableConformerc final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols33InitializableConformerByExtensionc // Make sure we're crashing from trying to use materializeForSet here. @objc protocol SelectionItem { var time: Double { get set } } func incrementTime(contents: SelectionItem) { contents.time += 1.0 }
apache-2.0
6efed2b5069eb6dc3d443d697d244fe6
41.257732
265
0.652842
3.541763
false
false
false
false
nissivm/DemoShopPayPal
DemoShop-PayPal/Objects/ShippingMethods.swift
1
1878
// // ShippingMethods.swift // DemoShop-PayPal // // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import Foundation class ShippingMethods { private var freeShipping: CGFloat = 0 private var pac: CGFloat = 0 private var sedex: CGFloat = 0 private var shippingOptions = [[String : AnyObject]]() init() { freeShipping = 0.00 pac = 20.00 sedex = 45.00 shippingOptions = [ ["description": "Free Shipping", "detail": "10 to 15 business days", "amount": freeShipping, "identifier": "free"], ["description": "PAC", "detail": "5 to 10 business days", "amount": pac, "identifier": "pac"], ["description": "SEDEX", "detail": "2 to 5 business days", "amount": sedex, "identifier": "sedex"] ] } func availableShippingMethods() -> [ShippingMethod] { var methods = [ShippingMethod]() for option in shippingOptions { let shippingMethod = ShippingMethod() shippingMethod.description = option["description"] as! String shippingMethod.detail = option["detail"] as! String shippingMethod.amount = option["amount"] as! CGFloat shippingMethod.identifier = option["identifier"] as! String methods.append(shippingMethod) } return methods } // In a real app, there'd be functions for calculate shipping method's values // according to costumer's zip code, shopping cart items weight, possible packing // measurements etc } class ShippingMethod { var description = "" var detail = "" var amount: CGFloat = 0 var identifier = "" }
mit
56c38ffe6cd017d04be172cbd16189ae
28.809524
91
0.55301
4.926509
false
false
false
false
brunchmade/mojito
Mojito/CandidatesWindow.swift
1
2199
// // CandidateWindow.swift // Mojito // // Created by Fang-Pen Lin on 12/30/15. // Copyright © 2015 VictorLin. All rights reserved. // import Cocoa import Foundation class CandidateWindow: NSWindow { private var initialLocation:NSPoint? override var canBecomeKeyWindow:Bool { get { return true } } override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool) { super.init(contentRect: contentRect, styleMask: NSBorderlessWindowMask, backing: bufferingType, `defer`: flag) opaque = false backgroundColor = NSColor.clearColor() // ref: https://github.com/danielpunkass/Blockpass/blob/master/Blockpass/AppDelegate.swift#L53-L55 // NSStatusWindowLevel doesn't seem available in Swift? And the types for CG constants // are mismatched Int vs Int32 so we have to do this dance level = Int(CGWindowLevelForKey(CGWindowLevelKey.StatusWindowLevelKey)) } required init?(coder: NSCoder) { super.init(coder: coder) } override func mouseDown(theEvent: NSEvent) { self.initialLocation = theEvent.locationInWindow } /* Once the user starts dragging the mouse, move the window with it. The window has no title bar for the user to drag (so we have to implement dragging ourselves) */ override func mouseDragged(theEvent: NSEvent) { let screenVisibleFrame = NSScreen.mainScreen()!.visibleFrame let windowFrame = frame var newOrigin = windowFrame.origin let currentLocation = theEvent.locationInWindow newOrigin.x += currentLocation.x - initialLocation!.x newOrigin.y += currentLocation.y - initialLocation!.y // Don't let window get dragged up under the menu bar if ((newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)) { newOrigin.y = screenVisibleFrame.origin.y + (screenVisibleFrame.size.height - windowFrame.size.height) } // Move the window to the new location setFrameOrigin(newOrigin) } }
mit
5e8440ef5e94a611dcce62bfa341cba7
35.633333
126
0.676979
4.627368
false
false
false
false
hulinSun/Better
better/better/Classes/Discover/Controller/DiscoverSingleController.swift
1
5377
// // DiscoverSingleController.swift // better // // Created by Hony on 2016/11/7. // Copyright © 2016年 Hony. All rights reserved. // import UIKit /// 发现页 单品控制器 class DiscoverSingleController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() DiscoverHttpHelper.requestDiscoverSingleCategory { (category) in self.topDatas = category } } var topDatas: SingleProCategory?{ didSet{ let count = Int((topDatas?.data?.category_list?.count)! / 6) + 1 pageControl.numberOfPages = count topCollectionView.reloadData() } } fileprivate lazy var topCollectionView: UICollectionView = { let i = UICollectionView(frame: .zero, collectionViewLayout: self.topLayout) i.register(UINib(nibName: "TopCategoryCell", bundle: nil), forCellWithReuseIdentifier: "TopCategoryCell") i.backgroundColor = UIColor.white i.showsVerticalScrollIndicator = false i.showsHorizontalScrollIndicator = false i.delegate = self i.dataSource = self i.isPagingEnabled = true i.bounces = false return i }() fileprivate lazy var pageControl: UIPageControl = { let i = UIPageControl() i.hidesForSinglePage = true i.pageIndicatorTintColor = UIColor.init(hexString: "#e4e4e4") i.currentPageIndicatorTintColor = UIColor.init(hexString: "#fd6363") return i }() fileprivate lazy var topView: UIView = { let i = UIView() // 按钮 let btn = UIButton() btn.backgroundColor = UIColor.clear btn.titleLabel?.font = UIFont.systemFont(ofSize: 13) btn.setTitle("分类", for: .normal) btn.setImage(UIImage(named:"descover_categoty_icon"), for: .normal) btn.imageView?.contentMode = .center btn.setTitleColor(UIColor.init(hexString: "#999999"), for: .normal) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) i.addSubview(btn) i.addSubview(self.topCollectionView) i.addSubview(self.pageControl) // 约束 btn.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(8) make.top.equalToSuperview().offset(10) make.width.equalTo(50) make.height.equalTo(20) } self.topCollectionView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(40) make.left.equalToSuperview().offset(5) make.right.equalToSuperview().offset(-5) make.height.equalTo(290) } self.pageControl.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalTo(150) make.bottom.equalToSuperview() make.height.equalTo(30) } return i }() fileprivate lazy var topLayout: UICollectionViewFlowLayout = { let i = UICollectionViewFlowLayout() i.itemSize = CGSize(width: (UIConst.screenWidth - 10) * CGFloat(0.5), height: 90) i.scrollDirection = .horizontal i.minimumLineSpacing = 0 i.minimumInteritemSpacing = 0 return i }() fileprivate lazy var bottomCollectionView: UICollectionView = { let i = UICollectionView(frame: .zero, collectionViewLayout: self.bottomLayout) return i }() fileprivate lazy var bottomLayout: UICollectionViewFlowLayout = { let i = UICollectionViewFlowLayout() return i }() fileprivate func setupUI(){ view.backgroundColor = UIColor.init(hexString: "f4f4f4") view.addSubview(topView) topView.backgroundColor = UIColor.white topView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(10 + 64) make.left.equalToSuperview() make.right.equalToSuperview() make.height.equalTo(360) } } } typealias CollectionProtocol = DiscoverSingleController extension CollectionProtocol: UICollectionViewDelegate , UICollectionViewDataSource , UIScrollViewDelegate{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return topDatas?.data?.category_list?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TopCategoryCell", for: indexPath) as! TopCategoryCell cell.item = topDatas?.data?.category_list?[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let item = topDatas?.data?.category_list?[indexPath.item] else { return } print("点击了\(item.name)") let hot = HotRecommondController() navigationController?.pushViewController(hot, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.currentPage = Int(CGFloat(scrollView.contentOffset.x) / UIConst.screenWidth + 0.5) } }
mit
f32ca72ad50c084eebfe4dc4d2964976
32.584906
129
0.632022
4.949027
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/UnusedClosureParameterRule.swift
1
9361
import Foundation import SourceKittenFramework public struct UnusedClosureParameterRule: ASTRule, ConfigurationProviderRule, CorrectableRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "unused_closure_parameter", name: "Unused Closure Parameter", description: "Unused parameter in a closure should be replaced with _.", kind: .lint, nonTriggeringExamples: [ "[1, 2].map { $0 + 1 }\n", "[1, 2].map({ $0 + 1 })\n", "[1, 2].map { number in\n number + 1 \n}\n", "[1, 2].map { _ in\n 3 \n}\n", "[1, 2].something { number, idx in\n return number * idx\n}\n", "let isEmpty = [1, 2].isEmpty()\n", "violations.sorted(by: { lhs, rhs in \n return lhs.location > rhs.location\n})\n", "rlmConfiguration.migrationBlock.map { rlmMigration in\n" + "return { migration, schemaVersion in\n" + "rlmMigration(migration.rlmMigration, schemaVersion)\n" + "}\n" + "}", "genericsFunc { (a: Type, b) in\n" + "a + b\n" + "}\n", "var label: UILabel = { (lbl: UILabel) -> UILabel in\n" + " lbl.backgroundColor = .red\n" + " return lbl\n" + "}(UILabel())\n", "hoge(arg: num) { num in\n" + " return num\n" + "}\n", """ ({ (manager: FileManager) in print(manager) })(FileManager.default) """ ], triggeringExamples: [ "[1, 2].map { ↓number in\n return 3\n}\n", "[1, 2].map { ↓number in\n return numberWithSuffix\n}\n", "[1, 2].map { ↓number in\n return 3 // number\n}\n", "[1, 2].map { ↓number in\n return 3 \"number\"\n}\n", "[1, 2].something { number, ↓idx in\n return number\n}\n", "genericsFunc { (↓number: TypeA, idx: TypeB) in return idx\n}\n", "hoge(arg: num) { ↓num in\n" + "}\n", "fooFunc { ↓아 in\n }", "func foo () {\n bar { ↓number in\n return 3\n}\n" ], corrections: [ "[1, 2].map { ↓number in\n return 3\n}\n": "[1, 2].map { _ in\n return 3\n}\n", "[1, 2].map { ↓number in\n return numberWithSuffix\n}\n": "[1, 2].map { _ in\n return numberWithSuffix\n}\n", "[1, 2].map { ↓number in\n return 3 // number\n}\n": "[1, 2].map { _ in\n return 3 // number\n}\n", "[1, 2].map { ↓number in\n return 3 \"number\"\n}\n": "[1, 2].map { _ in\n return 3 \"number\"\n}\n", "[1, 2].something { number, ↓idx in\n return number\n}\n": "[1, 2].something { number, _ in\n return number\n}\n", "genericsFunc(closure: { (↓int: Int) -> Void in // do something\n}\n": "genericsFunc(closure: { (_: Int) -> Void in // do something\n}\n", "genericsFunc { (↓a, ↓b: Type) -> Void in\n}\n": "genericsFunc { (_, _: Type) -> Void in\n}\n", "genericsFunc { (↓a: Type, ↓b: Type) -> Void in\n}\n": "genericsFunc { (_: Type, _: Type) -> Void in\n}\n", "genericsFunc { (↓a: Type, ↓b) -> Void in\n}\n": "genericsFunc { (_: Type, _) -> Void in\n}\n", "genericsFunc { (a: Type, ↓b) -> Void in\nreturn a\n}\n": "genericsFunc { (a: Type, _) -> Void in\nreturn a\n}\n", "hoge(arg: num) { ↓num in\n}\n": "hoge(arg: num) { _ in\n}\n", "func foo () {\n bar { ↓number in\n return 3\n}\n": "func foo () {\n bar { _ in\n return 3\n}\n", "class C {\n #if true\n func f() {\n [1, 2].map { ↓number in\n return 3\n }\n }\n #endif\n}": "class C {\n #if true\n func f() {\n [1, 2].map { _ in\n return 3\n }\n }\n #endif\n}" ] ) public func validate(file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { return violationRanges(in: file, dictionary: dictionary, kind: kind).map { range, name in let reason = "Unused parameter \"\(name)\" in a closure should be replaced with _." return StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: range.location), reason: reason) } } private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable], kind: SwiftExpressionKind) -> [(range: NSRange, name: String)] { guard kind == .call, !isClosure(dictionary: dictionary), let offset = dictionary.offset, let length = dictionary.length, let nameOffset = dictionary.nameOffset, let nameLength = dictionary.nameLength, let bodyLength = dictionary.bodyLength, bodyLength > 0 else { return [] } let rangeStart = nameOffset + nameLength let rangeLength = (offset + length) - (nameOffset + nameLength) let parameters = dictionary.enclosedVarParameters let contents = file.contents.bridge() return parameters.compactMap { param -> (NSRange, String)? in guard let paramOffset = param.offset, let name = param.name, name != "_", let regex = try? NSRegularExpression(pattern: name, options: [.ignoreMetacharacters]), let range = contents.byteRangeToNSRange(start: rangeStart, length: rangeLength) else { return nil } let paramLength = name.lengthOfBytes(using: .utf8) let matches = regex.matches(in: file.contents, options: [], range: range).ranges() for range in matches { guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length), // if it's the parameter declaration itself, we should skip byteRange.location > paramOffset, case let tokens = file.syntaxMap.tokens(inByteRange: byteRange), // a parameter usage should be only one token tokens.count == 1 else { continue } // found a usage, there's no violation! if let token = tokens.first, SyntaxKind(rawValue: token.type) == .identifier, token.offset == byteRange.location, token.length == byteRange.length { return nil } } if let range = contents.byteRangeToNSRange(start: paramOffset, length: paramLength) { return (range, name) } return nil } } private func isClosure(dictionary: [String: SourceKitRepresentable]) -> Bool { return dictionary.name.flatMap { name -> Bool in let length = name.bridge().length let range = NSRange(location: 0, length: length) return regex("\\A[\\s\\(]*?\\{").firstMatch(in: name, options: [], range: range) != nil } ?? false } private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable]) -> [NSRange] { let ranges = dictionary.substructure.flatMap { subDict -> [NSRange] in var ranges = violationRanges(in: file, dictionary: subDict) if let kind = subDict.kind.flatMap(SwiftExpressionKind.init(rawValue:)) { ranges += violationRanges(in: file, dictionary: subDict, kind: kind).map { $0.0 } } return ranges } return ranges.unique } private func violationRanges(in file: File) -> [NSRange] { return violationRanges(in: file, dictionary: file.structure.dictionary).sorted { lhs, rhs in lhs.location < rhs.location } } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: "_") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
mit
92a07036e551fbc9f1f7b43c62538213
45.545
105
0.519175
4.301756
false
false
false
false
banxi1988/Staff
Pods/BXiOSUtils/Pod/Classes/NSDateExtenstions.swift
1
10104
// File.swift // ExSwift // // Created by Piergiuseppe Longo on 23/11/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension NSDate { // MARK: NSDate Manipulation /** Returns a new NSDate object representing the date calculated by adding the amount specified to self date :param: seconds number of seconds to add :param: minutes number of minutes to add :param: hours number of hours to add :param: days number of days to add :param: weeks number of weeks to add :param: months number of months to add :param: years number of years to add :returns: the NSDate computed */ // public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { // var calendar = NSCalendar.currentCalendar() // // let version = floor(NSFoundationVersionNumber) // // if version <= NSFoundationVersionNumber10_9_2 { // var component = NSDateComponents() // component.setValue(seconds, forComponent: .Second) // // var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: nil)! // component = NSDateComponents() // component.setValue(minutes, forComponent: .Minute) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // // component = NSDateComponents() // component.setValue(hours, forComponent: .Hour) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // // component = NSDateComponents() // component.setValue(days, forComponent: .Day) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // // component = NSDateComponents() // component.setValue(weeks, forComponent: .WeekOfMonth) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // // component = NSDateComponents() // component.setValue(months, forComponent: .Month) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // // component = NSDateComponents() // component.setValue(years, forComponent: .Year) // date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! // return date // } // // var date : NSDate! = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil) // date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil) // return date // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date // // :param: seconds number of seconds to add // :returns: the NSDate computed // */ // public func addSeconds (seconds: Int) -> NSDate { // return add(seconds: seconds) // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date // // :param: minutes number of minutes to add // :returns: the NSDate computed // */ // public func addMinutes (minutes: Int) -> NSDate { // return add(minutes: minutes) // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of hours to self date // // :param: hours number of hours to add // :returns: the NSDate computed // */ // public func addHours(hours: Int) -> NSDate { // return add(hours: hours) // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of days to self date // // :param: days number of days to add // :returns: the NSDate computed // */ // public func addDays(days: Int) -> NSDate { // return add(days: days) // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date // // :param: weeks number of weeks to add // :returns: the NSDate computed // */ // public func addWeeks(weeks: Int) -> NSDate { // return add(weeks: weeks) // } // // // /** // Returns a new NSDate object representing the date calculated by adding an amount of months to self date // // :param: months number of months to add // :returns: the NSDate computed // */ // // public func addMonths(months: Int) -> NSDate { // return add(months: months) // } // // /** // Returns a new NSDate object representing the date calculated by adding an amount of years to self date // // :param: years number of year to add // :returns: the NSDate computed // */ // public func addYears(years: Int) -> NSDate { // return add(years: years) // } // // MARK: Date comparison /** Checks if self is after input NSDate :param: date NSDate to compare :returns: True if self is after the input NSDate, false otherwise */ public func isAfter(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedDescending) } /** Checks if self is before input NSDate :param: date NSDate to compare :returns: True if self is before the input NSDate, false otherwise */ public func isBefore(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedAscending) } // MARK: Getter /** Date year */ public var year : Int { get { return getComponent(.Year) } } /** Date month */ public var month : Int { get { return getComponent(.Month) } } /** Date weekday */ public var weekday : Int { get { return getComponent(.Weekday) } } /** Date weekMonth */ public var weekMonth : Int { get { return getComponent(.WeekOfMonth) } } /** Date days */ public var days : Int { get { return getComponent(.Day) } } /** Date hours */ public var hours : Int { get { return getComponent(.Hour) } } /** Date minuts */ public var minutes : Int { get { return getComponent(.Minute) } } /** Date seconds */ public var seconds : Int { get { return getComponent(.Second) } } /** Returns the value of the NSDate component :param: component NSCalendarUnit :returns: the value of the component */ public func getComponent (component : NSCalendarUnit) -> Int { let calendar = NSCalendar.currentCalendar() let components = calendar.components(component, fromDate: self) return components.valueForComponent(component) } } //extension NSDate: Strideable { // public func distanceTo(other: NSDate) -> NSTimeInterval { // return other - self // } // // public func advancedBy(n: NSTimeInterval) -> Self { // return NSDate(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) // } //} // MARK: Arithmetic func +(date: NSDate, timeInterval: Int) -> NSDate { return date + NSTimeInterval(timeInterval) } func -(date: NSDate, timeInterval: Int) -> NSDate { return date - NSTimeInterval(timeInterval) } func +=(inout date: NSDate, timeInterval: Int) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Int) { date = date - timeInterval } func +(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval)) } func -(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval)) } func +=(inout date: NSDate, timeInterval: Double) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Double) { date = date - timeInterval } func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { return date.timeIntervalSinceDate(otherDate) } //extension NSDate: Equatable { //} // //public func ==(lhs: NSDate, rhs: NSDate) -> Bool { // return lhs.compare(rhs) == NSComparisonResult.OrderedSame //} extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } extension NSDate{ public var bx_shortDateString:String{ return bx_dateTimeStringWithFormatStyle(.ShortStyle, timeStyle: .NoStyle) } public var bx_longDateString:String{ return bx_dateTimeStringWithFormatStyle(.MediumStyle, timeStyle: .NoStyle) } public var bx_shortTimeString:String{ return bx_dateTimeStringWithFormatStyle(.NoStyle, timeStyle: .ShortStyle) } public var bx_dateTimeString:String{ return bx_dateTimeStringWithFormatStyle(.MediumStyle, timeStyle: .MediumStyle) } public func bx_dateTimeStringWithFormatStyle(dateStyle:NSDateFormatterStyle,timeStyle:NSDateFormatterStyle) -> String{ let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = dateStyle dateFormatter.timeStyle = timeStyle return dateFormatter.stringFromDate(self) } public var bx_relativeDateTimeString:String{ let secondsToNow = abs(Int(timeIntervalSinceNow)) let now = NSDate() let calendar = NSCalendar.currentCalendar() switch secondsToNow{ case 0..<60: return "刚刚" case 60..<300: return "\(secondsToNow / 60)分钟前" default: if calendar.isDateInYesterday(self){ return "昨天 \(bx_shortTimeString)" }else if calendar.isDateInToday(self){ return bx_shortTimeString }else if now.year == year{ return bx_shortDateString }else{ return self.bx_longDateString } } } }
mit
4e61f0fb71a2312932a50113ff57be55
26.568306
147
0.662339
4.088331
false
false
false
false
ben-ng/swift
test/stdlib/TestUUID.swift
1
6182
// Copyright (c) 2014 - 2016 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 // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestUUIDSuper : XCTestCase { } #else import StdlibUnittest class TestUUIDSuper { } #endif class TestUUID : TestUUIDSuper { func test_NS_Equality() { let uuidA = NSUUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") let uuidB = NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f") let uuidC = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f]) let uuidD = NSUUID() expectEqual(uuidA, uuidB, "String case must not matter.") expectEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.") expectNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.") } func test_Equality() { let uuidA = UUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") let uuidB = UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f") let uuidC = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f)) let uuidD = UUID() expectEqual(uuidA, uuidB, "String case must not matter.") expectEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.") expectNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.") } func test_NS_InvalidUUID() { let uuid = NSUUID(uuidString: "Invalid UUID") expectNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.") } func test_InvalidUUID() { let uuid = UUID(uuidString: "Invalid UUID") expectNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.") } func test_NS_uuidString() { let uuid = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f]) expectEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") } func test_uuidString() { let uuid = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f)) expectEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") } func test_description() { let uuid = UUID() expectEqual(uuid.description, uuid.uuidString, "The description must be the same as the uuidString.") } func test_roundTrips() { let ref = NSUUID() let valFromRef = ref as UUID var bytes: [UInt8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] let valFromBytes = bytes.withUnsafeMutableBufferPointer { buffer -> UUID in ref.getBytes(buffer.baseAddress) return UUID(uuid: UnsafeRawPointer(buffer.baseAddress!).load(as: uuid_t.self)) } let valFromStr = UUID(uuidString: ref.uuidString) expectEqual(ref.uuidString, valFromRef.uuidString) expectEqual(ref.uuidString, valFromBytes.uuidString) expectNotNil(valFromStr) expectEqual(ref.uuidString, valFromStr!.uuidString) } func test_hash() { let ref = NSUUID() let val = UUID(uuidString: ref.uuidString)! expectEqual(ref.hashValue, val.hashValue, "Hashes of references and values should be identical") } func test_AnyHashableContainingUUID() { let values: [UUID] = [ UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!, UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, ] let anyHashables = values.map(AnyHashable.init) expectEqual(UUID.self, type(of: anyHashables[0].base)) expectEqual(UUID.self, type(of: anyHashables[1].base)) expectEqual(UUID.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSUUID() { let values: [NSUUID] = [ NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!, NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, ] let anyHashables = values.map(AnyHashable.init) expectEqual(UUID.self, type(of: anyHashables[0].base)) expectEqual(UUID.self, type(of: anyHashables[1].base)) expectEqual(UUID.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } #if !FOUNDATION_XCTEST var UUIDTests = TestSuite("TestUUID") UUIDTests.test("test_NS_Equality") { TestUUID().test_NS_Equality() } UUIDTests.test("test_Equality") { TestUUID().test_Equality() } UUIDTests.test("test_NS_InvalidUUID") { TestUUID().test_NS_InvalidUUID() } UUIDTests.test("test_InvalidUUID") { TestUUID().test_InvalidUUID() } UUIDTests.test("test_NS_uuidString") { TestUUID().test_NS_uuidString() } UUIDTests.test("test_uuidString") { TestUUID().test_uuidString() } UUIDTests.test("test_description") { TestUUID().test_description() } UUIDTests.test("test_roundTrips") { TestUUID().test_roundTrips() } UUIDTests.test("test_hash") { TestUUID().test_hash() } UUIDTests.test("test_AnyHashableContainingUUID") { TestUUID().test_AnyHashableContainingUUID() } UUIDTests.test("test_AnyHashableCreatedFromNSUUID") { TestUUID().test_AnyHashableCreatedFromNSUUID() } runAllTests() #endif
apache-2.0
7823fc2e4d02ab0fdb0e775bc67ba3b8
44.124088
169
0.673083
3.245144
false
true
false
false
dbahat/conventions-ios
Conventions/Conventions/model/Updates.swift
1
4714
// // SffUpdates.swift // Conventions // // Created by David Bahat on 9/26/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation class Updates { fileprivate static let apiUrl = "https://api.sf-f.org.il/announcements/get.php?slug="+Convention.name; fileprivate static let cacheFile = NSHomeDirectory() + "/Library/Caches/" + Convention.name + "Updates.json"; fileprivate var updates: Array<Update> = []; init() { if let cachedUpdates = load() { updates = cachedUpdates; } } func getAll() -> Array<Update> { return updates; } func markAllAsRead() { updates.forEach({$0.isNew = false}); save(); } func refresh(_ callback: ((_ success: Bool) -> Void)?) { download({result in guard let updates = result else { DispatchQueue.main.async { callback?(false) } return; } let parsedUpdates = self.parse(updates) let sortedUpdates = parsedUpdates.sorted(by: {$0.date.timeIntervalSince1970 > $1.date.timeIntervalSince1970}) // Using main thread for syncronizing access to events DispatchQueue.main.async { self.updates = sortedUpdates; print("Downloaded updates: ", self.updates.count) callback?(true) // Persist the updated events in a background thread, so as not to block the UI DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { self.save() } } }); } fileprivate func download(_ completion: @escaping (_ data: Data?) -> Void) { let session = URLSession(configuration: URLSessionConfiguration.default); let url = URL(string: Updates.apiUrl)!; session.dataTask(with: url, completionHandler: { (data, response, error) -> Void in completion(data); }).resume(); } fileprivate func parse(_ response: Data) -> Array<Update> { var result = Array<Update>(); guard let deserializedEvents = ((try? JSONSerialization.jsonObject(with: response, options: []) as? NSArray) as NSArray??), let updates = deserializedEvents else { print("Failed to deserialize updates"); return result; } for rawUpdate in updates { guard let update = rawUpdate as? Dictionary<String, AnyObject> else { print("Got invalid update. Skipping"); continue; } guard let id = update["id"] as? String else { print("Got update without ID. Skipping"); continue; } guard let text = update["content"] as? String else { print("Got update without ID. Skipping"); continue; } guard let time = update["update_time"] as? String else { print("Got update without ID. Skipping"); continue; } result.append(Update(id: id, text: text, date: parseDate(time))) } return result } fileprivate func parseDate(_ time: String) -> Date { if let result = Date.parse(time, dateFormat: "yyyy-MM-dd'T'HH:mm:ssxxxxx") { return result; } return Date.now() } fileprivate func save() { let serializedUpdates = self.updates.map({$0.toJson()}); let json = try? JSONSerialization.data(withJSONObject: serializedUpdates, options: JSONSerialization.WritingOptions.prettyPrinted); ((try? json?.write(to: URL(fileURLWithPath: Updates.cacheFile), options: [.atomic])) as ()??); } fileprivate func load() -> Array<Update>? { guard let storedUpdates = try? Data(contentsOf: URL(fileURLWithPath: Updates.cacheFile)) else { return nil; } guard let updatesJson = try? JSONSerialization.jsonObject(with: storedUpdates, options: JSONSerialization.ReadingOptions.allowFragments) else { return nil; } guard let parsedUpdates = updatesJson as? [Dictionary<String, AnyObject>] else { return nil; } var result = Array<Update>(); parsedUpdates.forEach({parsedUpdate in if let update = Update(json: parsedUpdate) { result.append(update); } }); return result; } }
apache-2.0
dcb148240cfef6d1af11f0637845b0c0
33.40146
151
0.545725
4.98203
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View/QiscusChatVC/QVCAction.swift
1
54918
// // QVCAction.swift // Example // // Created by Ahmad Athaullah on 5/16/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit import Photos import MobileCoreServices import SwiftyJSON import ContactsUI extension QiscusChatVC:CNContactPickerDelegate{ //func shareContact public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { func share(name:String, value:String){ let newComment = self.chatRoom!.newContactComment(name: name, value: value) self.postComment(comment: newComment) self.chatRoom!.post(comment: newComment, onSuccess: { }, onError: { (error) in Qiscus.printLog(text: "error \(error)") }) self.addCommentToCollectionView(comment: newComment) } let contactName = "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespacesAndNewlines) let contactSheetController = UIAlertController(title: contactName, message: "select contact you want to share", preferredStyle: .actionSheet) let cancelActionButton = UIAlertAction(title: "CANCEL".getLocalize(), style: .cancel) { action -> Void in } contactSheetController.addAction(cancelActionButton) for phoneNumber in contact.phoneNumbers { let value = phoneNumber.value.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) var title = "\(value)" if let label = phoneNumber.label { let labelString = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label) title = "\(labelString): \(value)" } let phoneButton = UIAlertAction(title: title, style: .default) { action -> Void in share(name: contactName, value: value) } contactSheetController.addAction(phoneButton) } for email in contact.emailAddresses { let value = email.value as String var title = "\(value)" if let label = email.label { let labelString = CNLabeledValue<NSString>.localizedString(forLabel: label) title = "\(labelString): \(value)" } let emailButton = UIAlertAction(title: title, style: .default) { action -> Void in share(name: contactName, value: value) } contactSheetController.addAction(emailButton) } picker.dismiss(animated: true, completion: nil) self.present(contactSheetController, animated: true, completion: nil) } } extension QiscusChatVC { @objc public func showLoading(_ text:String = "Loading"){ if !self.presentingLoading { self.presentingLoading = true self.showQiscusLoading(withText: text, isBlocking: true) } } @objc public func dismissLoading(){ self.presentingLoading = false self.dismissQiscusLoading() } @objc public func unlockChat(){ self.archievedNotifTop.constant = 65 UIView.animate(withDuration: 0.6, animations: { self.view.layoutIfNeeded() }, completion: { _ in self.archievedNotifView.isHidden = true }) } @objc public func lockChat(){ self.archived = true self.archievedNotifView.isHidden = false self.archievedNotifTop.constant = 0 UIView.animate(withDuration: 0.6, animations: { self.view.layoutIfNeeded() } ) } @objc func confirmUnlockChat(){ self.unlockAction() } func showAlert(alert:UIAlertController){ self.present(alert, animated: true, completion: nil) } func shareContact(){ self.contactVC.delegate = self self.present(self.contactVC, animated: true, completion: nil) } func showAttachmentMenu(){ let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelActionButton = UIAlertAction(title: "CANCEL".getLocalize(), style: .cancel) { action -> Void in Qiscus.printLog(text: "Cancel attach file") } actionSheetController.addAction(cancelActionButton) if Qiscus.shared.cameraUpload { let cameraActionButton = UIAlertAction(title: "CAMERA".getLocalize(), style: .default) { action -> Void in self.uploadFromCamera() } actionSheetController.addAction(cameraActionButton) } if Qiscus.shared.galeryUpload { let galeryActionButton = UIAlertAction(title: "GALLERY".getLocalize(), style: .default) { action -> Void in self.uploadImage() } actionSheetController.addAction(galeryActionButton) } if Qiscus.sharedInstance.iCloudUpload { let iCloudActionButton = UIAlertAction(title: "DOCUMENT".getLocalize(), style: .default) { action -> Void in self.iCloudOpen() } actionSheetController.addAction(iCloudActionButton) } if Qiscus.shared.contactShare { let contactActionButton = UIAlertAction(title: "CONTACT".getLocalize(), style: .default) { action -> Void in self.shareContact() } actionSheetController.addAction(contactActionButton) } if Qiscus.shared.locationShare { let contactActionButton = UIAlertAction(title: "CURRENT_LOCATION".getLocalize(), style: .default) { action -> Void in self.shareCurrentLocation() } actionSheetController.addAction(contactActionButton) } if let delegate = self.delegate{ delegate.chatVC?(didTapAttachment: actionSheetController, viewController: self, onRoom: self.chatRoom) } self.present(actionSheetController, animated: true, completion: nil) } func shareCurrentLocation(){ self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { switch CLLocationManager.authorizationStatus() { case .authorizedAlways, .authorizedWhenInUse: self.showLoading("LOADING_LOCATION".getLocalize()) locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters self.didFindLocation = false self.locationManager.startUpdatingLocation() break case .denied: self.showLocationAccessAlert() break case .restricted: self.showLocationAccessAlert() break case .notDetermined: self.showLocationAccessAlert() break } }else{ self.showLocationAccessAlert() } } func getLinkPreview(url:String){ } func hideLinkContainer(){ Qiscus.uiThread.async { autoreleasepool{ self.linkPreviewTopMargin.constant = 0 UIView.animate(withDuration: 0.65, animations: { self.view.layoutIfNeeded() }, completion: nil) }} } func showNoConnectionToast(){ QToasterSwift.toast(target: self, text: QiscusTextConfiguration.sharedInstance.noConnectionText, backgroundColor: UIColor(red: 0.9, green: 0,blue: 0,alpha: 0.8), textColor: UIColor.white) } // MARK: - Overriding back action func setTitle(title:String = "", withSubtitle:String? = nil){ QiscusUIConfiguration.sharedInstance.copyright.chatTitle = title if withSubtitle != nil { QiscusUIConfiguration.sharedInstance.copyright.chatSubtitle = withSubtitle! } self.loadTitle() } func subscribeRealtime(){ // if let room = self.chatRoom { // let delay = 3 * Double(NSEC_PER_SEC) // let time = DispatchTime.now() + delay / Double(NSEC_PER_SEC) // // DispatchQueue.main.asyncAfter(deadline: time, execute: { // let typingChannel:String = "r/\(room.id)/\(room.id)/+/t" // let readChannel:String = "r/\(room.id)/\(room.id)/+/r" // let deliveryChannel:String = "r/\(room.id)/\(room.id)/+/d" // Qiscus.shared.mqtt?.subscribe(typingChannel, qos: .qos1) // Qiscus.shared.mqtt?.subscribe(readChannel, qos: .qos1) // Qiscus.shared.mqtt?.subscribe(deliveryChannel, qos: .qos1) // for participant in room.participants { // let userChannel = "u/\(participant.email)/s" // Qiscus.shared.mqtt?.subscribe(userChannel, qos: .qos1) // } // }) // } } func unsubscribeTypingRealtime(onRoom room:QRoom?){ // if room != nil { // let channel = "r/\(room!.id)/\(room!.id)/+/t" // Qiscus.shared.mqtt?.unsubscribe(channel) // } } func iCloudOpen(){ if Qiscus.sharedInstance.connected{ UINavigationBar.appearance().tintColor = UIColor.blue let documentPicker = UIDocumentPickerViewController(documentTypes: self.UTIs, in: UIDocumentPickerMode.import) documentPicker.delegate = self documentPicker.modalPresentationStyle = UIModalPresentationStyle.fullScreen self.present(documentPicker, animated: true, completion: nil) }else{ self.showNoConnectionToast() } } func goToIPhoneSetting(){ UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) let _ = self.navigationController?.popViewController(animated: true) } func loadTitle(){ DispatchQueue.main.async {autoreleasepool{ if self.chatTitle == nil || self.chatTitle == "" { if let room = self.chatRoom { self.titleLabel.text = room.name if self.roomAvatarImage == nil { self.roomAvatar.image = Qiscus.image(named: "avatar") room.loadAvatar(onSuccess: { (avatar) in self.roomAvatar.image = avatar }, onError: { (_) in room.downloadRoomAvatar() }) } } } else{ self.titleLabel.text = self.chatTitle if let room = self.chatRoom { self.roomAvatar.image = Qiscus.image(named: "avatar") room.loadAvatar(onSuccess: { (avatar) in self.roomAvatar.image = avatar }, onError: { (_) in room.downloadRoomAvatar() }) } } }} } func loadSubtitle(){ if self.chatRoom != nil{ if self.chatRoom!.isInvalidated {return} DispatchQueue.main.async {autoreleasepool{ var prevSubtitle = "" if let currentSubtitle = self.subtitleLabel.text { prevSubtitle = currentSubtitle } if self.chatSubtitle == nil || self.chatSubtitle == "" { if let room = self.chatRoom { if room.isInvalidated { return } var subtitleString = "" if room.type == .group{ if room.isPublicChannel { subtitleString = "\(room.roomTotalParticipant) people" } else { subtitleString = "YOU".getLocalize() for participant in room.participants { if participant.email != Qiscus.client.email { if let user = participant.user { subtitleString += ", \(user.fullname)" } } } } }else{ if room.participants.count > 0 { for participant in room.participants { if participant.email != Qiscus.client.email { if let user = participant.user { if user.presence == .offline{ let lastSeenString = user.lastSeenString if lastSeenString != "" { subtitleString = "LAST_SEEN".getLocalize(value: "\(user.lastSeenString)") } }else{ subtitleString = "online" } } break } } }else{ subtitleString = "" } } var frame = self.titleLabel.frame if subtitleString == "" && prevSubtitle == "" && frame.size.height == 17 && room.type == .single{ self.subtitleLabel.text = "" frame.size.height = 30 UIView.animate(withDuration: 0.5, animations: { self.titleLabel.frame = frame }) } else if subtitleString == "" && prevSubtitle != "" && room.type == .single{ // increase title height self.subtitleLabel.text = "" frame.size.height = 30 UIView.animate(withDuration: 0.5, animations: { self.titleLabel.frame = frame }) }else if subtitleString != "" && prevSubtitle == "" && room.type == .single{ // reduce titleHeight frame.size.height = 17 UIView.animate(withDuration: 0.5, animations: { self.titleLabel.frame = frame }, completion: { (_) in self.subtitleLabel.text = subtitleString self.subtitleText = subtitleString }) }else{ self.subtitleLabel.text = subtitleString self.subtitleText = subtitleString } if subtitleString.contains("minute") || subtitleString.contains("hours") || subtitleString.contains("seconds"){ var delay = 60.0 * Double(NSEC_PER_SEC) if subtitleString.contains("hours"){ delay = 3600.0 * Double(NSEC_PER_SEC) } let time = DispatchTime.now() + delay / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { self.loadSubtitle() }) } } }else{ self.subtitleLabel.text = self.chatSubtitle! self.subtitleText = self.chatSubtitle! } }} } } func showLocationAccessAlert(){ DispatchQueue.main.async{autoreleasepool{ let text = QiscusTextConfiguration.sharedInstance.locationAccessAlertText let cancelTxt = QiscusTextConfiguration.sharedInstance.alertCancelText let settingTxt = QiscusTextConfiguration.sharedInstance.alertSettingText QPopUpView.showAlert(withTarget: self, message: text, firstActionTitle: settingTxt, secondActionTitle: cancelTxt, doneAction: { self.goToIPhoneSetting() }, cancelAction: {} ) }} } func showPhotoAccessAlert(){ DispatchQueue.main.async(execute: { let text = QiscusTextConfiguration.sharedInstance.galeryAccessAlertText let cancelTxt = QiscusTextConfiguration.sharedInstance.alertCancelText let settingTxt = QiscusTextConfiguration.sharedInstance.alertSettingText QPopUpView.showAlert(withTarget: self, message: text, firstActionTitle: settingTxt, secondActionTitle: cancelTxt, doneAction: { self.goToIPhoneSetting() }, cancelAction: {} ) }) } func showCameraAccessAlert(){ DispatchQueue.main.async(execute: { let text = QiscusTextConfiguration.sharedInstance.cameraAccessAlertText let cancelTxt = QiscusTextConfiguration.sharedInstance.alertCancelText let settingTxt = QiscusTextConfiguration.sharedInstance.alertSettingText QPopUpView.showAlert(withTarget: self, message: text, firstActionTitle: settingTxt, secondActionTitle: cancelTxt, doneAction: { self.goToIPhoneSetting() }, cancelAction: {} ) }) } func showMicrophoneAccessAlert(){ DispatchQueue.main.async(execute: { let text = QiscusTextConfiguration.sharedInstance.microphoneAccessAlertText let cancelTxt = QiscusTextConfiguration.sharedInstance.alertCancelText let settingTxt = QiscusTextConfiguration.sharedInstance.alertSettingText QPopUpView.showAlert(withTarget: self, message: text, firstActionTitle: settingTxt, secondActionTitle: cancelTxt, doneAction: { self.goToIPhoneSetting() }, cancelAction: {} ) }) } func goToGaleryPicker(){ DispatchQueue.main.async(execute: { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.photoLibrary picker.mediaTypes = [kUTTypeMovie as String, kUTTypeImage as String] self.present(picker, animated: true, completion: nil) }) } @objc func goToTitleAction(){ self.inputBarBottomMargin.constant = 0 self.view.layoutIfNeeded() if let delegate = self.delegate { delegate.chatVC?(titleAction: self, room: self.chatRoom, data:self.data) } } // func scrollToBottom(_ animated:Bool = false){ // self.collectionView.scrollToBottom() //// if self.chatRoom != nil { //// if self.collectionView.numberOfSections > 0 { //// let section = self.collectionView.numberOfSections - 1 //// if self.collectionView.numberOfItems(inSection: section) > 0 { //// let item = self.collectionView.numberOfItems(inSection: section) - 1 //// let lastIndexPath = IndexPath(row: item, section: section) //// self.collectionView.scrollToItem(at: lastIndexPath, at: .bottom, animated: animated) //// if self.isPresence { //// self.chatRoom!.readAll() //// } //// } //// } //// } // } func setNavigationColor(_ color:UIColor, tintColor:UIColor){ self.topColor = color self.bottomColor = color self.tintColor = tintColor self.navigationController?.navigationBar.verticalGradientColor(topColor, bottomColor: bottomColor) self.navigationController?.navigationBar.tintColor = tintColor let _ = self.view self.sendButton.tintColor = self.topColor if self.inputText.value == "" { self.sendButton.isEnabled = false } self.attachButton.tintColor = self.topColor self.bottomButton.tintColor = self.topColor self.recordButton.tintColor = self.topColor self.cancelRecordButton.tintColor = self.topColor self.emptyChatImage.tintColor = self.bottomColor } @objc func sendMessage(){ //if Qiscus.shared.connected{ if !self.isRecording { let value = self.inputText.value.trimmingCharacters(in: .whitespacesAndNewlines) if value != "" { var type:QCommentType = .text var payload:JSON? = nil if let reply = self.replyData { if (reply.isInvalidated) { self.replyData = nil self.inputText.clearValue() return } var senderName = reply.senderName if let user = reply.sender{ senderName = user.fullname } var payloadArray: [(String,Any)] = [ ("replied_comment_sender_email",reply.senderEmail), ("replied_comment_id", reply.id), ("text", value), ("replied_comment_message", reply.text), ("replied_comment_sender_username", senderName), ("replied_comment_payload", reply.data) ] if reply.type == .location || reply.type == .contact { payloadArray.append(("replied_comment_type",reply.typeRaw)) } payload = JSON(dictionaryLiteral: payloadArray) type = .reply self.replyData = nil } self.inputText.clearValue() DispatchQueue.main.async { autoreleasepool{ self.inputText.text = "" self.minInputHeight.constant = 32 self.sendButton.isEnabled = false self.inputText.layoutIfNeeded() } } guard let chatRoomObj = chatRoom else {return} let comment = chatRoomObj.newComment(text: value, payload: payload, type: type) self.postComment(comment: comment) self.addCommentToCollectionView(comment: comment) } }else{ if !self.processingAudio { self.processingAudio = true self.finishRecording() } } // }else{ // self.showNoConnectionToast() // if self.isRecording { // self.cancelRecordVoice() // } // } } func addCommentToCollectionView(comment: QComment) { var section = 0 var item = 0 if comment.sender?.email == Qiscus.client.email { if let lastUid = self.collectionView.messagesId.last?.last { if let lastComment = QComment.comment(withUniqueId: lastUid) { section = self.collectionView.messagesId.count - 1 item = (self.collectionView.messagesId.last?.count)! - 1 if lastComment.date == comment.date && lastComment.sender?.email == comment.sender?.email { var lastGroup = self.collectionView.messagesId.last lastGroup?.append(comment.uniqueId) self.collectionView.messagesId.removeLast() self.collectionView.messagesId.append(lastGroup!) let newIndexPath = IndexPath(row: item + 1, section: section) self.collectionView.performBatchUpdates({ self.collectionView.insertItems(at: [newIndexPath]) }, completion: { (success) in self.collectionView.layoutIfNeeded() self.collectionView.scrollToBottom(true) if lastComment.cellPos == .single { lastComment.updateCellPos(cellPos: .first) }else if lastComment.cellPos == .last { lastComment.updateCellPos(cellPos: .middle) } let lastIndexPath = IndexPath(row: item, section: section) self.collectionView.reloadItems(at: [lastIndexPath]) }) } else { self.collectionView.messagesId.append([comment.uniqueId]) let newIndexPath = IndexPath(row: 0, section: section + 1) comment.updateCellPos(cellPos: .single) self.collectionView.performBatchUpdates({ self.collectionView.insertSections(IndexSet(integer: section + 1)) self.collectionView.insertItems(at: [newIndexPath]) }, completion: { (success) in self.collectionView.layoutIfNeeded() self.collectionView.scrollToBottom(true) }) } } } else { self.collectionView.messagesId.append([comment.uniqueId]) let newIndexPath = IndexPath(row: 0, section: 0) comment.updateCellPos(cellPos: .single) self.collectionView.reloadData() } } } func uploadImage(){ view.endEditing(true) if Qiscus.sharedInstance.connected{ let photoPermissions = PHPhotoLibrary.authorizationStatus() if(photoPermissions == PHAuthorizationStatus.authorized){ self.goToGaleryPicker() }else if(photoPermissions == PHAuthorizationStatus.notDetermined){ PHPhotoLibrary.requestAuthorization({(status:PHAuthorizationStatus) in switch status{ case .authorized: self.goToGaleryPicker() break case .denied: self.showPhotoAccessAlert() break default: self.showPhotoAccessAlert() break } }) }else{ self.showPhotoAccessAlert() } }else{ self.showNoConnectionToast() } } func uploadFromCamera(){ view.endEditing(true) if Qiscus.sharedInstance.connected{ if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == AVAuthorizationStatus.authorized { let photoPermissions = PHPhotoLibrary.authorizationStatus() if(photoPermissions == PHAuthorizationStatus.authorized){ DispatchQueue.main.async(execute: { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.mediaTypes = [(kUTTypeImage as String),(kUTTypeMovie as String)] picker.sourceType = UIImagePickerControllerSourceType.camera self.present(picker, animated: true, completion: nil) }) }else if(photoPermissions == PHAuthorizationStatus.notDetermined){ PHPhotoLibrary.requestAuthorization({(status:PHAuthorizationStatus) in switch status{ case .authorized: DispatchQueue.main.async(execute: { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.mediaTypes = [(kUTTypeImage as String),(kUTTypeMovie as String)] picker.sourceType = UIImagePickerControllerSourceType.camera self.present(picker, animated: true, completion: nil) }) break case .denied: self.showPhotoAccessAlert() break default: self.showPhotoAccessAlert() break } }) }else{ self.showPhotoAccessAlert() } }else{ AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted :Bool) -> Void in if granted { PHPhotoLibrary.requestAuthorization({(status:PHAuthorizationStatus) in switch status{ case .authorized: let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.mediaTypes = [(kUTTypeImage as String),(kUTTypeMovie as String)] picker.sourceType = UIImagePickerControllerSourceType.camera self.present(picker, animated: true, completion: nil) break case .denied: self.showPhotoAccessAlert() break default: self.showPhotoAccessAlert() break } }) }else{ DispatchQueue.main.async(execute: { self.showCameraAccessAlert() }) } }) } }else{ self.showNoConnectionToast() } } @objc func recordVoice(){ self.prepareRecording() } func startRecording(){ let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let time = Double(Date().timeIntervalSince1970) let timeToken = UInt64(time * 10000) let fileName = "audio-\(timeToken).m4a" let audioURL = documentsPath.appendingPathComponent(fileName) print ("audioURL: \(audioURL)") self.recordingURL = audioURL let settings:[String : Any] = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: Float(44100), AVNumberOfChannelsKey: Int(2), AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] Qiscus.uiThread.async {autoreleasepool{ self.recordButton.isHidden = true self.sendButton.isHidden = false self.recordBackground.clipsToBounds = true let inputWidth = self.inputText.frame.width let recorderWidth = inputWidth + 17 self.recordViewLeading.constant = 0 - recorderWidth UIView.animate(withDuration: 0.5, animations: { self.inputText.isHidden = true self.cancelRecordButton.isHidden = false self.view.layoutIfNeeded() }, completion: { success in var timerLabel = self.recordBackground.viewWithTag(543) as? UILabel if timerLabel == nil { timerLabel = UILabel(frame: CGRect(x: 34, y: 5, width: 40, height: 20)) timerLabel!.backgroundColor = UIColor.clear timerLabel!.textColor = UIColor.white timerLabel!.tag = 543 timerLabel!.font = UIFont.systemFont(ofSize: 12) self.recordBackground.addSubview(timerLabel!) } timerLabel!.text = "00:00" var waveView = self.recordBackground.viewWithTag(544) as? QSiriWaveView if waveView == nil { let backgroundFrame = self.recordBackground.bounds waveView = QSiriWaveView(frame: CGRect(x: 76, y: 2, width: backgroundFrame.width - 110, height: 28)) waveView!.waveColor = UIColor.white waveView!.numberOfWaves = 6 waveView!.primaryWaveWidth = 1.0 waveView!.secondaryWaveWidth = 0.75 waveView!.tag = 544 waveView!.layer.cornerRadius = 14.0 waveView!.clipsToBounds = true waveView!.backgroundColor = UIColor.clear self.recordBackground.addSubview(waveView!) } do { self.recorder = nil if self.recorder == nil { self.recorder = try AVAudioRecorder(url: audioURL, settings: settings) } self.recorder?.prepareToRecord() self.recorder?.isMeteringEnabled = true self.recorder?.record() self.sendButton.isEnabled = true self.recordDuration = 0 if self.recordTimer != nil { self.recordTimer?.invalidate() self.recordTimer = nil } self.recordTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(QiscusChatVC.updateTimer), userInfo: nil, repeats: true) self.isRecording = true let displayLink = CADisplayLink(target: self, selector: #selector(QiscusChatVC.updateAudioMeter)) displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) } catch { Qiscus.printLog(text: "error recording") } }) }} } func prepareRecording(){ do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in if allowed { self.startRecording() } else { Qiscus.uiThread.async { autoreleasepool{ self.showMicrophoneAccessAlert() }} } } } catch { Qiscus.uiThread.async { autoreleasepool{ self.showMicrophoneAccessAlert() }} } } @objc func updateTimer(){ if let timerLabel = self.recordBackground.viewWithTag(543) as? UILabel { self.recordDuration += 1 let minutes = Int(self.recordDuration / 60) let seconds = self.recordDuration % 60 var minutesString = "\(minutes)" if minutes < 10 { minutesString = "0\(minutes)" } var secondsString = "\(seconds)" if seconds < 10 { secondsString = "0\(seconds)" } timerLabel.text = "\(minutesString):\(secondsString)" } } @objc func updateAudioMeter(){ if let audioRecorder = self.recorder{ audioRecorder.updateMeters() let normalizedValue:CGFloat = pow(10.0, CGFloat(audioRecorder.averagePower(forChannel: 0)) / 20) Qiscus.uiThread.async {autoreleasepool{ if let waveView = self.recordBackground.viewWithTag(544) as? QSiriWaveView { waveView.update(withLevel: normalizedValue) } }} } } func finishRecording(){ self.recorder?.stop() self.recorder = nil self.recordViewLeading.constant = 8 Qiscus.uiThread.async {autoreleasepool{ UIView.animate(withDuration: 0.5, animations: { self.inputText.isHidden = false self.cancelRecordButton.isHidden = true self.view.layoutIfNeeded() }) { (_) in self.recordButton.isHidden = false self.sendButton.isHidden = true if self.recordTimer != nil { self.recordTimer?.invalidate() self.recordTimer = nil self.recordDuration = 0 } self.isRecording = false self.processingAudio = false } }} if let audioURL = self.recordingURL { var fileContent: Data? fileContent = try! Data(contentsOf: audioURL) let mediaSize = Double(fileContent!.count) / 1024.0 if mediaSize > Qiscus.maxUploadSizeInKB { self.showFileTooBigAlert() return } let fileName = audioURL.lastPathComponent let newComment = self.chatRoom!.newFileComment(type: .audio, filename: fileName, data: fileContent!) self.addCommentToCollectionView(comment: newComment) self.chatRoom!.upload(comment: newComment, onSuccess: { (roomResult, commentResult) in self.postComment(comment: commentResult) }, onError: { (roomResult, commentResult, error) in Qiscus.printLog(text: "Error: \(error)") }) } } @objc func cancelRecordVoice(){ self.recordViewLeading.constant = 8 Qiscus.uiThread.async { autoreleasepool{ UIView.animate(withDuration: 0.5, animations: { self.inputText.isHidden = false self.cancelRecordButton.isHidden = true self.view.layoutIfNeeded() }) { (_) in self.recordButton.isHidden = false self.sendButton.isHidden = true if self.recordTimer != nil { self.recordTimer?.invalidate() self.recordTimer = nil self.recordDuration = 0 } self.isRecording = false } }} } func postFile(filename:String, data:Data? = nil, type:QiscusFileType, thumbImage:UIImage? = nil){ if Qiscus.sharedInstance.connected { let newComment = self.chatRoom!.newFileComment(type: type, filename: filename, data: data, thumbImage: thumbImage) self.addCommentToCollectionView(comment: newComment) self.chatRoom!.upload(comment: newComment, onSuccess: { (roomResult, commentResult) in self.postComment(comment: commentResult) }, onError: { (roomResult, commentResult, error) in Qiscus.printLog(text: "Error: \(error)") }) }else{ self.showNoConnectionToast() } } // MARK: - Back Button class func backButton(_ target: UIViewController, action: Selector) -> UIBarButtonItem{ let backIcon = UIImageView() backIcon.contentMode = .scaleAspectFit let image = Qiscus.image(named: "ic_back")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) backIcon.image = image backIcon.tintColor = QiscusChatVC.currentNavbarTint if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { backIcon.frame = CGRect(x: 0,y: 11,width: 13,height: 22) }else{ backIcon.frame = CGRect(x: 22,y: 11,width: 13,height: 22) } let backButton = UIButton(frame:CGRect(x: 0,y: 0,width: 23,height: 44)) backButton.addSubview(backIcon) backButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) return UIBarButtonItem(customView: backButton) } func setGradientChatNavigation(withTopColor topColor:UIColor, bottomColor:UIColor, tintColor:UIColor){ self.topColor = topColor self.bottomColor = bottomColor self.tintColor = tintColor self.navigationController?.navigationBar.verticalGradientColor(self.topColor, bottomColor: self.bottomColor) self.navigationController?.navigationBar.tintColor = self.tintColor let _ = self.view self.sendButton.tintColor = self.topColor if self.inputText.value == "" { self.sendButton.isEnabled = false } self.attachButton.tintColor = self.topColor self.bottomButton.tintColor = self.topColor self.recordButton.tintColor = self.topColor self.cancelRecordButton.tintColor = self.topColor self.emptyChatImage.tintColor = self.bottomColor } // MARK: - Load DataSource on firstTime func loadData(){ if self.chatRoomId != nil && !self.isPublicChannel { self.chatService.room(withId: self.chatRoomId!, withMessage: self.chatMessage) }else if self.chatUser != nil { self.chatService.room(withUser: self.chatUser!, distincId: self.chatDistinctId, optionalData: self.chatData, withMessage: self.chatMessage) }else if self.chatNewRoomUsers.count > 0 { self.chatService.createRoom(withUsers: self.chatNewRoomUsers, roomName: self.chatTitle!, optionalData: self.chatData, withMessage: self.chatMessage) }else if self.chatRoomUniqueId != nil && self.isPublicChannel { self.chatService.room(withUniqueId: self.chatRoomUniqueId!, title: self.chatTitle!, avatarURL: self.chatAvatarURL, withMessage: self.chatMessage) }else { self.dismissLoading() } } func forward(comment:QComment){ if let delegate = self.delegate { delegate.chatVC?(viewController: self, onForwardComment: comment, data: self.data) } } func info(comment:QComment){ if let delegate = self.delegate { delegate.chatVC?(viewController: self, infoActionComment: comment, data: self.data) } } public func hideInputBar(){ self.inputBarHeight.constant = 0 self.minInputHeight.constant = 0 } open func reply(toComment comment:QComment?){ if comment == nil { Qiscus.uiThread.async { autoreleasepool{ self.linkPreviewTopMargin.constant = 0 UIView.animate(withDuration: 0.65, animations: { self.view.layoutIfNeeded() }, completion: {(_) in if self.inputText.value == "" { self.sendButton.isEnabled = false self.sendButton.isHidden = true self.recordButton.isHidden = false self.linkImage.image = nil } }) }} } else{ Qiscus.uiThread.async {autoreleasepool{ switch comment!.type { case .text: self.linkDescription.text = comment!.text self.linkImageWidth.constant = 0 break case .document: self.linkImage.contentMode = .scaleAspectFill if let file = comment!.file { if QFileManager.isFileExist(inLocalPath: file.localThumbPath){ self.linkImage.loadAsync(fromLocalPath: file.localThumbPath, onLoaded: { (image, _) in self.linkImage.image = image }) } else if QFileManager.isFileExist(inLocalPath: file.localMiniThumbPath){ self.linkImage.loadAsync(fromLocalPath: file.localMiniThumbPath, onLoaded: { (image, _) in self.linkImage.image = image }) } else{ self.linkImage.loadAsync(file.thumbURL, onLoaded: { (image, _) in self.linkImage.image = image }) } self.linkImageWidth.constant = 55 var description = "\(file.filename)\nPDF File" if file.pages > 0 { description = "\(description), \(file.pages) page" } if file.sizeString != "" { description = "\(description), \(file.sizeString)" } self.linkDescription.text = description } break case .video, .image: self.linkImage.contentMode = .scaleAspectFill if let file = comment!.file { if comment!.type == .video || comment!.type == .image { if QFileManager.isFileExist(inLocalPath: file.localThumbPath){ self.linkImage.loadAsync(fromLocalPath: file.localThumbPath, onLoaded: { (image, _) in self.linkImage.image = image }) } else if QFileManager.isFileExist(inLocalPath: file.localMiniThumbPath){ self.linkImage.loadAsync(fromLocalPath: file.localMiniThumbPath, onLoaded: { (image, _) in self.linkImage.image = image }) } else{ self.linkImage.loadAsync(file.thumbURL, onLoaded: { (image, _) in self.linkImage.image = image }) } self.linkImageWidth.constant = 55 } var description = "\(file.filename)\n" if file.sizeString != "" { description = "\(description), \(file.sizeString)" } self.linkDescription.text = file.filename } break case .audio: self.linkImageWidth.constant = 0 if let file = comment!.file { var description = "\(file.filename)\nAUDIO FILE" if file.sizeString != "" { description = "\(description), \(file.sizeString)" } self.linkDescription.text = description } break case .file: self.linkImageWidth.constant = 0 if let file = comment!.file { var description = "\(file.filename)\n\(file.ext.uppercased()) FILE" if file.sizeString != "" { description = "\(description), \(file.sizeString)" } self.linkDescription.text = description } break case .location: let payload = JSON(parseJSON: comment!.data) self.linkImage.contentMode = .scaleAspectFill self.linkImage.image = Qiscus.image(named: "map_ico") self.linkImageWidth.constant = 55 self.linkDescription.text = "\(payload["name"].stringValue) - \(payload["address"].stringValue)" break case .contact: let payload = JSON(parseJSON: comment!.data) self.linkImage.contentMode = .top self.linkImage.image = Qiscus.image(named: "contact") self.linkImageWidth.constant = 55 self.linkDescription.text = "\(payload["name"].stringValue) - \(payload["value"].stringValue)" break case .reply: self.linkDescription.text = comment!.text self.linkImageWidth.constant = 0 break default: break } if let user = self.replyData!.sender { self.linkTitle.text = user.fullname }else{ self.linkTitle.text = comment!.senderName } self.linkPreviewTopMargin.constant = -65 UIView.animate(withDuration: 0.35, animations: { self.view.layoutIfNeeded() if self.lastVisibleRow != nil { self.collectionView.scrollToItem(at: self.lastVisibleRow!, at: .bottom, animated: true) } }, completion: { (_) in if self.inputText.value == "" { self.sendButton.isEnabled = false }else{ self.sendButton.isEnabled = true } self.sendButton.isHidden = false self.recordButton.isHidden = true }) }} } } func didTapActionButton(withData data:JSON){ if Qiscus.sharedInstance.connected{ let postbackType = data["type"] let payload = data["payload"] switch postbackType { case "link": let urlString = payload["url"].stringValue.trimmingCharacters(in: .whitespacesAndNewlines) let urlArray = urlString.components(separatedBy: "/") func openInBrowser(){ if let url = URL(string: urlString) { UIApplication.shared.openURL(url) } } if urlArray.count > 2 { if urlArray[2].lowercased().contains("instagram.com") { var instagram = "instagram://app" if urlArray.count == 4 || (urlArray.count == 5 && urlArray[4] == ""){ let usernameIG = urlArray[3] instagram = "instagram://user?username=\(usernameIG)" } if let instagramURL = URL(string: instagram) { if UIApplication.shared.canOpenURL(instagramURL) { UIApplication.shared.openURL(instagramURL) }else{ openInBrowser() } } }else{ openInBrowser() } }else{ openInBrowser() } break default: let text = data["label"].stringValue let type = "button_postback_response" if let room = self.chatRoom { let newComment = room.newComment(text: text) room.post(comment: newComment, type: type, payload: payload, onSuccess: { }, onError: { (error) in Qiscus.printLog(text: "error \(error)") }) } break } }else{ Qiscus.uiThread.async { autoreleasepool{ self.showNoConnectionToast() }} } } @objc internal func userTyping(_ notification: Notification){ if let userInfo = notification.userInfo { let user = userInfo["user"] as! QUser let typing = userInfo["typing"] as! Bool let room = userInfo["room"] as! QRoom if room.isInvalidated || user.isInvalidated { return } if let currentRoom = self.chatRoom { if currentRoom.isInvalidated { return } if currentRoom.id == room.id { if !processingTyping{ self.userTypingChanged(user: user, typing: typing) } } } } } open func userTypingChanged(user: QUser, typing:Bool){ if user.isInvalidated {return} if !typing { self.subtitleLabel.text = self.subtitleText }else{ guard let room = self.chatRoom else {return} if room.type == .single { self.subtitleLabel.text = "is typing ..." }else{ self.subtitleLabel.text = "\(user.fullname) is typing ..." } } } }
mit
63782303c2f2a1d8c4545cbca9927d4c
44.498757
195
0.501885
5.782563
false
false
false
false
rvanmelle/LeetSwift
Problems.playground/Pages/LFU Cache.xcplaygroundpage/Contents.swift
1
2845
//: [Previous](@previous) /* 460. LFU Cache https://leetcode.com/problems/lfu-cache/#/description Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted. Follow up: Could you do both operations in O(1) time complexity? Example: LFUCache cache = new LFUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.get(3); // returns 3. cache.put(4, 4); // evicts key 1. cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 */ import Foundation import XCTest struct CacheItem { var usageCount: Int = 0 var lastUsed: Date = Date.distantPast var val: Int var key: Int } class LFUCache { var store: [Int:CacheItem] = [:] let capacity: Int init(capacity:Int) { self.capacity = capacity } func get(_ key:Int) -> Int { if let _item = store[key] { var item = _item item.usageCount += 1 item.lastUsed = Date() store[key] = item return item.val } else { return -1 } } func put(_ key:Int, _ value:Int) { if store[key] == nil && store.count >= capacity { let sortedValues = store.values.sorted(by: { (left, right) -> Bool in if left.usageCount == right.usageCount { return left.lastUsed < right.lastUsed } else { return left.usageCount < right.usageCount } }) store.removeValue(forKey: sortedValues.first!.key) } store[key] = CacheItem(usageCount: 0, lastUsed: Date.distantPast, val: value, key: key) } } let cache = LFUCache(capacity:2) cache.put(1, 1) cache.put(2, 2) XCTAssert( cache.get(1) == 1 ) // returns 1 cache.put(3, 3) // evicts key 2 XCTAssert( cache.get(2) == -1 ) // returns -1 (not found) XCTAssert( cache.get(3) == 3 ) // returns 3. cache.put(4, 4) // evicts key 1. XCTAssert( cache.get(1) == -1 ) // returns -1 (not found) XCTAssert( cache.get(3) == 3 ) // returns 3 XCTAssert( cache.get(4) == 4 ) // returns 4 //: [Next](@next)
mit
bfc6598ae88c5729db0ea816ddb9bde5
29.923913
349
0.591564
3.55625
false
false
false
false
adevelopers/prosvet
Prosvet/Common/Models/NetModel.swift
1
2841
// // NetModel.swift // Prosvet // // Created by adeveloper on 19.04.17. // Copyright © 2017 adeveloper. All rights reserved. // import Foundation protocol NetProsvetProtocol { // func npGetList((_ onCompletion: @escaping ([Post])->Void ) func npGetPost(by id:ID,_ onCompletion: @escaping (Post)->Void) } struct NetModel: NetProsvetProtocol { enum errors{ case NO_TOKEN_FILE case NO_TOKEN case FILE_TOKEN_EXCEPTION } let baseUrl:String = Constants.baseUrlApi var token:String { return loadToken() } func loadToken() -> String { let apiKeyFileName = "token.api" let fm = FileManager.default let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) if var path = dir.first?.path { path += "/" + apiKeyFileName if fm.fileExists(atPath: path) { let urlPath = URL(fileURLWithPath: path) do { let apiKey = try String(contentsOf: urlPath, encoding: String.Encoding.utf8) print("api key is: \(apiKey)") return apiKey } catch { print(errors.FILE_TOKEN_EXCEPTION) } } else { print("api key not found! \(errors.NO_TOKEN_FILE)") } } return "demo" } func buildPost() -> Post { let post = Post() return post } func npGetPost(by id:ID, _ onCompletion: @escaping (Post) -> Void) { let api = NetApi.shared var post = Post() api.setBase(self.baseUrl).get(link: "?action=getitem&token=\(token)&id=\(id)"){ json, errors in if !json.isEmpty { let title = json["NAME"] post.title = title.stringValue } onCompletion(post) } } func npGetList(_ onCompletion: @escaping ([Post])->Void ) { var posts = [Post]() var post = Post() NetApi.shared.setBase(self.baseUrl).get(link: "?action=getlist&token=\(token)"){ json, errors in if !json.isEmpty { for (_, item) in json { let title = item["NAME"].stringValue post.id = Int(item["ID"].description)! post.title = title if item["DETAIL_TEXT"].exists() { post.text = item["DETAIL_TEXT"].stringValue } posts.append(post) } onCompletion(posts) } } } }
mit
d52f29fe78c4bf86f2be495e9fab790c
24.585586
96
0.472535
4.640523
false
false
false
false
qinting513/SwiftNote
PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/YahooWeatherRefreshHeader.swift
1
3277
// // YahooWeatherRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/8/2. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit class YahooWeatherRefreshHeader: UIView,RefreshableHeader{ let imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 40, height: 40)) let logoImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 14)) let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(white: 0.0, alpha: 0.25) logoImage.center = CGPoint(x: self.bounds.width/2.0, y: frame.height - 30 - 7.0) imageView.center = CGPoint(x: self.bounds.width/2.0 - 60.0, y: frame.height - 30) imageView.image = UIImage(named: "sun_000000") logoImage.image = UIImage(named: "yahoo_logo") label.frame = CGRect(x: logoImage.frame.origin.x, y: logoImage.frame.origin.y + logoImage.frame.height + 2,width: 200, height: 20) label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 12) label.text = "Last update: 5 minutes ago" addSubview(imageView) addSubview(logoImage) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - RefreshableHeader - func heightForRefreshingState()->CGFloat{ return 60 } func percentUpdateDuringScrolling(_ percent: CGFloat) { let adjustPercent = max(min(1.0, percent),0.0) let index = Int(adjustPercent * 27) let imageName = index < 10 ? "sun_0000\(index)" : "sun_000\(index)" imageView.image = UIImage(named:imageName) } func startTransitionAnimation(){ imageView.image = UIImage(named: "sun_00073") let images = (27...72).map({"sun_000\($0)"}).map({UIImage(named:$0)!}) imageView.animationImages = images imageView.animationDuration = Double(images.count) * 0.02 imageView.animationRepeatCount = 1 imageView.startAnimating() self.perform(#selector(YahooWeatherRefreshHeader.transitionFinihsed), with: nil, afterDelay: imageView.animationDuration) } func transitionFinihsed(){ imageView.stopAnimating() let images = (73...109).map({return $0 < 100 ? "sun_000\($0)" : "sun_00\($0)"}).map({UIImage(named:$0)!}) imageView.animationImages = images imageView.animationDuration = Double(images.count) * 0.03 imageView.animationRepeatCount = 1000000 imageView.startAnimating() } //松手即将刷新的状态 func didBeginRefreshingState(){ imageView.image = nil startTransitionAnimation() } //刷新结束,将要隐藏header func didBeginEndRefershingAnimation(_ result:RefreshResult){ } //刷新结束,完全隐藏header func didCompleteEndRefershingAnimation(_ result:RefreshResult){ imageView.stopAnimating() imageView.animationImages = nil imageView.image = UIImage(named: "sun_000000") NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(YahooWeatherRefreshHeader.transitionFinihsed), object: nil) } }
apache-2.0
41704066c3d3668ce10f7ff1b3252a98
39.25
144
0.657764
4.138817
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/AANavigationBadge.swift
4
2538
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation class AANavigationBadge { fileprivate static var binder = AABinder() fileprivate static let badgeView = UIImageView() fileprivate static var badgeCount = 0 fileprivate static var isBadgeVisible = false fileprivate static var isInited = false class fileprivate func start() { if isInited { return } isInited = true badgeView.image = Imaging.roundedImage(UIColor(rgb: 0xfe0000), size: CGSize(width: 16, height: 16), radius: 8) // badgeView.frame = CGRectMake(16, 22, 32, 16) badgeView.alpha = 0 let badgeText = UILabel() badgeText.text = "0" badgeText.textColor = UIColor.white // badgeText.frame = CGRectMake(0, 0, 32, 16) badgeText.font = UIFont.systemFont(ofSize: 12) badgeText.textAlignment = NSTextAlignment.center badgeView.addSubview(badgeText) UIApplication.shared.windows.first!.addSubview(badgeView) // Bind badge counter binder.bind(Actor.getGlobalState().globalCounter, closure: { (value: JavaLangInteger?) -> () in if let v = value { self.badgeCount = Int(v.intValue) } else { self.badgeCount = 0 } badgeText.text = "\(self.badgeCount)" if (self.isBadgeVisible && self.badgeCount > 0) { self.badgeView.showView() } else if (self.badgeCount == 0) { self.badgeView.hideView() } badgeText.frame = CGRect(x: 0, y: 0, width: 128, height: 16) badgeText.sizeToFit() if badgeText.frame.width < 8 { self.badgeView.frame = CGRect(x: 16, y: 22, width: 16, height: 16) } else { self.badgeView.frame = CGRect(x: 16, y: 22, width: badgeText.frame.width + 8, height: 16) } badgeText.frame = self.badgeView.bounds }) } class func showBadge() { if (AADevice.isiPad) { return } start() isBadgeVisible = true if badgeCount > 0 { self.badgeView.showView() } } class func hideBadge() { if (AADevice.isiPad) { return } start() isBadgeVisible = false self.badgeView.hideView() } }
agpl-3.0
33e6107f7afd5cbdfb7684cab5a97fc2
29.578313
118
0.536643
4.665441
false
false
false
false
AlexDenisov/sgl
sgl/Specs/Collections/array/array_reverse_iterator_spec.swift
1
5274
// // array_reverse_iterator_spec.swift // sgl // // Created by AlexDenisov on 7/27/14. // Copyright (c) 2014 AlexDenisov. All rights reserved. // import Foundation import Sleipnir class array_reverse_iterator_spec : SleipnirSpec { typealias SUTArray = array<Int> typealias SUTIterator = SUTArray.reverse_iterator var spec : () = describe("array reverse iterator") { var subject: SUTArray! var iterator: SUTIterator = SUTIterator(nil) beforeEach { subject = SUTArray(1, 3, 5, 7) } describe("methods") { it("rbegin()") { expect(subject.rbegin().value()).to(equal(7)) } it("rend()") { expect(subject.rend().value()).to(beNil()) } } describe("arithmetic") { context("increment") { beforeEach { iterator = subject.rbegin() } it("prefix") { expect((++iterator).value()).to(equal(5)) expect(iterator.value()).to(equal(5)) } it("postfix") { expect((iterator++).value()).to(equal(7)) expect(iterator.value()).to(equal(5)) } } context("positive contant addition") { beforeEach { iterator = subject.rbegin() } it("postfix") { expect((iterator + 2).value()).to(equal(3)) } it("prefix") { expect((2 + iterator).value()).to(equal(3)) } it("assignment") { iterator += 2 expect(iterator.value()).to(equal(3)) } } context("negative contant addition") { beforeEach { iterator = subject.rbegin() + 2 } it("postfix") { expect((iterator + -2).value()).to(equal(7)) } it("prefix") { expect((-2 + iterator).value()).to(equal(7)) } it("assignment") { iterator += -2 expect(iterator.value()).to(equal(7)) } } context("decrement") { beforeEach { iterator = subject.rend() } it("prefix") { expect((--iterator).value()).to(equal(1)) expect(iterator.value()).to(equal(1)) } it("postfix") { expect((iterator--).value()).to(beNil()) expect(iterator.value()).to(equal(1)) } } context("positive constant subtraction") { beforeEach { iterator = subject.rend() } it("postfix") { expect((iterator - 2).value()).to(equal(3)) } it("prefix") { expect((2 - iterator).value()).to(equal(3)) } it("assignment") { iterator -= 2 expect(iterator.value()).to(equal(3)) } } context("negative constant subtraction") { beforeEach { iterator = subject.rend() - 3 } it("postfix") { expect((iterator - -2).value()).to(equal(1)) } it("prefix") { expect((-2 - iterator).value()).to(equal(1)) } it("assignment") { iterator -= -2 expect(iterator.value()).to(equal(1)) } } } describe("equality") { it("rbegin iterators equal") { var result = subject.rbegin() == subject.rbegin() expect(result).to(beTrue()) } it("rbegin + size equal to rend") { var result = (subject.rbegin() + subject.size()) == subject.rend() expect(result).to(beTrue()) } it("rend iterators equal") { var result = subject.rend() == subject.rend() expect(result).to(beTrue()) } } } }
mit
0325f911936218231118b0d4fcf6d866
27.508108
82
0.33978
5.814774
false
false
false
false
jandro-es/Evergreen
Carthage/Checkouts/Freddy/Tests/JSONTests.swift
1
1734
// // JSONTests.swift // Freddy // // Created by David House on 1/14/16. // Copyright © 2016 Big Nerd Ranch. All rights reserved. // import XCTest import Freddy class JSONTests: XCTestCase { var sampleData:NSData! override func setUp() { super.setUp() let testBundle = NSBundle(forClass: JSONSubscriptTests.self) guard let data = testBundle.URLForResource("sample", withExtension: "JSON").flatMap(NSData.init) else { XCTFail("Could not read sample data from test bundle") return } sampleData = data } func testInitializingFromData() { do { _ = try JSON(data: sampleData) } catch { XCTFail("Could not parse sample JSON: \(error)") return } } // TODO: This test currently exposes an error in the Parser func DoNotRuntestInitializingFromEmptyData() { do { _ = try JSON(data: NSData()) } catch { XCTFail("Could not parse empty data: \(error)") return } } func testInitializingFromString() { let jsonString = "{ \"slashers\": [\"Jason\",\"Freddy\"] }" do { _ = try JSON(jsonString: jsonString) } catch { XCTFail("Could not parse JSON from string: \(error)") return } } // TODO: This test currently exposes an error in the Parser func DoNotRuntestInitializingFromEmptyString() { do { _ = try JSON(jsonString: "") } catch { XCTFail("Could not parse JSON from string: \(error)") return } } }
apache-2.0
7a41a2de87394c0dceca4d9fcb74fc87
23.771429
111
0.532602
4.840782
false
true
false
false
michaelsabo/hammer
HammerTests/Helpers/MockTagService.swift
1
1269
// // MockTagService.swift // Hammer // // Created by Mike Sabo on 11/7/15. // Copyright © 2015 FlyingDinosaurs. All rights reserved. // import Foundation import SwiftyJSON class MockTagService: TagService { let tagsResponse = TagsResponse(json: JSON(data: TestingHelper.jsonFromFile("tags"))) let taggedResponse = Tag(json: JSON(data: TestingHelper.jsonFromFile("tag"))) override func getAllTags() -> SignalProducer<TagsResponse, NSError> { return SignalProducer { observer, _ in observer.sendNext(self.tagsResponse) observer.sendCompleted() } } override func getTagsForGifId(_ id: Int) -> SignalProducer<TagsResponse, NSError> { return SignalProducer { observer, _ in if id == 999 { observer.sendNext(TagsResponse()) observer.sendCompleted() return } let stubbedTags = TagsResponse() for var i = 0; i < 3; i++ { stubbedTags.tags.append(self.tagsResponse.tags[i]) } observer.sendNext(stubbedTags) observer.sendCompleted() } } override func tagGifWith(id _: Int, tag _: String) -> SignalProducer<Tag, NSError> { return SignalProducer { observer, _ in observer.sendNext(self.taggedResponse) observer.sendCompleted() } } }
mit
9c5befc72be4dc406a0f232a90856d30
27.177778
87
0.670347
4.090323
false
false
false
false
Draveness/RbSwift
Sources/Duration+Comparable.swift
2
1268
// // Duration+Comparable.swift // RbSwift // // Created by draveness on 19/03/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation // MARK: - Comparable extension Duration: Comparable, Equatable { /// Returns a Boolean value indicating whether the value of the first /// argument is less than that of the second argument. /// /// This function is the only requirement of the `Comparable` protocol. The /// remainder of the relational operator functions are implemented by the /// standard library for any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func <(lhs: Duration, rhs: Duration) -> Bool { return lhs.toSeconds < rhs.toSeconds } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: Duration, rhs: Duration) -> Bool { return lhs.toSeconds == rhs.toSeconds } }
mit
7e57084162d9214452ce3e7a443a8978
31.487179
79
0.630624
4.223333
false
false
false
false
kalanyuz/SwiftR
CommonSource/common/PrismColor.swift
1
4251
// // SRColor+Lines.swift // NativeSigP // // Created by Kalanyu Zintus-art on 10/22/15. // Copyright © 2017 KalanyuZ. All rights reserved. // open class PrismColor { required public init() { } open subscript(index: Int) -> SRColor { let colorIndex = index%10 var returnColor : SRColor switch colorIndex { case 0: returnColor = SRColor(red: 0.6350, green: 0.0780, blue: 0.1840, alpha: 1.0) case 1: returnColor = SRColor(red: 0.3010, green: 0.7450, blue: 0.9930, alpha: 1.0) case 2: returnColor = SRColor(red: 0.9290, green: 0.6940, blue: 0.1250, alpha: 1.0) case 3: returnColor = SRColor(red: 0.4940, green: 0.1840, blue: 0.5560, alpha: 1.0) case 4: returnColor = SRColor(red: 0.4660, green: 0.6740, blue: 0.1880, alpha: 1.0) case 5: returnColor = SRColor(red: 0.8500, green: 0.3250, blue: 0.0980, alpha: 1.0) case 6: returnColor = SRColor(red: 0, green: 0.4470, blue: 0.7410, alpha: 1.0) default: returnColor = SRColor(red: 1, green: 1, blue: 1, alpha: 1.0) break } return returnColor } /* 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840 0 0.4470 0.7410 0.8500 0.3250 0.0980 */ }
apache-2.0
e6f0e0073c1ea91244e377a50110a38d
29.357143
87
0.499765
2.397067
false
false
false
false
andrewcar/hoods
Project/hoods/hoods/User.swift
1
829
// // User.swift // hoods // // Created by Andrew Carvajal on 6/20/18. // Copyright © 2018 YugeTech. All rights reserved. // import UIKit class User { var displayName: String var birthdate: String? var email: String? var canonicalUsername: String? var spotifyAccountType: String? var profilePicture: UIImage? var country: String? init(displayName: String, birthdate: String?, email: String? , canonicalUsername: String?, spotifyAccountType: String?, profilePicture: UIImage?, country: String?) { self.displayName = displayName self.birthdate = birthdate self.email = email self.canonicalUsername = canonicalUsername self.spotifyAccountType = spotifyAccountType self.profilePicture = profilePicture self.country = country } }
mit
5d7ff4646b50d5ecde7fb434a174f176
27.551724
169
0.682367
4.52459
false
false
false
false
GYLibrary/A_Y_T
GYVideo/GYVideo/ViewModel/BaseViewModel.swift
1
1218
// // BaseViewModel.swift // GYVideo // // Created by ZGY on 2017/2/8. // Copyright © 2017年 GYJade. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2017/2/8 13:52 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit import GYNetWorking typealias SuccessBlock = (Any) -> Void typealias ErrorCodeBlock = (Any) -> Void typealias FailureBlock = (Void) -> Void typealias NetWorkBlock = (Bool) -> Void class BaseViewModel: NSObject { var returnBlock:SuccessBlock? var errorBlock: ErrorCodeBlock? var failureblock: FailureBlock? init(_ returnBlock: SuccessBlock?, errorBlock: ErrorCodeBlock?,failureblock: FailureBlock?) { super.init() self.returnBlock = returnBlock self.errorBlock = errorBlock self.failureblock = failureblock } // static func setBlock(_ returnBlock: SuccessBlock?, errorBlock: ErrorCodeBlock?,failureBlock: FailureBlock?) { // self.returnBlock = returnBlock // // } }
mit
ae59923ac24ee1c24b4590760572ce8d
24.851064
115
0.651852
3.832808
false
false
false
false
adamnemecek/WebMIDIKit
Sources/WebMIDIKit/MIDIStatus.swift
1
1237
import CoreMIDI public enum MIDIStatus: Int { /// Default empty status case nothing = 0 /// Note off is something resembling a keyboard key release case noteOff = 8 /// Note on is triggered when a new note is created, or a keyboard key press case noteOn = 9 /// Polyphonic aftertouch is a rare MIDI control on controllers in which /// every key has separate touch sensing case polyphonicAftertouch = 10 /// Controller changes represent a wide range of control types including volume, /// expression, modulation and a host of unnamed controllers with numbers case controllerChange = 11 /// Program change messages are associated with changing the basic character of the sound preset case programChange = 12 /// A single aftertouch for all notes on a given channel /// (most common aftertouch type in keyboards) case channelAftertouch = 13 /// A pitch wheel is a common keyboard control that allow for a pitch to be /// bent up or down a given number of semitones case pitchWheel = 14 /// System commands differ from system to system case systemCommand = 15 init?(packet: MIDIPacket) { self.init(rawValue: Int(packet.data.0 >> 4)) } }
mit
ce9c18336d7bba0c54af9665a05e3653
40.233333
100
0.703314
4.81323
false
false
false
false
Sharelink/Bahamut
Bahamut/BahamutUIKit/Animation/UIAnimationHelper.swift
1
7379
// // UIAnimationHelper.swift // iDiaries // // Created by AlexChow on 15/12/6. // Copyright © 2015年 GStudio. All rights reserved. // import UIKit import QuartzCore extension UIView:CAAnimationDelegate { func startFlash(_ duration:TimeInterval = 0.8) { UIAnimationHelper.flashView(self, duration: duration) } func stopFlash() { UIAnimationHelper.stopFlashView(self) } func shakeAnimationForView(_ repeatTimes:Float = 3,completion:AnimationCompletedHandler! = nil) { UIAnimationHelper.shakeAnimationForView(self,repeatTimes:repeatTimes,completion: completion) } func animationMaxToMin(_ duration:Double = 0.2,maxScale:CGFloat = 1.1,repeatCount:Float = 0,completion:AnimationCompletedHandler! = nil) { UIAnimationHelper.animationMaxToMin(self,duration:duration,maxScale: maxScale,repeatCount:repeatCount,completion: completion) } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let handler = UIAnimationHelper.instance.animationCompleted.removeValue(forKey: self) { handler() } } } typealias AnimationCompletedHandler = ()->Void class UIAnimationHelper { fileprivate var animationCompleted = [UIView:AnimationCompletedHandler]() fileprivate static let instance = UIAnimationHelper() static func animationPageCurlView(_ view:UIView,duration:TimeInterval,completion:AnimationCompletedHandler! = nil){ // 获取到当前的View let viewLayer = view.layer // 设置动画 let animation = CATransition() animation.duration = duration animation.type = convertToCATransitionType("pageCurl") animation.subtype = CATransitionSubtype.fromBottom // 添加上动画 viewLayer.add(animation, forKey: nil) playAnimation(view, animation: animation, key: "animationPageCurl", completion: completion) } static func shakeAnimationForView(_ view:UIView,repeatTimes:Float,completion:AnimationCompletedHandler! = nil){ // 获取到当前的View let viewLayer = view.layer // 获取当前View的位置 let position:CGPoint = viewLayer.position // 移动的两个终点位置 let a = CGPoint(x: position.x + 10, y: position.y) let b = CGPoint(x: position.x - 10, y: position.y) // 设置动画 let animation = CABasicAnimation(keyPath: "position") // 设置运动形式 animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) // 设置开始位置 animation.fromValue = NSValue(cgPoint: a) // 设置结束位置 animation.toValue = NSValue(cgPoint: b) // 设置自动反转 animation.autoreverses = true // 设置时间 animation.duration = 0.05 // 设置次数 animation.repeatCount = repeatTimes // 添加上动画 viewLayer.add(animation, forKey: nil) playAnimation(view, animation: animation, key: "shakeAnimationForView", completion: completion) } static func flyToTopForView(_ startPosition:CGPoint,view:UIView,completion:AnimationCompletedHandler! = nil){ // 获取到当前的View let viewLayer = view.layer // 获取当前View的位置 let position:CGPoint = viewLayer.position // 移动的两个终点位置 let a = startPosition let b = CGPoint(x: position.x, y: -10) // 设置动画 let animation = CABasicAnimation(keyPath: "position") // 设置运动形式 animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) // 设置开始位置 animation.fromValue = NSValue(cgPoint: a) // 设置结束位置 animation.toValue = NSValue(cgPoint: b) // 设置时间 animation.duration = 1 playAnimation(view, animation: animation, key: "flyToTopForView", completion: completion) } static func animationMaxToMin(_ view:UIView,duration:Double,maxScale:CGFloat,repeatCount:Float = 0,completion:AnimationCompletedHandler! = nil){ let animation = CABasicAnimation(keyPath: "transform.scale") animation.fromValue = 1.0 animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) animation.toValue = maxScale animation.duration = duration animation.repeatCount = repeatCount animation.autoreverses = true animation.isRemovedOnCompletion = true animation.fillMode = CAMediaTimingFillMode.forwards playAnimation(view, animation: animation, key: "animationMaxToMin", completion: completion) } static func playAnimation(_ view:UIView,animation:CAAnimation,key:String? = nil,completion:AnimationCompletedHandler! = nil) { animation.delegate = view if let handler = completion { UIAnimationHelper.instance.animationCompleted[view] = handler } view.layer.add(animation, forKey: key) } static func flashView(_ view:UIView,duration:TimeInterval = 0.8,autoStop:Bool = false,stopAfterMs:UInt64 = 3000,completion:AnimationCompletedHandler! = nil) { let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 1.0 animation.toValue = 0.0 animation.autoreverses = true animation.duration = duration animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.timingFunction=CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) view.layer.add(animation, forKey: "Flash") if autoStop{ let time = DispatchTime.now() + Double(NSNumber(value: NSEC_PER_MSEC * stopAfterMs as UInt64).int64Value) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { stopFlashView(view) completion?() }) } } static func stopFlashView(_ view:UIView) { view.layer.removeAnimation(forKey: "Flash") } } extension DispatchQueue{ func afterMS(_ ms:UInt64,handler:@escaping ()->Void){ let time = DispatchTime.now() + Double(NSNumber(value: NSEC_PER_MSEC * ms as UInt64).int64Value) / Double(NSEC_PER_SEC) self.asyncAfter(deadline: time,execute: handler) } static func background() -> DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.background) } } extension CAAnimation{ func setStorePropertyOnComplete() { self.isRemovedOnCompletion = false self.fillMode = CAMediaTimingFillMode.forwards } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToCATransitionType(_ input: String) -> CATransitionType { return CATransitionType(rawValue: input) }
mit
4397f6dbbca040eaee708af02086d563
31.678899
162
0.642055
4.899587
false
false
false
false
lennet/bugreporter
Bugreporter/Helper/AttachmentManager.swift
1
4735
// // AttachmentManager.swift // Bugreporter // // Created by Leo Thomas on 15/07/16. // Copyright © 2016 Leonard Thomas. All rights reserved. // import Foundation import Cocoa struct Attachment { var url: URL var type: AttachmentType var title: String { return url.lastPathComponent } var name: String { return title.replacingOccurrences(of: ".\(type.fileExtension)", with: "") } var thumbURL: URL { switch type { case .image: return url case.video: var thumbURL = url.deletingPathExtension() thumbURL.appendPathExtension("thumb") return thumbURL } } var data: Data? { do { return try Data(contentsOf: url) } catch { print("Retrieving data for url \(url) failed with error: \(error)") return nil } } static func ==(left: Attachment, right: Attachment) -> Bool { guard left.name == right.name else { return false } guard left.type == right.type else { return false } guard left.url == right.url else { return false } return true } } extension Attachment: Hashable { var hashValue: Int { return url.hashValue + type.hashValue } } extension Attachment { var thumb: NSImage? { return NSImage(contentsOf: thumbURL) } } enum AttachmentType { case image case video var fileExtension: String { get { switch self { case .image: return "png" case .video: return "mp4" } } } static var all: [AttachmentType] { get { return [.image, .video] } } } class AttachmentManager { static var documentURL: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[0] }() class func getAll() -> [Attachment] { var result: [Attachment] = [] do { let documentsPath = documentURL.path let allFiles = try FileManager.default.contentsOfDirectory(atPath: documentsPath) for fileName in allFiles { let fileURL = URL(fileURLWithPath: documentsPath + "/" + fileName) if let attachment = getAttachment(for: fileURL) { result.append(attachment) } } } catch { print("Error occured while fetching files: \(error)") } return result } /// Returns an optional attachment with the correct for url (if its exists) /// /// - parameter url: url of the wanted attachment class private func getAttachment(for url: URL) -> Attachment? { guard FileManager.default.fileExists(atPath: url.path) else { return nil } for type in AttachmentType.all { if url.pathExtension == type.fileExtension { return Attachment(url: url, type: type) } } return nil } /// Saves data to disk /// /// - parameter data /// - parameter name: the name for the new file without extension /// - parameter type: the type of the new file /// /// - returns: whether the operation was successfull or not @discardableResult class func save(data: Data, name: String, type: AttachmentType) -> Bool { let url = getURL(for: type, name: name) do { try data.write(to: url) return true } catch { print("Could not save Attachment for type:\(type) with error: \(error)") return false } } /// Deletes attachment from Disk /// /// - parameter attachment: the attachment which should be deleted /// /// - returns: whether the operation was successfull or not @discardableResult class func delete(attachment: Attachment) -> Bool { var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: attachment.url.path, isDirectory: &isDirectory), !isDirectory.boolValue else { // file doesn't exist or is directory return false } do { try FileManager.default.removeItem(at: attachment.url) return true } catch { return false } } class func getURL(for type: AttachmentType, name: String) -> URL { return documentURL.appendingPathComponent("\(name).\(type.fileExtension)") } }
mit
59513ac9665c3440579cd5d23e7b71fa
24.451613
131
0.549218
4.972689
false
false
false
false
kongtomorrow/WatchTransition
WatchTransition/ViewController.swift
1
18702
// // ViewController.swift // WatchTransition // // Created by Ken Ferry on 4/27/15. // Copyright (c) 2015 Understudy. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var crownSlider: UISlider! = nil @IBAction func crownSliderDidChange(sender: UISlider) { masterTiming = Double(crownSlider.value) } var masterTiming : Double = 0 { didSet { updateForAnimation() } } @IBOutlet var contentView: UIView! @IBOutlet var clockTruthView: UIImageView! @IBOutlet var otherAppsView : UIView! @IBOutlet var tickLabels : [UILabel]! @IBOutlet var complicationViews : [UIImageView]! var positioningLayer : CALayer! // the "mini" representation when it's on the home screen var watchBezelMiniLayer : CALayer! var hourHandMiniLayer : CAShapeLayer! var minuteHandMiniLayer : CAShapeLayer! var secondHandMiniLayer : CALayer! var orangeCapMiniLayer : CALayer! var miniLayers : [CALayer] { return [watchBezelMiniLayer, hourHandMiniLayer, minuteHandMiniLayer, secondHandMiniLayer, secondHandMiniLayer, orangeCapMiniLayer] } var maskLayer : CALayer! var dialLayer : CAShapeLayer! var hourHandLayer : CAShapeLayer! var minuteHandLayer : CAShapeLayer! var whiteCapLayer : CALayer! var secondHandLayer : CALayer! var orangeCapLayer : CALayer! var blackCapLayer : CALayer! override func viewDidLoad() { super.viewDidLoad() makeLayers() let spec = KFTunableSpec(named:"MainSpec") view.addGestureRecognizer(KFTunableSpec(named:"MainSpec").twoFingerTripleTapGestureRecognizer()) let configAffectingSpecKeys = [ "ClockRadius", "LineWidth", "LargeTickWidth", "SmallTickWidth", "SecondHandOverhang", "PatternPhase", "SecondHandMiniThickness", "OarCurveLen" ] for key in configAffectingSpecKeys { spec.withDoubleForKey(key, owner: self) { (owner, _) in let props = spec.dictionaryRepresentation() as! Dictionary<String,CGFloat> owner.configureLayers() } } masterTiming = Double(crownSlider.value) let anim = CABasicAnimation(keyPath:"transform.rotation") anim.fromValue = 0 anim.toValue = 2*M_PI anim.duration = 60; anim.repeatCount = 1e100; secondHandLayer.addAnimation(anim, forKey: "tick") secondHandMiniLayer.addAnimation(anim, forKey: "tick") } func makeLayers() { positioningLayer = CALayer(superlayer: contentView.layer, position: centerScreen) watchBezelMiniLayer = CALayer(superlayer: positioningLayer, backgroundColor:.whiteColor()) hourHandMiniLayer = CAShapeLayer(superlayer:positioningLayer, fillColor:.blackColor()) minuteHandMiniLayer = CAShapeLayer(superlayer:positioningLayer, fillColor:.blackColor()) secondHandMiniLayer = CALayer(superlayer: positioningLayer, backgroundColor: secondHandColor) orangeCapMiniLayer = CALayer(superlayer: positioningLayer, backgroundColor: secondHandColor) maskLayer = CALayer(superlayer: positioningLayer, backgroundColor: UIColor.blackColor()) dialLayer = CAShapeLayer(superlayer:maskLayer, strokeColor:.whiteColor()) hourHandLayer = CAShapeLayer(superlayer:maskLayer, fillColor:hourHandColor) minuteHandLayer = CAShapeLayer(superlayer:maskLayer, fillColor:minuteHandColor) whiteCapLayer = CALayer(superlayer: maskLayer, backgroundColor: .whiteColor()) secondHandLayer = CALayer(superlayer: maskLayer, backgroundColor: secondHandColor) orangeCapLayer = CALayer(superlayer: maskLayer, backgroundColor: secondHandColor) blackCapLayer = CALayer(superlayer: maskLayer, backgroundColor: .blackColor()) } // this is separated from makeLayers because we want to use KFTunableSpec to change design values. // we rerun this method whenever that happens. func configureLayers() { let spec = KFTunableSpec(named:"MainSpec") let outsideRadius = CGFloat(spec.doubleForKey("ClockRadius")) let tickThickness = CGFloat(spec.doubleForKey("LineWidth")) let bigTickWidth = CGFloat(spec.doubleForKey("LargeTickWidth")) let smallTickWidth = CGFloat(spec.doubleForKey("SmallTickWidth")) let secondHandOverhang = CGFloat(spec.doubleForKey("SecondHandOverhang")) let tickPatternPhase = CGFloat(spec.doubleForKey("PatternPhase")) let secondHandMiniThickness = CGFloat(spec.doubleForKey("SecondHandMiniThickness")) let pi = CGFloat(M_PI) let watchFaceBounds = CGRect(center: CGPointZero, width: 2 * outsideRadius, height: 2 * outsideRadius) // these are random, where the watch hands point. let hourHandRotationXForm = CGAffineTransformMakeRotation(0.66 * 2 * pi) let minuteHandRotationXForm = CGAffineTransformMakeRotation(0.25 * 2 * pi) // whiteDiskLayer watchBezelMiniLayer.bounds = watchFaceBounds watchBezelMiniLayer.cornerRadius = watchFaceBounds.size.height/2 // hourHandMiniLayer let minuteHandLength = outsideRadius - tickThickness - 0.5 /* 0.5 == half a point == 1 pixel is taken visually from the design */ let hourHandLength = minuteHandLength * 2 / 3 let handleLen = CGFloat(7) let handleThickness : CGFloat = 2 let miniBladeThickness : CGFloat = 8 let bladeThickness : CGFloat = 6 hourHandMiniLayer.path = OarShapedBezier(handleLength: handleLen, totalLength: hourHandLength, handleThickness: handleThickness, bladeThickness: miniBladeThickness) hourHandMiniLayer.anchorPoint = CGPoint(x: 0.5, y: 0.0) hourHandMiniLayer.setAffineTransform(hourHandRotationXForm) // minuteHandMiniLayer minuteHandMiniLayer.path = OarShapedBezier(handleLength: handleLen, totalLength: minuteHandLength, handleThickness: handleThickness, bladeThickness: miniBladeThickness) minuteHandMiniLayer.anchorPoint = CGPoint(x: 0.5, y: 0.0) minuteHandMiniLayer.setAffineTransform(minuteHandRotationXForm) // secondHandMiniLayer func handRect(#thickness:CGFloat, #length:CGFloat, overhang:CGFloat = 0)->CGRect { return CGRect(x: -thickness/2, y: -overhang, width: thickness, height: length) } let secondHandMiniLength = minuteHandLength + secondHandOverhang secondHandMiniLayer.bounds = handRect(thickness:secondHandMiniThickness, length:secondHandMiniLength, overhang:secondHandOverhang) secondHandMiniLayer.anchorPoint = CGPoint(x: 0.5, y: secondHandOverhang / secondHandMiniLength) // orangeCapMiniLayer let orangeCapMiniLayerRadius = CGFloat(5) orangeCapMiniLayer.bounds = CGRect(center: CGPointZero, width: 2 * orangeCapMiniLayerRadius, height: 2 * orangeCapMiniLayerRadius) orangeCapMiniLayer.cornerRadius = orangeCapMiniLayerRadius // that's it for the mini representation // dialLayer let radiusToTickMiddle = outsideRadius - tickThickness/2 let tickMiddleCircumference = pi * 2 * radiusToTickMiddle let tickNominalGapWidth = tickMiddleCircumference / 60 let tickBigToSmallGapWidth = tickNominalGapWidth - bigTickWidth/2 - smallTickWidth/2 let tickSmalToSmallGapWidth = tickNominalGapWidth - smallTickWidth let dialRotation = pi/2 + 2*pi*tickPatternPhase/tickMiddleCircumference let tickPattern : [NSNumber] = [ bigTickWidth, tickBigToSmallGapWidth, smallTickWidth, tickSmalToSmallGapWidth, smallTickWidth, tickSmalToSmallGapWidth, smallTickWidth, tickSmalToSmallGapWidth, smallTickWidth, tickBigToSmallGapWidth] dialLayer.path = UIBezierPath(ovalInRect:CGRect(center: CGPointZero, width: radiusToTickMiddle * 2, height: radiusToTickMiddle * 2)).CGPath dialLayer.bounds = watchFaceBounds dialLayer.lineWidth = tickThickness dialLayer.setAffineTransform(CGAffineTransformMakeRotation(-dialRotation)) dialLayer.lineDashPattern = tickPattern // hourHandLayer hourHandLayer.path = OarShapedBezier(handleLength: handleLen, totalLength: hourHandLength, handleThickness: handleThickness, bladeThickness: bladeThickness) hourHandLayer.anchorPoint = CGPoint(x: 0.5, y:0) hourHandLayer.setAffineTransform(hourHandRotationXForm) hourHandLayer.shadowPath = hourHandLayer.path hourHandLayer.shadowOpacity = 1 hourHandLayer.shadowOffset = CGSizeZero // minuteHandLayer minuteHandLayer.path = OarShapedBezier(handleLength: handleLen, totalLength: minuteHandLength, handleThickness: handleThickness, bladeThickness: bladeThickness) minuteHandLayer.anchorPoint = CGPoint(x: 0.5, y:0) minuteHandLayer.setAffineTransform(minuteHandRotationXForm) minuteHandLayer.shadowPath = minuteHandLayer.path minuteHandLayer.shadowOpacity = 1 minuteHandLayer.shadowOffset = CGSizeZero // whiteCapLayer whiteCapLayer.bounds = CGRectMake(-3, -3, 6, 6) whiteCapLayer.cornerRadius = 3 // secondHandLayer let secondHandLength = outsideRadius + secondHandOverhang let secondHandThickness : CGFloat = 1 secondHandLayer.bounds = handRect(thickness:secondHandThickness, length:secondHandLength, overhang:secondHandOverhang) secondHandLayer.anchorPoint = CGPoint(x: 0.5, y: secondHandOverhang / secondHandLength) // orangeCapLayer orangeCapLayer.bounds = CGRectMake(-2, -2, 4, 4) orangeCapLayer.cornerRadius = 2 // blackCapLayer blackCapLayer.bounds = CGRectMake(-1, -1, 2, 2) blackCapLayer.cornerRadius = 1 } func updateForAnimation() { CATransaction.setAnimationDuration(0) // the start times and end times of various separate animations // the curves here aren't real, since we're driving our animation entirely through a slider let blackCircleGrowthRange = 0.0..<0.5 let rotaryDialRange = 0.6...0.95 let scaleAllContentRange = 0.0..<1.0 let complicationsScaleRange = 0.86..<1.0 // blackCircleGrowth animation switch progressInRange(blackCircleGrowthRange, masterTiming) { case .Before: maskLayer.masksToBounds = false maskLayer.backgroundColor = nil for layer in miniLayers { layer.hidden = false } case let .During(progress): maskLayer.masksToBounds = true maskLayer.backgroundColor = UIColor.blackColor().CGColor maskLayer.bounds = CGRectApplyAffineTransform(dialLayer.bounds, CGAffineTransformMakeScale(progress, progress)) maskLayer.cornerRadius = maskLayer.bounds.size.width/2 for layer in miniLayers { layer.hidden = false } case .After: maskLayer.masksToBounds = false maskLayer.backgroundColor = nil maskLayer.bounds = dialLayer.bounds for layer in miniLayers { layer.hidden = true } } // showing the watch dial as a rotary sweep switch progressInRange(rotaryDialRange, masterTiming) { case .Before: dialLayer.hidden = true for label in tickLabels { label.hidden = true } case let .During(progress): dialLayer.hidden = false dialLayer.strokeEnd = progress for i in 0..<tickLabels.count { let ithAnimRange = (Double(i)/12)..<((Double(i)+0.7)/12) switch progressInRange(ithAnimRange, Double(progress)) { case .Before: tickLabels[i].hidden = true case let .During(prog): tickLabels[i].hidden = false tickLabels[i].transform = CGAffineTransformMakeScale(prog, prog) case .After: tickLabels[i].hidden = false tickLabels[i].transform = CGAffineTransformIdentity } } case .After: dialLayer.hidden = false dialLayer.strokeEnd = 1.0 for i in 0..<tickLabels.count { tickLabels[i].hidden = false tickLabels[i].transform = CGAffineTransformIdentity } } // zooming in on everything // turns out we need two separate scalings – the other apps need to zoom in and move offscreen faster than the watch app for the effect to look correct. let startScaleForMiniWatch = KFTunableSpec(named: "MainSpec").doubleForKey("MinScale") let contentScaleRange = startScaleForMiniWatch...1.0 let otherAppsScaleRange = 1.0...5.0 switch progressInRange(scaleAllContentRange, masterTiming) { case .Before: let contentScale = CGFloat(contentScaleRange.start) contentView.transform = CGAffineTransformMakeScale(contentScale, contentScale) otherAppsView.transform = CGAffineTransformIdentity case let .During(progress): func linearInterpolate(time:CGFloat, interval:ClosedInterval<Double>)->CGFloat { return CGFloat(interval.start + Double(time) * (interval.end - interval.start)) } let contentScale = linearInterpolate(progress, contentScaleRange) contentView.transform = CGAffineTransformMakeScale(contentScale, contentScale) let otherAppsScale = linearInterpolate(progress, otherAppsScaleRange) otherAppsView.transform = CGAffineTransformMakeScale(otherAppsScale, otherAppsScale) case .After: contentView.transform = CGAffineTransformIdentity let otherAppsScale = CGFloat(otherAppsScaleRange.end) otherAppsView.transform = CGAffineTransformMakeScale(otherAppsScale, otherAppsScale) } // showing the complications switch progressInRange(complicationsScaleRange, masterTiming) { case .Before: for view in complicationViews { view.hidden = true } case let .During(progress): for view in complicationViews { view.hidden = false view.transform = CGAffineTransformMakeScale(progress, progress) } case .After: for view in complicationViews { view.hidden = false view.transform = CGAffineTransformIdentity } } } } let centerScreen = CGPoint(x: 312.0/4, y: 390.0/4) let secondHandColor = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 3.0/255.0, alpha: 1.0) let hourHandColor = UIColor.whiteColor() let minuteHandColor = UIColor.whiteColor() extension CALayer { convenience init(superlayer:CALayer, position:CGPoint = CGPointZero, backgroundColor : UIColor? = nil) { self.init() superlayer.addSublayer(self) self.position = position self.backgroundColor = backgroundColor?.CGColor } } extension CAShapeLayer { convenience init(superlayer:CALayer, position:CGPoint = CGPointZero, strokeColor:UIColor? = nil, fillColor:UIColor? = nil) { self.init() superlayer.addSublayer(self) self.position = position self.strokeColor = strokeColor?.CGColor self.fillColor = fillColor?.CGColor self.edgeAntialiasingMask = CAEdgeAntialiasingMask.LayerLeftEdge | CAEdgeAntialiasingMask.LayerRightEdge | CAEdgeAntialiasingMask.LayerBottomEdge | CAEdgeAntialiasingMask.LayerTopEdge } } extension CGRect { init(center:CGPoint, width:CGFloat, height:CGFloat) { self = CGRect(x:center.x - width/2, y: center.y - height/2, width:width, height:height) } } func OarShapedBezier(#handleLength:CGFloat, #totalLength:CGFloat, #handleThickness:CGFloat, #bladeThickness:CGFloat)->CGPath { let path = UIBezierPath() // the oar is sticking straight up, with the blade in the air and sitting centered on 0,0 // trace around it, starting at 0,0 and moving left first let lengthWithoutCap = totalLength - bladeThickness let transitionLen = CGFloat(KFTunableSpec(named: "MainSpec").doubleForKey("OarCurveLen")) path.moveToPoint(CGPointZero) path.addLineToPoint(CGPoint(x: -handleThickness/2, y: 0)) // bottom left path.addLineToPoint(CGPoint(x: -handleThickness/2, y: handleLength)) // up the handle path.addCurveToPoint(CGPoint(x:-bladeThickness/2, y:handleLength + transitionLen), // curve out to the blade controlPoint1: CGPoint(x: -handleThickness/2, y: handleLength + transitionLen/2), controlPoint2: CGPoint(x: -bladeThickness/2, y: handleLength + transitionLen/2)) path.addLineToPoint(CGPoint(x: -bladeThickness/2, y:lengthWithoutCap)) // up to the top // we're at the top now. Put a cap on the end path.addArcWithCenter(CGPoint(x:0,y:lengthWithoutCap), radius: bladeThickness/2, startAngle: CGFloat(M_PI), endAngle: 0, clockwise: false) // and back down path.addLineToPoint(CGPoint(x: bladeThickness/2, y:handleLength + transitionLen)) // down to where we start to curve in path.addCurveToPoint(CGPoint(x:handleThickness/2, y:handleLength), // curve out to the blade controlPoint1: CGPoint(x: bladeThickness/2, y: handleLength + transitionLen/2), controlPoint2: CGPoint(x: handleThickness/2, y: handleLength + transitionLen/2)) path.addLineToPoint(CGPoint(x: handleThickness/2, y:0)) // down the handle path.addLineToPoint(CGPoint(x: 0, y:0)) // back left to the center return path.CGPath } enum ProgressInRange { case Before case During(CGFloat) case After } func progressInRange<T:IntervalType where T.Bound == Double>(r:T, t:T.Bound)->ProgressInRange { if t < r.start { return .Before } else if r ~= t { let progress = CGFloat((t - r.start) / (r.end - r.start)) return .During(progress) } else { return .After } }
mit
64fe80bc52f7bd415919a1d01190dd59
43.949519
191
0.665864
4.622744
false
false
false
false
mgrebenets/hackerrank
alg/warmup/solve-me-second.swift
1
469
/// Solve me second /// https://www.hackerrank.com/challenges/solve-me-second public func solveMeSecond() { let n: Int = readLn() let s: String = readLn() for _ in 0..<n { let ints: [Int] = readLn() // 1.2 wants combine: let sum = ints.reduce(0, combine: +) println(sum) } } #if CLI_BUILD import StdIO // silence the xcode, it doesn't like just calling funcName() directly let x: Void = solveMeSecond() #endif
mit
f61eb6bfbda970671ac70ba29f35f0d0
23.684211
74
0.599147
3.448529
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Today Widgets/WidgetStyles.swift
2
1035
import Foundation import NotificationCenter class WidgetStyles: NSObject { static let primaryTextColor: UIColor = .text static let secondaryTextColor: UIColor = .textSubtle static let headlineFont = UIFont.systemFont(ofSize: UIFont.preferredFont(forTextStyle: .headline).pointSize) static let footnoteNote = UIFont.systemFont(ofSize: UIFont.preferredFont(forTextStyle: .footnote).pointSize) static var separatorColor: UIColor = { if #available(iOS 13, *) { return .separator } else { return .divider } }() static var separatorVibrancyEffect: UIVibrancyEffect = { if #available(iOS 13, *) { return .widgetEffect(forVibrancyStyle: .separator) } else { return .widgetSecondary() } }() static func configureSeparator(_ separator: UIView) { // Both colors are need for the vibrancy effect. separator.backgroundColor = separatorColor separator.tintColor = separatorColor } }
gpl-2.0
6ddd540951d820f2abe5a8adb7828ef3
30.363636
112
0.663768
5.149254
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/System/WindowManager.swift
1
3423
import Foundation import WordPressAuthenticator /// This class takes care of managing the App window and its `rootViewController`. /// This is mostly intended to handle the UI transitions between authenticated and unauthenticated user sessions. /// @objc class WindowManager: NSObject { typealias Completion = () -> Void /// The App's window. /// private let window: UIWindow /// A boolean to track whether we're showing the sign in flow in fullscreen mode.. /// private(set) var isShowingFullscreenSignIn = false init(window: UIWindow) { self.window = window } // MARK: - Initial App UI /// Shows the initial UI for the App to be shown right after launch. This method will present the sign-in flow if the user is not /// authenticated, or the actuall App UI if the user is already authenticated. /// public func showUI(for blog: Blog? = nil) { if AccountHelper.isLoggedIn { showAppUI(for: blog) } else { showSignInUI() } } /// Shows the SignIn UI flow if the conditions to do so are met. /// @objc func showFullscreenSignIn() { guard isShowingFullscreenSignIn == false && AccountHelper.isLoggedIn == false else { return } showSignInUI() } func dismissFullscreenSignIn(blogToShow: Blog? = nil, completion: Completion? = nil) { guard isShowingFullscreenSignIn == true && AccountHelper.isLoggedIn == true else { return } showAppUI(for: blogToShow, completion: completion) } /// Shows the UI for authenticated users. /// @objc func showAppUI(for blog: Blog? = nil, completion: Completion? = nil) { isShowingFullscreenSignIn = false show(WPTabBarController.sharedInstance(), completion: completion) guard let blog = blog else { return } WPTabBarController.sharedInstance()?.showBlogDetails(for: blog) } /// Shows the initial UI for unauthenticated users. /// func showSignInUI(completion: Completion? = nil) { isShowingFullscreenSignIn = true guard let loginViewController = WordPressAuthenticator.loginUI() else { fatalError("No login UI to show to the user. There's no way to gracefully handle this error.") } show(loginViewController, completion: completion) WordPressAuthenticator.track(.openedLogin) } /// Shows the specified VC as the root VC for the managed window. Takes care of animating the transition whenever the existing /// root VC isn't `nil` (this is because a `nil` VC means we're showing the initial VC on a call to this method). /// func show(_ viewController: UIViewController, completion: Completion? = nil) { // When the App is launched, the root VC will be `nil`. // When this is the case we'll simply show the VC without any type of animation. guard window.rootViewController != nil else { window.rootViewController = viewController return } window.rootViewController = viewController UIView.transition( with: window, duration: WPAnimationDurationDefault, options: .transitionCrossDissolve, animations: nil, completion: { _ in completion?() }) } }
gpl-2.0
384f61022c590ad564a706d94ab89612
31.913462
134
0.639498
5.026432
false
false
false
false
lsirbu/BelerLibrary
Pod/Classes/CustomNavigationController.swift
1
2065
// // CustomNavigationController.swift // MyFramework // // Created by Liliana on 25/01/16. // Copyright (c) 2016 Liliana Sirbu. All rights reserved. // import UIKit public class CustomNavigationController:UINavigationController, UINavigationControllerDelegate{ override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.setup() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup(){ self.delegate = self } public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { if let navBar = self.customNavigationBar(){ navBar.updateTitleView() } } public func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool){ } override public func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } // MARK: CustomNavigationBar Extension public extension UINavigationController{ // Return the customNavigationBar object, if it exists. public func customNavigationBar()->CustomNavigationBar?{ if let navbar = self.navigationBar as? CustomNavigationBar{ return navbar } else{ return nil } } // Set the CustomNavigationBar as delegate for a UIScrollView public func setupPulltoRefresh(scrollView:UIScrollView, viewController: CustomNavigationBarDelegate?){ if let navbar = self.customNavigationBar(){ scrollView.delegate = navbar navbar.delegateNav = viewController } } public func stopRefresh(){ if let navbar = self.customNavigationBar(){ navbar.stopLoaderAnimation() } } }
mit
c0a30eda8e465a8f4aabe22ef9e71753
27.694444
156
0.675545
5.657534
false
false
false
false
KevinJhon464/ios-charts
Charts/Classes/Charts/PieRadarChartViewBase.swift
1
28338
// // PieRadarChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base class of PieChartView and RadarChartView. public class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not public var rotationEnabled = true /// Sets the minimum offset (padding) around the chart, defaults to 10 public var minOffset = CGFloat(10.0) private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: UITapGestureRecognizer! #if !os(tvOS) private var _rotationGestureRecognizer: UIRotationGestureRecognizer! #endif public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) self.addGestureRecognizer(_tapGestureRecognizer) #if !os(tvOS) _rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: Selector("rotationGestureRecognized:")) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.enabled = rotationWithTwoFingers #endif } internal override func calcMinMax() { _deltaX = CGFloat(_data.xVals.count - 1) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() if (_legend !== nil) { _legendRenderer.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if (_legend != nil && _legend.enabled) { var fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) fullLegendWidth += _legend.formSize + _legend.formToTextSpace if (_legend.position == .RightOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendRight = fullLegendWidth + spacing } else if (_legend.position == .RightOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomRight.x, y: bottomRight.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendRight = minOffset + diff } if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendRight = legendWidth } } else if (_legend.position == .LeftOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendLeft = fullLegendWidth + spacing } else if (_legend.position == .LeftOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let min = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendLeft = min + diff } if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendLeft = legendWidth } } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendBottom = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendTop = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = self.minOffset if (self.isKindOfClass(RadarChartView)) { let x = (self as! RadarChartView).xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(minOffset, x.labelWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: the angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... public func angleForPoint(x x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r * ChartUtils.Math.RAD2DEG if (x > c.x) { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if (angle > 360.0) { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. internal func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD), y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD)) } /// - returns: the distance of a certain point on the chart to the center of the chart. public func distanceToCenter(x x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if (x > c.x) { xDist = x - c.x } else { xDist = c.x - x } if (y > c.y) { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: the xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. public func indexForAngle(angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: will always return a normalized value, which will be between 0.0 < 360.0 public var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue) setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. public var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: the diameter of the pie- or radar-chart public var diameter: CGFloat { let content = _viewPortHandler.contentRect return min(content.width, content.height) } /// - returns: the radius of the chart in pixels. public var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: the required offset for the chart legend. internal var requiredLegendOffset: CGFloat { fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase") } /// - returns: the base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } public override var chartXMax: Double { return 0.0 } public override var chartXMin: Double { getSelectionDetailsAtIndex(1); return 0.0 } /// The SelectionDetail objects give information about the value at the selected index and the DataSet it belongs to. /// - returns: an array of SelectionDetail objects for the given x-index. public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail] { var vals = [ChartSelectionDetail]() for (var i = 0; i < _data.dataSetCount; i++) { let dataSet = _data.getDataSetByIndex(i) if (dataSet === nil || !dataSet.isHighlightEnabled) { continue } // extract all y-values from all DataSets at the given x-index let yVal = dataSet!.yValForXIndex(xIndex) if (yVal.isNaN) { continue } vals.append(ChartSelectionDetail(value: yVal, dataSetIndex: i, dataSet: dataSet!)) } return vals } public var isRotationEnabled: Bool { return rotationEnabled; } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// **default**: false public var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue #if !os(tvOS) _rotationGestureRecognizer.enabled = _rotationWithTwoFingers #endif } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// **default**: false public var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: ChartAnimator! /// Applys a spin animation to the Chart. public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if (_spinAnimator != nil) { _spinAnimator.stop() } _spinAnimator = ChartAnimator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil; } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } public func stopSpinAnimation() { if (_spinAnimator != nil) { _spinAnimator.stop() } } // MARK: - Gestures private var _touchStartPoint: CGPoint! private var _isRotating = false private var _defaultTouchEventsWereEnabled = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: NSTimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // if rotation by touch is enabled if (rotationEnabled) { stopDeceleration() if (!rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) self.resetVelocity() if (rotationEnabled) { self.sampleVelocity(touchLocation: touchLocation) } self.setGestureStartAngle(x: touchLocation.x, y: touchLocation.y) _touchStartPoint = touchLocation } } if (!_isRotating) { super.touchesBegan(touches, withEvent: event) } } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) if (isDragDecelerationEnabled) { sampleVelocity(touchLocation: touchLocation) } if (!_isRotating && distance(eventX: touchLocation.x, startX: _touchStartPoint.x, eventY: touchLocation.y, startY: _touchStartPoint.y) > CGFloat(8.0)) { _isRotating = true } else { self.updateGestureRotation(x: touchLocation.x, y: touchLocation.y) setNeedsDisplay() } } if (!_isRotating) { super.touchesMoved(touches, withEvent: event) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!_isRotating) { super.touchesEnded(touches, withEvent: event) } if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) if (isDragDecelerationEnabled) { stopDeceleration() sampleVelocity(touchLocation: touchLocation) _decelerationAngularVelocity = calculateVelocity() if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } if (_isRotating) { _isRotating = false } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) if (_isRotating) { _isRotating = false } } private func resetVelocity() { _velocitySamples.removeAll(keepCapacity: false) } private func sampleVelocity(touchLocation touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds for (var i = 0, count = _velocitySamples.count; i < count - 2; i++) { if (currentTime - _velocitySamples[i].time > 1.0) { _velocitySamples.removeAtIndex(0) i-- count-- } else { break } } } private func calculateVelocity() -> CGFloat { if (_velocitySamples.isEmpty) { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for (var i = _velocitySamples.count - 1; i >= 0; i--) { beforeLastSample = _velocitySamples[i] if (beforeLastSample.angle != lastSample.angle) { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if (timeDelta == 0.0) { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if (lastSample.angle - firstSample.angle > 180.0) { firstSample.angle += 360.0 } else if (firstSample.angle - lastSample.angle > 180.0) { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if (!clockwise) { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: the distance between two points private func distance(eventX eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: the distance between two points private func distance(from from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: ChartHighlight! @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Ended) { let location = recognizer.locationInView(self) let distance = distanceToCenter(x: location.x, y: location.y) // check if a slice was touched if (distance > self.radius) { // if no slice was touched, highlight nothing self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { var angle = angleForPoint(x: location.x, y: location.y) if (self.isKindOfClass(PieChartView)) { angle /= _animator.phaseY } let index = indexForAngle(angle) // check if the index could be found if (index < 0) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { let valsAtIndex = getSelectionDetailsAtIndex(index) var dataSetIndex = 0 // get the dataset that is closest to the selection (PieChart only has one DataSet) if (self.isKindOfClass(RadarChartView)) { dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Double(distance / (self as! RadarChartView).factor), axis: nil) } if (dataSetIndex < 0) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { let h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex) if (_lastHighlight !== nil && h == _lastHighlight) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { self.highlightValue(highlight: h, callDelegate: true) _lastHighlight = h } } } } } } #if !os(tvOS) @objc private func rotationGestureRecognized(recognizer: UIRotationGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() _startAngle = self.rawRotationAngle } if (recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Changed) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if (recognizer.state == UIGestureRecognizerState.Ended) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation self.rotationAngle = _startAngle + angle setNeedsDisplay() if (isDragDecelerationEnabled) { stopDeceleration() _decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } } #endif }
apache-2.0
a22ae38655d862218ca80a2044c419d6
32.257042
191
0.555834
5.548071
false
false
false
false
OneBestWay/EasyCode
Swift/PocketBook/PocketBook/AccountHomeViewController.swift
1
2859
// // ViewController.swift // PocketBook // // Created by GK on 2017/3/11. // Copyright © 2017年 GK. All rights reserved. // import UIKit class AccountHomeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableHeaderView: UIView! @IBOutlet weak var segmentedControl: UISegmentedControl! fileprivate let dataService: ConsumptionDataService = ConsumptionDataService() var headerHeight: CGFloat = 135.00 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. headerViewFrameHeight(height: headerHeight) setUI() } func headerViewFrameHeight(height:CGFloat) { var headerFrame = tableHeaderView.frame headerFrame.size.height = height tableHeaderView.frame = headerFrame } func setUI() { //segemented control style segmentedControl.layer.borderColor = UIColor.black.cgColor segmentedControl.layer.borderWidth = 1 segmentedControl.layer.cornerRadius = 4 segmentedControl.clipsToBounds = true } @IBAction func didSelectedControl(_ sender: UISegmentedControl) { let selectedIndex = sender.selectedSegmentIndex switch selectedIndex { case 0: headerHeight = 135 headerViewFrameHeight(height: headerHeight) print("did selected 明细") case 1: headerHeight = 380 headerViewFrameHeight(height: headerHeight) print("did selected 类别报表") case 2: headerHeight = 135 headerViewFrameHeight(height: headerHeight) print("did selected 账户") default: break } } } extension AccountHomeViewController: UITableViewDataSource,UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataService.consumptionList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DetailsCell.cellIdentifier()) return cell! } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let consumptionDTO = dataService.consumptionList[indexPath.row] if let detailCell = cell as? DetailsCell { detailCell.configCell(consumptionDTO: consumptionDTO) } } } extension AccountHomeViewController: ConsumptionDataServiceDelegate { func listDidChanged() { self.tableView.reloadData() } }
mit
f7a637ac227be0c372c332da1047bf6a
30.555556
112
0.664437
5.43021
false
false
false
false
mcberros/VirtualTourist
VirtualTourist/FlickrApiConstants.swift
1
669
// // FlickrApiConstants.swift // VirtualTourist // // Created by Carmen Berros on 03/07/16. // Copyright © 2016 mcberros. All rights reserved. // import Foundation extension FlickrApiClient { struct Constants { static let BaseURL = "https://api.flickr.com/services/rest/" static let ApiKey = "b78bc85713989c71fce367ce67a46843" } struct Methods { static let SearchPhotos = "flickr.photos.search" } struct ParameterValues { static let SafeSearch = "1" static let Extras = "url_m" static let Format = "json" static let NoJsonCallback = "1" static let PerPage = "10" } }
mit
887fd249b53729804bbbd83fe5516201
19.875
68
0.634731
3.67033
false
false
false
false
systers/PowerUp
Powerup/OOC-Event-Classes/SoundPlayer.swift
1
1778
import UIKit import AVFoundation import AudioToolbox /** Creates a strong reference to AVAudioPlayer and plays a sound file. Convenience class to declutter controller classes. Example Use ``` let soundPlayer : SoundPlayer? = SoundPlayer() guard let player = self.soundPlayer else {return} // player.playSound(fileName: String, volume: Float) player.playSound("sound.mp3", 0.5) ``` - Author: Cadence Holmes 2018 */ class SoundPlayer { var player: AVAudioPlayer? var numberOfLoops: Int = 1 init () { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback))) try AVAudioSession.sharedInstance().setActive(true) } catch let error { print(error.localizedDescription) } } /** Handles checking for AVAudioPlayer and playing a sound. - throws: print(error.localizedDescription) - parameters: - fileName : String - file name as it appears in Sounds.xcassets - volume : Float - volume scaled 0.0 - 1.0 */ func playSound(_ fileName: String, _ volume: Float) { guard let sound = NSDataAsset(name: fileName) else { return } do { player = try AVAudioPlayer(data: sound.data) guard let soundplayer = player else { return } soundplayer.numberOfLoops = numberOfLoops soundplayer.volume = volume soundplayer.play() } catch let error { print(error.localizedDescription) } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String { return input.rawValue }
gpl-2.0
6ac7c3597a103eda689d2d94b17a0f32
28.633333
163
0.668166
4.844687
false
false
false
false
christos-bimpas/MenuSegmentedViewController
MenuSegmentedViewController/MenuSegmentedViewController.swift
1
9388
// // MenuSegmentedViewController.swift // MenuSegmentedViewController // // Created by Christos Bimpas on 25/11/16. // Copyright © 2016 Christos Bimpas. All rights reserved. // import Foundation import UIKit import QuartzCore import SnapKit open class MenuSegmentedViewController: UIViewController, UIScrollViewDelegate { //MARK: - Properties public var viewControllers: [UIViewController] = [] public var titleViewHeight: Float = 34 public var titleFont: UIFont? public var titleColor: UIColor? public var underlineColor: UIColor? public var minAlpha: CGFloat = 0.2 private var titleScrollView: UIScrollView! private var contentScrollView: UIScrollView! private var buttonViews: [UIButton] = [] private var underlineViews: [UIView] = [] private var shouldUpdateAlphaOnScroll = true private var index: Int = 0 private var previousXContentOffset: CGFloat = 0.0 var shadowImage: UIImage! //MARK: - public init() { super.init(nibName:nil, bundle:nil) self.view.backgroundColor = UIColor.white titleScrollView = UIScrollView() titleScrollView.isPagingEnabled = true titleScrollView.showsHorizontalScrollIndicator = false titleScrollView.backgroundColor = UIColor.white titleScrollView.bounces = false titleScrollView.delegate = self self.view.addSubview(titleScrollView) titleScrollView.snp.makeConstraints { (make) in make.left.right.top.equalTo(self.view) make.height.equalTo(titleViewHeight) } let bottomBorder = CALayer() bottomBorder.frame = CGRect.init(x: 0.0, y: Double(titleViewHeight - 1.0), width: Double(self.view.frame.size.width), height: 1.0) bottomBorder.backgroundColor = UIColor.init(red: 222.0/255.0, green: 222.0/255.0, blue: 222.0/255.0, alpha: 1.0).cgColor bottomBorder.shadowColor = UIColor.gray.cgColor bottomBorder.shadowRadius = 5.0 bottomBorder.shadowOffset = CGSize(width: 0, height: 1) titleScrollView.layer.addSublayer(bottomBorder) contentScrollView = UIScrollView() contentScrollView.isPagingEnabled = true contentScrollView.showsHorizontalScrollIndicator = false contentScrollView.delegate = self contentScrollView.backgroundColor = UIColor.clear self.view.addSubview(contentScrollView) contentScrollView.snp.makeConstraints { (make) in make.top.equalTo(titleScrollView.snp.bottom) make.left.right.bottom.equalTo(self.view) } let innerRect = CGRect.init(x: 0.0, y: 3.0 + CGFloat(titleViewHeight), width: self.view.frame.size.width, height: 1.0) let shadowView = UIView(frame: innerRect) shadowView.backgroundColor = UIColor.clear shadowView.layer.masksToBounds = false; shadowView.layer.shadowRadius = 0.7 shadowView.layer.shadowOpacity = 0.3 shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath self.view.addSubview(shadowView) shadowImage = self.navigationController?.navigationBar.shadowImage DispatchQueue.main.async { self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) } } public func set(viewControllers controllers: [UIViewController]) { viewControllers = controllers var previousButton: UIButton! for viewController in viewControllers { let button = UIButton() button.setTitle(viewController.title, for: UIControlState.normal) if let font = titleFont { button.titleLabel?.font = font } if let color = titleColor { button.setTitleColor(color, for: UIControlState.normal) } else { button.setTitleColor(UIColor.black, for: UIControlState.normal) } button.addTarget(self, action: #selector(didTapOnButton(sender:)), for: UIControlEvents.touchUpInside) titleScrollView.addSubview(button) button.snp.makeConstraints({ (make) in if previousButton == nil { make.left.equalTo(titleScrollView) } else { make.left.equalTo(previousButton.snp.right) } make.top.equalTo(titleScrollView) make.height.equalTo(titleViewHeight - 8) make.width.equalTo(self.view.frame.size.width / CGFloat(viewControllers.count)) if viewControllers.last == viewController { make.right.equalTo(titleScrollView) } }) buttonViews.append(button) let underlineView = UIView() if let color = underlineColor { underlineView.backgroundColor = color } else { underlineView.backgroundColor = UIColor.black } underlineView.alpha = viewControllers.first == viewController ? 1.0 : minAlpha titleScrollView.addSubview(underlineView) underlineView.snp.makeConstraints { (make) in make.left.equalTo(button).offset(4) make.right.equalTo(button).offset(-4) make.height.equalTo(4) make.top.equalTo(button.snp.bottom) make.bottom.equalTo(titleScrollView).offset(-6) } underlineViews.append(underlineView) previousButton = button } var previousView: UIView! for viewController in viewControllers { var contentView = UIView() contentView = viewController.view contentScrollView.addSubview(contentView) contentView.snp.makeConstraints({ (make) in if previousView == nil { make.left.equalTo(contentScrollView) } else { make.left.equalTo(previousView.snp.right) } make.top.bottom.equalTo(contentScrollView) make.width.equalTo(contentScrollView) make.height.equalTo(contentScrollView) if viewControllers.last == viewController { make.right.equalTo(contentScrollView) } }) previousView = contentView } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } //MARK: - UIButton func didTapOnButton(sender: UIButton) { shouldUpdateAlphaOnScroll = false let nextIndex = buttonViews.index(of: sender) UIView.animate(withDuration: 0.0, animations: { self.contentScrollView.contentOffset = CGPoint.init(x: CGFloat(nextIndex!) * self.contentScrollView.frame.size.width, y: self.contentScrollView.contentOffset.y) }) { (_) in self.shouldUpdateAlphaOnScroll = true self.contentDidScroll(withOffset: CGFloat(nextIndex!)) } let currentUndelineView = underlineViews[index] let nextUndelineView = underlineViews[nextIndex!] UIView.animate(withDuration: 0.25) { currentUndelineView.alpha = self.minAlpha nextUndelineView.alpha = 1.0 } index = nextIndex! } //MARK: - UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.x / scrollView.frame.size.width self.contentDidScroll(withOffset: offset) if scrollView == contentScrollView && shouldUpdateAlphaOnScroll { if offset > CGFloat(viewControllers.count - 1) { return } var currentIndex: Int! let nextIndex: Int! if previousXContentOffset < scrollView.contentOffset.x { currentIndex = Int(floor(offset)) nextIndex = Int(ceil(offset)) } else if previousXContentOffset > scrollView.contentOffset.x { currentIndex = Int(ceil(offset)) nextIndex = Int(floor(offset)) } else { return } let progress = fabs(CGFloat(nextIndex) - offset) let currentIndexValid = underlineViews.indices.contains(currentIndex) if currentIndexValid { let currentUnderlineView = underlineViews[currentIndex] currentUnderlineView.alpha = (1 - minAlpha) * progress + minAlpha } let nextIndexValid = underlineViews.indices.contains(nextIndex) if nextIndexValid { let nextUnderlineView = underlineViews[nextIndex] nextUnderlineView.alpha = (1 - minAlpha) * (1 - progress) + minAlpha } index = nextIndex } previousXContentOffset = scrollView.contentOffset.x } open func contentDidScroll(withOffset offset: CGFloat) { } }
mit
3efab177b469221928615a15f27753ca
38.944681
172
0.612443
5.324447
false
false
false
false
ifLab/WeCenterMobile-iOS
WeCenterMobile/Controller/SearchViewController.swift
3
8403
// // SearchViewController.swift // WeCenterMobile // // Created by Darren Liu on 15/6/13. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit @objc protocol SearchResultCell: class { optional var articleButton: UIButton! { get } optional var questionButton: UIButton! { get } optional var topicButton: UIButton! { get } optional var userButton: UIButton! { get } func update(dataObject dataObject: DataObject) } extension ArticleSearchResultCell: SearchResultCell {} extension QuestionSearchResultCell: SearchResultCell {} extension TopicSearchResultCell: SearchResultCell {} extension UserSearchResultCell: SearchResultCell {} class SearchViewController: UITableViewController, UISearchBarDelegate { let objectTypes: [DataObject.Type] = [Article.self, Question.self, Topic.self, User.self] let nibNames = ["ArticleSearchResultCell", "QuestionSearchResultCell", "TopicSearchResultCell", "UserSearchResultCell"] let identifiers = ["ArticleSearchResultCell", "QuestionSearchResultCell", "TopicSearchResultCell", "UserSearchResultCell"] var objects = [DataObject]() var keyword = "" var page = 1 var shouldReloadAfterLoadingMore = true lazy var searchBar: UISearchBar = { [weak self] in let theme = SettingsManager.defaultManager.currentTheme let v = UISearchBar() v.delegate = self v.placeholder = "搜索用户和内容" v.barStyle = theme.navigationBarStyle v.keyboardAppearance = theme.keyboardAppearance return v }() override func loadView() { super.loadView() navigationItem.titleView = searchBar navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Navigation-Root"), style: .Plain, target: self, action: "showSidebar") for i in 0..<nibNames.count { tableView.registerNib(UINib(nibName: nibNames[i], bundle: NSBundle.mainBundle()), forCellReuseIdentifier: identifiers[i]) } let theme = SettingsManager.defaultManager.currentTheme view.backgroundColor = theme.backgroundColorA tableView.indicatorStyle = theme.scrollViewIndicatorStyle tableView.separatorStyle = .None tableView.estimatedRowHeight = 80 tableView.rowHeight = UITableViewAutomaticDimension tableView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self) tableView.delaysContentTouches = false tableView.keyboardDismissMode = .OnDrag tableView.msr_wrapperView?.delaysContentTouches = false tableView.wc_addRefreshingHeaderWithTarget(self, action: "refresh") } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "sidebarDidBecomeVisible:", name: SidebarDidBecomeVisibleNotificationName, object: appDelegate.mainViewController.sidebar) NSNotificationCenter.defaultCenter().addObserver(self, selector: "sidebarDidBecomeInvisible:", name: SidebarDidBecomeInvisibleNotificationName, object: appDelegate.mainViewController.sidebar) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let object = objects[indexPath.row] if let index = (objectTypes.map { object.classForCoder === $0 }).indexOf(true) { let cell = tableView.dequeueReusableCellWithIdentifier(identifiers[index], forIndexPath: indexPath) as! SearchResultCell cell.update(dataObject: object) cell.articleButton?.addTarget(self, action: "didPressArticleButton:", forControlEvents: .TouchUpInside) cell.questionButton?.addTarget(self, action: "didPressQuestionButton:", forControlEvents: .TouchUpInside) cell.topicButton?.addTarget(self, action: "didPressTopicButton:", forControlEvents: .TouchUpInside) cell.userButton?.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside) return cell as! UITableViewCell } else { return UITableViewCell() // Needs specification } } override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() let text = searchBar.text ?? "" if text != "" { keyword = searchBar.text ?? "" tableView.mj_header.beginRefreshing() } } func didPressUserButton(sender: UIButton) { if let user = sender.msr_userInfo as? User { msr_navigationController!.pushViewController(UserViewController(user: user), animated: true) } } func didPressTopicButton(sender: UIButton) { if let topic = sender.msr_userInfo as? Topic { msr_navigationController!.pushViewController(TopicViewController(topic: topic), animated: true) } } func didPressArticleButton(sender: UIButton) { if let article = sender.msr_userInfo as? Article { msr_navigationController!.pushViewController(ArticleViewController(dataObject: article), animated: true) } } func didPressQuestionButton(sender: UIButton) { if let question = sender.msr_userInfo as? Question { msr_navigationController!.pushViewController(QuestionViewController(question: question), animated: true) } } func refresh() { if keyword == "" { tableView.mj_header.endRefreshing() return } shouldReloadAfterLoadingMore = false tableView.mj_footer?.endRefreshing() DataObject.fetchSearchResultsWithKeyword(keyword, type: .All, page: 1, success: { [weak self] objects in if let self_ = self { self_.page = 1 self_.objects = objects self_.tableView.reloadData() self_.tableView.mj_header.endRefreshing() if self_.tableView.mj_footer == nil { self_.tableView.wc_addRefreshingFooterWithTarget(self_, action: "loadMore") } } return }, failure: { [weak self] error in self?.tableView.mj_header.endRefreshing() return }) } func loadMore() { if tableView.mj_header.isRefreshing() { tableView.mj_footer.endRefreshing() return } shouldReloadAfterLoadingMore = true DataObject.fetchSearchResultsWithKeyword(keyword, type: .All, page: page + 1, success: { [weak self] objects in if let self_ = self { if self_.shouldReloadAfterLoadingMore { ++self_.page self_.objects.appendContentsOf(objects) self_.tableView.reloadData() } self_.tableView.mj_footer.endRefreshing() } return }, failure: { [weak self] error in self?.tableView.mj_footer.endRefreshing() return }) } func showSidebar() { appDelegate.mainViewController.sidebar.expand() } func sidebarDidBecomeVisible(notification: NSNotification) { if msr_navigationController?.topViewController === self { searchBar.endEditing(true) } } func sidebarDidBecomeInvisible(notification: NSNotification) {} override func preferredStatusBarStyle() -> UIStatusBarStyle { return SettingsManager.defaultManager.currentTheme.statusBarStyle } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
gpl-2.0
fa4df0257dfbf8765c1e2ce20a6543a6
38.938095
199
0.642542
5.602538
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Convolution.xcplaygroundpage/Contents.swift
1
2074
//: ## Convolution //: Allows you to create a large variety of effects, usually reverbs or environments, //: but it could also be for modeling. import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true let bundle = NSBundle.mainBundle() let stairwell = bundle.URLForResource("Impulse Responses/stairwell", withExtension: "wav")! let dish = bundle.URLForResource("Impulse Responses/dish", withExtension: "wav")! var stairwellConvolution = AKConvolution.init(player, impulseResponseFileURL: stairwell, partitionLength: 8192) var dishConvolution = AKConvolution.init(player, impulseResponseFileURL: dish, partitionLength: 8192) var mixer = AKDryWetMixer(stairwellConvolution, dishConvolution, balance: 0.5) var dryWetMixer = AKDryWetMixer(player, mixer, balance: 0.5) AudioKit.output = dryWetMixer AudioKit.start() stairwellConvolution.start() dishConvolution.start() player.play() class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Convolution") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: processingPlaygroundFiles)) addSubview(AKPropertySlider( property: "Dry Audio to Convolved", value: dryWetMixer.balance, color: AKColor.greenColor() ) { sliderValue in dryWetMixer.balance = sliderValue }) addSubview(AKPropertySlider( property: "Stairwell to Dish", value: mixer.balance, color: AKColor.cyanColor() ) { sliderValue in mixer.balance = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
bc2f57d2874aa97c0c4fa1f71f0ccad4
31.920635
91
0.644166
5.146402
false
false
false
false
Albertorizzoli/ioscreator
IOS8SwiftCoreImageTutorial/IOS8SwiftCoreImageTutorial/ViewController.swift
40
899
// // ViewController.swift // IOS8SwiftCoreImageTutorial // // Created by Arthur Knopper on 01/04/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "dog.jpg") let originalImage = CIImage(image: image) var filter = CIFilter(name: "CIPhotoEffectMono") filter.setDefaults() filter.setValue(originalImage, forKey: kCIInputImageKey) var outputImage = filter.outputImage var newImage = UIImage(CIImage: outputImage) imageView.image = newImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
bc1424ca86a92f693befa73d0a4b58e7
23.972222
64
0.655172
4.93956
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/ModelParser/QuestChannelMP.swift
1
821
// // QuestChannelMP.swift // Pods // // Created by Evandro Harrison Hoffmann on 7/23/18. // import Foundation struct QuestChannelMP { static func parseChannelsFrom(_ json: Data) -> [QuestChannel] { var channels: [QuestChannel] = [] if let decoded = try? JSONDecoder().decode(QuestChannelsDataKey.self, from: json) { channels = decoded.data.channels } return channels } static func parseChannelFrom(_ json: Data) -> QuestChannel? { var channel: QuestChannel? do { let decoded = try JSONDecoder().decode(SingleQuestChannelDataKey.self, from: json) channel = decoded.data.channel } catch { print("\(#function) error: \(error)") } return channel } }
mit
b06c1d85ac4017513850380a63782444
23.878788
94
0.579781
4.413978
false
false
false
false
Jnosh/swift
benchmark/utils/main.swift
2
39204
//===--- main.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is manually generated from .gyb template and should not // be directly modified. Instead, make changes to main.swift.gyb and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySubscript import BitCount import ByteSwap import CString import Calculator import CaptureProp import CharacterLiteralsLarge import CharacterLiteralsSmall import Chars import ClassArrayGetter import DeadArray import DictTest import DictTest2 import DictTest3 import DictionaryBridge import DictionaryLiteral import DictionaryRemove import DictionarySwap import DropFirst import DropLast import DropWhile import ErrorHandling import ExistentialPerformance import Fibonacci import GlobalClass import Hanoi import Hash import HashQuadratic import Histogram import Integrate import IterateData import Join import LazyFilter import LinkedList import MapReduce import Memset import MonteCarloE import MonteCarloPi import NSDictionaryCastToSwift import NSError import NSStringConversion import NopDeinit import ObjectAllocation import ObjectiveCBridging import ObjectiveCBridgingStubs import ObjectiveCNoBridgingStubs import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpenClose import Phonebook import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import ProtocolDispatch import ProtocolDispatch2 import RC4 import RGBHistogram import RangeAssignment import RecursiveOwnedParameter import ReversedCollections import SetTests import SevenBoom import Sim2DArray import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringEdits import StringInterpolation import StringMatch import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import XorLoop @inline(__always) private func addTo( _ testSuite: inout [String : (Int) -> ()], _ name: String, _ function: @escaping (Int) -> () ) { testSuite[name] = function } // The main test suite: precommit tests addTo(&precommitTests, "AngryPhonebook", run_AngryPhonebook) addTo(&precommitTests, "AnyHashableWithAClass", run_AnyHashableWithAClass) addTo(&precommitTests, "Array2D", run_Array2D) addTo(&precommitTests, "ArrayAppend", run_ArrayAppend) addTo(&precommitTests, "ArrayAppendArrayOfInt", run_ArrayAppendArrayOfInt) addTo(&precommitTests, "ArrayAppendAscii", run_ArrayAppendAscii) addTo(&precommitTests, "ArrayAppendFromGeneric", run_ArrayAppendFromGeneric) addTo(&precommitTests, "ArrayAppendGenericStructs", run_ArrayAppendGenericStructs) addTo(&precommitTests, "ArrayAppendLatin1", run_ArrayAppendLatin1) addTo(&precommitTests, "ArrayAppendLazyMap", run_ArrayAppendLazyMap) addTo(&precommitTests, "ArrayAppendOptionals", run_ArrayAppendOptionals) addTo(&precommitTests, "ArrayAppendRepeatCol", run_ArrayAppendRepeatCol) addTo(&precommitTests, "ArrayAppendReserved", run_ArrayAppendReserved) addTo(&precommitTests, "ArrayAppendSequence", run_ArrayAppendSequence) addTo(&precommitTests, "ArrayAppendStrings", run_ArrayAppendStrings) addTo(&precommitTests, "ArrayAppendToFromGeneric", run_ArrayAppendToFromGeneric) addTo(&precommitTests, "ArrayAppendToGeneric", run_ArrayAppendToGeneric) addTo(&precommitTests, "ArrayAppendUTF16", run_ArrayAppendUTF16) addTo(&precommitTests, "ArrayInClass", run_ArrayInClass) addTo(&precommitTests, "ArrayLiteral", run_ArrayLiteral) addTo(&precommitTests, "ArrayOfGenericPOD", run_ArrayOfGenericPOD) addTo(&precommitTests, "ArrayOfGenericRef", run_ArrayOfGenericRef) addTo(&precommitTests, "ArrayOfPOD", run_ArrayOfPOD) addTo(&precommitTests, "ArrayOfRef", run_ArrayOfRef) addTo(&precommitTests, "ArrayPlusEqualArrayOfInt", run_ArrayPlusEqualArrayOfInt) addTo(&precommitTests, "ArrayPlusEqualFiveElementCollection", run_ArrayPlusEqualFiveElementCollection) addTo(&precommitTests, "ArrayPlusEqualSingleElementCollection", run_ArrayPlusEqualSingleElementCollection) addTo(&precommitTests, "ArrayPlusEqualThreeElements", run_ArrayPlusEqualThreeElements) addTo(&precommitTests, "ArraySubscript", run_ArraySubscript) addTo(&precommitTests, "ArrayValueProp", run_ArrayValueProp) addTo(&precommitTests, "ArrayValueProp2", run_ArrayValueProp2) addTo(&precommitTests, "ArrayValueProp3", run_ArrayValueProp3) addTo(&precommitTests, "ArrayValueProp4", run_ArrayValueProp4) addTo(&precommitTests, "BitCount", run_BitCount) addTo(&precommitTests, "ByteSwap", run_ByteSwap) addTo(&precommitTests, "CStringLongAscii", run_CStringLongAscii) addTo(&precommitTests, "CStringLongNonAscii", run_CStringLongNonAscii) addTo(&precommitTests, "CStringShortAscii", run_CStringShortAscii) addTo(&precommitTests, "Calculator", run_Calculator) addTo(&precommitTests, "CaptureProp", run_CaptureProp) addTo(&precommitTests, "CharacterLiteralsLarge", run_CharacterLiteralsLarge) addTo(&precommitTests, "CharacterLiteralsSmall", run_CharacterLiteralsSmall) addTo(&precommitTests, "Chars", run_Chars) addTo(&precommitTests, "ClassArrayGetter", run_ClassArrayGetter) addTo(&precommitTests, "DeadArray", run_DeadArray) addTo(&precommitTests, "Dictionary", run_Dictionary) addTo(&precommitTests, "Dictionary2", run_Dictionary2) addTo(&precommitTests, "Dictionary2OfObjects", run_Dictionary2OfObjects) addTo(&precommitTests, "Dictionary3", run_Dictionary3) addTo(&precommitTests, "Dictionary3OfObjects", run_Dictionary3OfObjects) addTo(&precommitTests, "DictionaryBridge", run_DictionaryBridge) addTo(&precommitTests, "DictionaryLiteral", run_DictionaryLiteral) addTo(&precommitTests, "DictionaryOfObjects", run_DictionaryOfObjects) addTo(&precommitTests, "DictionaryRemove", run_DictionaryRemove) addTo(&precommitTests, "DictionaryRemoveOfObjects", run_DictionaryRemoveOfObjects) addTo(&precommitTests, "DictionarySwap", run_DictionarySwap) addTo(&precommitTests, "DictionarySwapOfObjects", run_DictionarySwapOfObjects) addTo(&precommitTests, "DropFirstAnyCollection", run_DropFirstAnyCollection) addTo(&precommitTests, "DropFirstAnyCollectionLazy", run_DropFirstAnyCollectionLazy) addTo(&precommitTests, "DropFirstAnySeqCRangeIter", run_DropFirstAnySeqCRangeIter) addTo(&precommitTests, "DropFirstAnySeqCRangeIterLazy", run_DropFirstAnySeqCRangeIterLazy) addTo(&precommitTests, "DropFirstAnySeqCntRange", run_DropFirstAnySeqCntRange) addTo(&precommitTests, "DropFirstAnySeqCntRangeLazy", run_DropFirstAnySeqCntRangeLazy) addTo(&precommitTests, "DropFirstAnySequence", run_DropFirstAnySequence) addTo(&precommitTests, "DropFirstAnySequenceLazy", run_DropFirstAnySequenceLazy) addTo(&precommitTests, "DropFirstArray", run_DropFirstArray) addTo(&precommitTests, "DropFirstArrayLazy", run_DropFirstArrayLazy) addTo(&precommitTests, "DropFirstCountableRange", run_DropFirstCountableRange) addTo(&precommitTests, "DropFirstCountableRangeLazy", run_DropFirstCountableRangeLazy) addTo(&precommitTests, "DropFirstSequence", run_DropFirstSequence) addTo(&precommitTests, "DropFirstSequenceLazy", run_DropFirstSequenceLazy) addTo(&precommitTests, "DropLastAnyCollection", run_DropLastAnyCollection) addTo(&precommitTests, "DropLastAnyCollectionLazy", run_DropLastAnyCollectionLazy) addTo(&precommitTests, "DropLastAnySeqCRangeIter", run_DropLastAnySeqCRangeIter) addTo(&precommitTests, "DropLastAnySeqCRangeIterLazy", run_DropLastAnySeqCRangeIterLazy) addTo(&precommitTests, "DropLastAnySeqCntRange", run_DropLastAnySeqCntRange) addTo(&precommitTests, "DropLastAnySeqCntRangeLazy", run_DropLastAnySeqCntRangeLazy) addTo(&precommitTests, "DropLastAnySequence", run_DropLastAnySequence) addTo(&precommitTests, "DropLastAnySequenceLazy", run_DropLastAnySequenceLazy) addTo(&precommitTests, "DropLastArray", run_DropLastArray) addTo(&precommitTests, "DropLastArrayLazy", run_DropLastArrayLazy) addTo(&precommitTests, "DropLastCountableRange", run_DropLastCountableRange) addTo(&precommitTests, "DropLastCountableRangeLazy", run_DropLastCountableRangeLazy) addTo(&precommitTests, "DropLastSequence", run_DropLastSequence) addTo(&precommitTests, "DropLastSequenceLazy", run_DropLastSequenceLazy) addTo(&precommitTests, "DropWhileAnyCollection", run_DropWhileAnyCollection) addTo(&precommitTests, "DropWhileAnyCollectionLazy", run_DropWhileAnyCollectionLazy) addTo(&precommitTests, "DropWhileAnySeqCRangeIter", run_DropWhileAnySeqCRangeIter) addTo(&precommitTests, "DropWhileAnySeqCRangeIterLazy", run_DropWhileAnySeqCRangeIterLazy) addTo(&precommitTests, "DropWhileAnySeqCntRange", run_DropWhileAnySeqCntRange) addTo(&precommitTests, "DropWhileAnySeqCntRangeLazy", run_DropWhileAnySeqCntRangeLazy) addTo(&precommitTests, "DropWhileAnySequence", run_DropWhileAnySequence) addTo(&precommitTests, "DropWhileAnySequenceLazy", run_DropWhileAnySequenceLazy) addTo(&precommitTests, "DropWhileArray", run_DropWhileArray) addTo(&precommitTests, "DropWhileArrayLazy", run_DropWhileArrayLazy) addTo(&precommitTests, "DropWhileCountableRange", run_DropWhileCountableRange) addTo(&precommitTests, "DropWhileCountableRangeLazy", run_DropWhileCountableRangeLazy) addTo(&precommitTests, "DropWhileSequence", run_DropWhileSequence) addTo(&precommitTests, "DropWhileSequenceLazy", run_DropWhileSequenceLazy) addTo(&precommitTests, "EqualStringSubstring", run_EqualStringSubstring) addTo(&precommitTests, "EqualSubstringString", run_EqualSubstringString) addTo(&precommitTests, "EqualSubstringSubstring", run_EqualSubstringSubstring) addTo(&precommitTests, "EqualSubstringSubstringGenericEquatable", run_EqualSubstringSubstringGenericEquatable) addTo(&precommitTests, "ErrorHandling", run_ErrorHandling) addTo(&precommitTests, "GlobalClass", run_GlobalClass) addTo(&precommitTests, "Hanoi", run_Hanoi) addTo(&precommitTests, "HashTest", run_HashTest) addTo(&precommitTests, "Histogram", run_Histogram) addTo(&precommitTests, "Integrate", run_Integrate) addTo(&precommitTests, "IterateData", run_IterateData) addTo(&precommitTests, "Join", run_Join) addTo(&precommitTests, "LazilyFilteredArrays", run_LazilyFilteredArrays) addTo(&precommitTests, "LazilyFilteredRange", run_LazilyFilteredRange) addTo(&precommitTests, "LessSubstringSubstring", run_LessSubstringSubstring) addTo(&precommitTests, "LessSubstringSubstringGenericComparable", run_LessSubstringSubstringGenericComparable) addTo(&precommitTests, "LinkedList", run_LinkedList) addTo(&precommitTests, "MapReduce", run_MapReduce) addTo(&precommitTests, "MapReduceAnyCollection", run_MapReduceAnyCollection) addTo(&precommitTests, "MapReduceAnyCollectionShort", run_MapReduceAnyCollectionShort) addTo(&precommitTests, "MapReduceClass", run_MapReduceClass) addTo(&precommitTests, "MapReduceClassShort", run_MapReduceClassShort) addTo(&precommitTests, "MapReduceLazyCollection", run_MapReduceLazyCollection) addTo(&precommitTests, "MapReduceLazyCollectionShort", run_MapReduceLazyCollectionShort) addTo(&precommitTests, "MapReduceLazySequence", run_MapReduceLazySequence) addTo(&precommitTests, "MapReduceSequence", run_MapReduceSequence) addTo(&precommitTests, "MapReduceShort", run_MapReduceShort) addTo(&precommitTests, "MapReduceShortString", run_MapReduceShortString) addTo(&precommitTests, "MapReduceString", run_MapReduceString) addTo(&precommitTests, "Memset", run_Memset) addTo(&precommitTests, "MonteCarloE", run_MonteCarloE) addTo(&precommitTests, "MonteCarloPi", run_MonteCarloPi) addTo(&precommitTests, "NSDictionaryCastToSwift", run_NSDictionaryCastToSwift) addTo(&precommitTests, "NSError", run_NSError) addTo(&precommitTests, "NSStringConversion", run_NSStringConversion) addTo(&precommitTests, "NopDeinit", run_NopDeinit) addTo(&precommitTests, "ObjectAllocation", run_ObjectAllocation) addTo(&precommitTests, "ObjectiveCBridgeFromNSArrayAnyObject", run_ObjectiveCBridgeFromNSArrayAnyObject) addTo(&precommitTests, "ObjectiveCBridgeFromNSArrayAnyObjectForced", run_ObjectiveCBridgeFromNSArrayAnyObjectForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSArrayAnyObjectToString", run_ObjectiveCBridgeFromNSArrayAnyObjectToString) addTo(&precommitTests, "ObjectiveCBridgeFromNSArrayAnyObjectToStringForced", run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSDictionaryAnyObject", run_ObjectiveCBridgeFromNSDictionaryAnyObject) addTo(&precommitTests, "ObjectiveCBridgeFromNSDictionaryAnyObjectForced", run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSDictionaryAnyObjectToString", run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString) addTo(&precommitTests, "ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced", run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSSetAnyObject", run_ObjectiveCBridgeFromNSSetAnyObject) addTo(&precommitTests, "ObjectiveCBridgeFromNSSetAnyObjectForced", run_ObjectiveCBridgeFromNSSetAnyObjectForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSSetAnyObjectToString", run_ObjectiveCBridgeFromNSSetAnyObjectToString) addTo(&precommitTests, "ObjectiveCBridgeFromNSSetAnyObjectToStringForced", run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced) addTo(&precommitTests, "ObjectiveCBridgeFromNSString", run_ObjectiveCBridgeFromNSString) addTo(&precommitTests, "ObjectiveCBridgeFromNSStringForced", run_ObjectiveCBridgeFromNSStringForced) addTo(&precommitTests, "ObjectiveCBridgeStubDataAppend", run_ObjectiveCBridgeStubDataAppend) addTo(&precommitTests, "ObjectiveCBridgeStubDateAccess", run_ObjectiveCBridgeStubDateAccess) addTo(&precommitTests, "ObjectiveCBridgeStubDateMutation", run_ObjectiveCBridgeStubDateMutation) addTo(&precommitTests, "ObjectiveCBridgeStubFromArrayOfNSString", run_ObjectiveCBridgeStubFromArrayOfNSString) addTo(&precommitTests, "ObjectiveCBridgeStubFromNSDate", run_ObjectiveCBridgeStubFromNSDate) addTo(&precommitTests, "ObjectiveCBridgeStubFromNSDateRef", run_ObjectiveCBridgeStubFromNSDateRef) addTo(&precommitTests, "ObjectiveCBridgeStubFromNSString", run_ObjectiveCBridgeStubFromNSString) addTo(&precommitTests, "ObjectiveCBridgeStubFromNSStringRef", run_ObjectiveCBridgeStubFromNSStringRef) addTo(&precommitTests, "ObjectiveCBridgeStubNSDataAppend", run_ObjectiveCBridgeStubNSDataAppend) addTo(&precommitTests, "ObjectiveCBridgeStubNSDateMutationRef", run_ObjectiveCBridgeStubNSDateMutationRef) addTo(&precommitTests, "ObjectiveCBridgeStubNSDateRefAccess", run_ObjectiveCBridgeStubNSDateRefAccess) addTo(&precommitTests, "ObjectiveCBridgeStubToArrayOfNSString", run_ObjectiveCBridgeStubToArrayOfNSString) addTo(&precommitTests, "ObjectiveCBridgeStubToNSDate", run_ObjectiveCBridgeStubToNSDate) addTo(&precommitTests, "ObjectiveCBridgeStubToNSDateRef", run_ObjectiveCBridgeStubToNSDateRef) addTo(&precommitTests, "ObjectiveCBridgeStubToNSString", run_ObjectiveCBridgeStubToNSString) addTo(&precommitTests, "ObjectiveCBridgeStubToNSStringRef", run_ObjectiveCBridgeStubToNSStringRef) addTo(&precommitTests, "ObjectiveCBridgeStubURLAppendPath", run_ObjectiveCBridgeStubURLAppendPath) addTo(&precommitTests, "ObjectiveCBridgeStubURLAppendPathRef", run_ObjectiveCBridgeStubURLAppendPathRef) addTo(&precommitTests, "ObjectiveCBridgeToNSArray", run_ObjectiveCBridgeToNSArray) addTo(&precommitTests, "ObjectiveCBridgeToNSDictionary", run_ObjectiveCBridgeToNSDictionary) addTo(&precommitTests, "ObjectiveCBridgeToNSSet", run_ObjectiveCBridgeToNSSet) addTo(&precommitTests, "ObjectiveCBridgeToNSString", run_ObjectiveCBridgeToNSString) addTo(&precommitTests, "ObserverClosure", run_ObserverClosure) addTo(&precommitTests, "ObserverForwarderStruct", run_ObserverForwarderStruct) addTo(&precommitTests, "ObserverPartiallyAppliedMethod", run_ObserverPartiallyAppliedMethod) addTo(&precommitTests, "ObserverUnappliedMethod", run_ObserverUnappliedMethod) addTo(&precommitTests, "OpenClose", run_OpenClose) addTo(&precommitTests, "Phonebook", run_Phonebook) addTo(&precommitTests, "PolymorphicCalls", run_PolymorphicCalls) addTo(&precommitTests, "PopFrontArray", run_PopFrontArray) addTo(&precommitTests, "PopFrontArrayGeneric", run_PopFrontArrayGeneric) addTo(&precommitTests, "PopFrontUnsafePointer", run_PopFrontUnsafePointer) addTo(&precommitTests, "PrefixAnyCollection", run_PrefixAnyCollection) addTo(&precommitTests, "PrefixAnyCollectionLazy", run_PrefixAnyCollectionLazy) addTo(&precommitTests, "PrefixAnySeqCRangeIter", run_PrefixAnySeqCRangeIter) addTo(&precommitTests, "PrefixAnySeqCRangeIterLazy", run_PrefixAnySeqCRangeIterLazy) addTo(&precommitTests, "PrefixAnySeqCntRange", run_PrefixAnySeqCntRange) addTo(&precommitTests, "PrefixAnySeqCntRangeLazy", run_PrefixAnySeqCntRangeLazy) addTo(&precommitTests, "PrefixAnySequence", run_PrefixAnySequence) addTo(&precommitTests, "PrefixAnySequenceLazy", run_PrefixAnySequenceLazy) addTo(&precommitTests, "PrefixArray", run_PrefixArray) addTo(&precommitTests, "PrefixArrayLazy", run_PrefixArrayLazy) addTo(&precommitTests, "PrefixCountableRange", run_PrefixCountableRange) addTo(&precommitTests, "PrefixCountableRangeLazy", run_PrefixCountableRangeLazy) addTo(&precommitTests, "PrefixSequence", run_PrefixSequence) addTo(&precommitTests, "PrefixSequenceLazy", run_PrefixSequenceLazy) addTo(&precommitTests, "PrefixWhileAnyCollection", run_PrefixWhileAnyCollection) addTo(&precommitTests, "PrefixWhileAnyCollectionLazy", run_PrefixWhileAnyCollectionLazy) addTo(&precommitTests, "PrefixWhileAnySeqCRangeIter", run_PrefixWhileAnySeqCRangeIter) addTo(&precommitTests, "PrefixWhileAnySeqCRangeIterLazy", run_PrefixWhileAnySeqCRangeIterLazy) addTo(&precommitTests, "PrefixWhileAnySeqCntRange", run_PrefixWhileAnySeqCntRange) addTo(&precommitTests, "PrefixWhileAnySeqCntRangeLazy", run_PrefixWhileAnySeqCntRangeLazy) addTo(&precommitTests, "PrefixWhileAnySequence", run_PrefixWhileAnySequence) addTo(&precommitTests, "PrefixWhileAnySequenceLazy", run_PrefixWhileAnySequenceLazy) addTo(&precommitTests, "PrefixWhileArray", run_PrefixWhileArray) addTo(&precommitTests, "PrefixWhileArrayLazy", run_PrefixWhileArrayLazy) addTo(&precommitTests, "PrefixWhileCountableRange", run_PrefixWhileCountableRange) addTo(&precommitTests, "PrefixWhileCountableRangeLazy", run_PrefixWhileCountableRangeLazy) addTo(&precommitTests, "PrefixWhileSequence", run_PrefixWhileSequence) addTo(&precommitTests, "PrefixWhileSequenceLazy", run_PrefixWhileSequenceLazy) addTo(&precommitTests, "Prims", run_Prims) addTo(&precommitTests, "ProtocolDispatch", run_ProtocolDispatch) addTo(&precommitTests, "ProtocolDispatch2", run_ProtocolDispatch2) addTo(&precommitTests, "RC4", run_RC4) addTo(&precommitTests, "RGBHistogram", run_RGBHistogram) addTo(&precommitTests, "RGBHistogramOfObjects", run_RGBHistogramOfObjects) addTo(&precommitTests, "RangeAssignment", run_RangeAssignment) addTo(&precommitTests, "RecursiveOwnedParameter", run_RecursiveOwnedParameter) addTo(&precommitTests, "ReversedArray", run_ReversedArray) addTo(&precommitTests, "ReversedBidirectional", run_ReversedBidirectional) addTo(&precommitTests, "ReversedDictionary", run_ReversedDictionary) addTo(&precommitTests, "SetExclusiveOr", run_SetExclusiveOr) addTo(&precommitTests, "SetExclusiveOr_OfObjects", run_SetExclusiveOr_OfObjects) addTo(&precommitTests, "SetIntersect", run_SetIntersect) addTo(&precommitTests, "SetIntersect_OfObjects", run_SetIntersect_OfObjects) addTo(&precommitTests, "SetIsSubsetOf", run_SetIsSubsetOf) addTo(&precommitTests, "SetIsSubsetOf_OfObjects", run_SetIsSubsetOf_OfObjects) addTo(&precommitTests, "SetUnion", run_SetUnion) addTo(&precommitTests, "SetUnion_OfObjects", run_SetUnion_OfObjects) addTo(&precommitTests, "SevenBoom", run_SevenBoom) addTo(&precommitTests, "Sim2DArray", run_Sim2DArray) addTo(&precommitTests, "SortLargeExistentials", run_SortLargeExistentials) addTo(&precommitTests, "SortLettersInPlace", run_SortLettersInPlace) addTo(&precommitTests, "SortSortedStrings", run_SortSortedStrings) addTo(&precommitTests, "SortStrings", run_SortStrings) addTo(&precommitTests, "SortStringsUnicode", run_SortStringsUnicode) addTo(&precommitTests, "StackPromo", run_StackPromo) addTo(&precommitTests, "StaticArray", run_StaticArray) addTo(&precommitTests, "StrComplexWalk", run_StrComplexWalk) addTo(&precommitTests, "StrToInt", run_StrToInt) addTo(&precommitTests, "StringAdder", run_StringAdder) addTo(&precommitTests, "StringBuilder", run_StringBuilder) addTo(&precommitTests, "StringBuilderLong", run_StringBuilderLong) addTo(&precommitTests, "StringEdits", run_StringEdits) addTo(&precommitTests, "StringEqualPointerComparison", run_StringEqualPointerComparison) addTo(&precommitTests, "StringFromLongWholeSubstring", run_StringFromLongWholeSubstring) addTo(&precommitTests, "StringFromLongWholeSubstringGeneric", run_StringFromLongWholeSubstringGeneric) addTo(&precommitTests, "StringHasPrefix", run_StringHasPrefix) addTo(&precommitTests, "StringHasPrefixUnicode", run_StringHasPrefixUnicode) addTo(&precommitTests, "StringHasSuffix", run_StringHasSuffix) addTo(&precommitTests, "StringHasSuffixUnicode", run_StringHasSuffixUnicode) addTo(&precommitTests, "StringInterpolation", run_StringInterpolation) addTo(&precommitTests, "StringMatch", run_StringMatch) addTo(&precommitTests, "StringUTF16Builder", run_StringUTF16Builder) addTo(&precommitTests, "StringWalk", run_StringWalk) addTo(&precommitTests, "StringWithCString", run_StringWithCString) addTo(&precommitTests, "SubstringFromLongString", run_SubstringFromLongString) addTo(&precommitTests, "SubstringFromLongStringGeneric", run_SubstringFromLongStringGeneric) addTo(&precommitTests, "SuffixAnyCollection", run_SuffixAnyCollection) addTo(&precommitTests, "SuffixAnyCollectionLazy", run_SuffixAnyCollectionLazy) addTo(&precommitTests, "SuffixAnySeqCRangeIter", run_SuffixAnySeqCRangeIter) addTo(&precommitTests, "SuffixAnySeqCRangeIterLazy", run_SuffixAnySeqCRangeIterLazy) addTo(&precommitTests, "SuffixAnySeqCntRange", run_SuffixAnySeqCntRange) addTo(&precommitTests, "SuffixAnySeqCntRangeLazy", run_SuffixAnySeqCntRangeLazy) addTo(&precommitTests, "SuffixAnySequence", run_SuffixAnySequence) addTo(&precommitTests, "SuffixAnySequenceLazy", run_SuffixAnySequenceLazy) addTo(&precommitTests, "SuffixArray", run_SuffixArray) addTo(&precommitTests, "SuffixArrayLazy", run_SuffixArrayLazy) addTo(&precommitTests, "SuffixCountableRange", run_SuffixCountableRange) addTo(&precommitTests, "SuffixCountableRangeLazy", run_SuffixCountableRangeLazy) addTo(&precommitTests, "SuffixSequence", run_SuffixSequence) addTo(&precommitTests, "SuffixSequenceLazy", run_SuffixSequenceLazy) addTo(&precommitTests, "SuperChars", run_SuperChars) addTo(&precommitTests, "TwoSum", run_TwoSum) addTo(&precommitTests, "TypeFlood", run_TypeFlood) addTo(&precommitTests, "UTF8Decode", run_UTF8Decode) addTo(&precommitTests, "Walsh", run_Walsh) addTo(&precommitTests, "XorLoop", run_XorLoop) // Other tests addTo(&otherTests, "Ackermann", run_Ackermann) addTo(&otherTests, "ExistentialTestArrayConditionalShift_ClassValueBuffer1", run_ExistentialTestArrayConditionalShift_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestArrayConditionalShift_ClassValueBuffer2", run_ExistentialTestArrayConditionalShift_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestArrayConditionalShift_ClassValueBuffer3", run_ExistentialTestArrayConditionalShift_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestArrayConditionalShift_ClassValueBuffer4", run_ExistentialTestArrayConditionalShift_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestArrayConditionalShift_IntValueBuffer0", run_ExistentialTestArrayConditionalShift_IntValueBuffer0) addTo(&otherTests, "ExistentialTestArrayConditionalShift_IntValueBuffer1", run_ExistentialTestArrayConditionalShift_IntValueBuffer1) addTo(&otherTests, "ExistentialTestArrayConditionalShift_IntValueBuffer2", run_ExistentialTestArrayConditionalShift_IntValueBuffer2) addTo(&otherTests, "ExistentialTestArrayConditionalShift_IntValueBuffer3", run_ExistentialTestArrayConditionalShift_IntValueBuffer3) addTo(&otherTests, "ExistentialTestArrayConditionalShift_IntValueBuffer4", run_ExistentialTestArrayConditionalShift_IntValueBuffer4) addTo(&otherTests, "ExistentialTestArrayMutating_ClassValueBuffer1", run_ExistentialTestArrayMutating_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestArrayMutating_ClassValueBuffer2", run_ExistentialTestArrayMutating_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestArrayMutating_ClassValueBuffer3", run_ExistentialTestArrayMutating_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestArrayMutating_ClassValueBuffer4", run_ExistentialTestArrayMutating_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestArrayMutating_IntValueBuffer0", run_ExistentialTestArrayMutating_IntValueBuffer0) addTo(&otherTests, "ExistentialTestArrayMutating_IntValueBuffer1", run_ExistentialTestArrayMutating_IntValueBuffer1) addTo(&otherTests, "ExistentialTestArrayMutating_IntValueBuffer2", run_ExistentialTestArrayMutating_IntValueBuffer2) addTo(&otherTests, "ExistentialTestArrayMutating_IntValueBuffer3", run_ExistentialTestArrayMutating_IntValueBuffer3) addTo(&otherTests, "ExistentialTestArrayMutating_IntValueBuffer4", run_ExistentialTestArrayMutating_IntValueBuffer4) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_ClassValueBuffer1", run_ExistentialTestArrayOneMethodCall_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_ClassValueBuffer2", run_ExistentialTestArrayOneMethodCall_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_ClassValueBuffer3", run_ExistentialTestArrayOneMethodCall_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_ClassValueBuffer4", run_ExistentialTestArrayOneMethodCall_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_IntValueBuffer0", run_ExistentialTestArrayOneMethodCall_IntValueBuffer0) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_IntValueBuffer1", run_ExistentialTestArrayOneMethodCall_IntValueBuffer1) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_IntValueBuffer2", run_ExistentialTestArrayOneMethodCall_IntValueBuffer2) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_IntValueBuffer3", run_ExistentialTestArrayOneMethodCall_IntValueBuffer3) addTo(&otherTests, "ExistentialTestArrayOneMethodCall_IntValueBuffer4", run_ExistentialTestArrayOneMethodCall_IntValueBuffer4) addTo(&otherTests, "ExistentialTestArrayShift_ClassValueBuffer1", run_ExistentialTestArrayShift_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestArrayShift_ClassValueBuffer2", run_ExistentialTestArrayShift_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestArrayShift_ClassValueBuffer3", run_ExistentialTestArrayShift_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestArrayShift_ClassValueBuffer4", run_ExistentialTestArrayShift_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestArrayShift_IntValueBuffer0", run_ExistentialTestArrayShift_IntValueBuffer0) addTo(&otherTests, "ExistentialTestArrayShift_IntValueBuffer1", run_ExistentialTestArrayShift_IntValueBuffer1) addTo(&otherTests, "ExistentialTestArrayShift_IntValueBuffer2", run_ExistentialTestArrayShift_IntValueBuffer2) addTo(&otherTests, "ExistentialTestArrayShift_IntValueBuffer3", run_ExistentialTestArrayShift_IntValueBuffer3) addTo(&otherTests, "ExistentialTestArrayShift_IntValueBuffer4", run_ExistentialTestArrayShift_IntValueBuffer4) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_ClassValueBuffer1", run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_ClassValueBuffer2", run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_ClassValueBuffer3", run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_ClassValueBuffer4", run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_IntValueBuffer0", run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer0) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_IntValueBuffer1", run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer1) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_IntValueBuffer2", run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer2) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_IntValueBuffer3", run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer3) addTo(&otherTests, "ExistentialTestArrayTwoMethodCalls_IntValueBuffer4", run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer4) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_ClassValueBuffer1", run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_ClassValueBuffer2", run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_ClassValueBuffer3", run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_ClassValueBuffer4", run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_IntValueBuffer0", run_ExistentialTestMutatingAndNonMutating_IntValueBuffer0) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_IntValueBuffer1", run_ExistentialTestMutatingAndNonMutating_IntValueBuffer1) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_IntValueBuffer2", run_ExistentialTestMutatingAndNonMutating_IntValueBuffer2) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_IntValueBuffer3", run_ExistentialTestMutatingAndNonMutating_IntValueBuffer3) addTo(&otherTests, "ExistentialTestMutatingAndNonMutating_IntValueBuffer4", run_ExistentialTestMutatingAndNonMutating_IntValueBuffer4) addTo(&otherTests, "ExistentialTestMutating_ClassValueBuffer1", run_ExistentialTestMutating_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestMutating_ClassValueBuffer2", run_ExistentialTestMutating_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestMutating_ClassValueBuffer3", run_ExistentialTestMutating_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestMutating_ClassValueBuffer4", run_ExistentialTestMutating_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestMutating_IntValueBuffer0", run_ExistentialTestMutating_IntValueBuffer0) addTo(&otherTests, "ExistentialTestMutating_IntValueBuffer1", run_ExistentialTestMutating_IntValueBuffer1) addTo(&otherTests, "ExistentialTestMutating_IntValueBuffer2", run_ExistentialTestMutating_IntValueBuffer2) addTo(&otherTests, "ExistentialTestMutating_IntValueBuffer3", run_ExistentialTestMutating_IntValueBuffer3) addTo(&otherTests, "ExistentialTestMutating_IntValueBuffer4", run_ExistentialTestMutating_IntValueBuffer4) addTo(&otherTests, "ExistentialTestOneMethodCall_ClassValueBuffer1", run_ExistentialTestOneMethodCall_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestOneMethodCall_ClassValueBuffer2", run_ExistentialTestOneMethodCall_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestOneMethodCall_ClassValueBuffer3", run_ExistentialTestOneMethodCall_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestOneMethodCall_ClassValueBuffer4", run_ExistentialTestOneMethodCall_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestOneMethodCall_IntValueBuffer0", run_ExistentialTestOneMethodCall_IntValueBuffer0) addTo(&otherTests, "ExistentialTestOneMethodCall_IntValueBuffer1", run_ExistentialTestOneMethodCall_IntValueBuffer1) addTo(&otherTests, "ExistentialTestOneMethodCall_IntValueBuffer2", run_ExistentialTestOneMethodCall_IntValueBuffer2) addTo(&otherTests, "ExistentialTestOneMethodCall_IntValueBuffer3", run_ExistentialTestOneMethodCall_IntValueBuffer3) addTo(&otherTests, "ExistentialTestOneMethodCall_IntValueBuffer4", run_ExistentialTestOneMethodCall_IntValueBuffer4) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer1", run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer2", run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer3", run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer4", run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_IntValueBuffer0", run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer0) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_IntValueBuffer1", run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer1) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_IntValueBuffer2", run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer2) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_IntValueBuffer3", run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer3) addTo(&otherTests, "ExistentialTestPassExistentialOneMethodCall_IntValueBuffer4", run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer4) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer1", run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer2", run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer3", run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer4", run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer0", run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer0) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer1", run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer1) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer2", run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer2) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer3", run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer3) addTo(&otherTests, "ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer4", run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer4) addTo(&otherTests, "ExistentialTestTwoMethodCalls_ClassValueBuffer1", run_ExistentialTestTwoMethodCalls_ClassValueBuffer1) addTo(&otherTests, "ExistentialTestTwoMethodCalls_ClassValueBuffer2", run_ExistentialTestTwoMethodCalls_ClassValueBuffer2) addTo(&otherTests, "ExistentialTestTwoMethodCalls_ClassValueBuffer3", run_ExistentialTestTwoMethodCalls_ClassValueBuffer3) addTo(&otherTests, "ExistentialTestTwoMethodCalls_ClassValueBuffer4", run_ExistentialTestTwoMethodCalls_ClassValueBuffer4) addTo(&otherTests, "ExistentialTestTwoMethodCalls_IntValueBuffer0", run_ExistentialTestTwoMethodCalls_IntValueBuffer0) addTo(&otherTests, "ExistentialTestTwoMethodCalls_IntValueBuffer1", run_ExistentialTestTwoMethodCalls_IntValueBuffer1) addTo(&otherTests, "ExistentialTestTwoMethodCalls_IntValueBuffer2", run_ExistentialTestTwoMethodCalls_IntValueBuffer2) addTo(&otherTests, "ExistentialTestTwoMethodCalls_IntValueBuffer3", run_ExistentialTestTwoMethodCalls_IntValueBuffer3) addTo(&otherTests, "ExistentialTestTwoMethodCalls_IntValueBuffer4", run_ExistentialTestTwoMethodCalls_IntValueBuffer4) addTo(&otherTests, "Fibonacci", run_Fibonacci) addTo(&otherTests, "HashQuadratic", run_HashQuadratic) // String tests, an extended benchmark suite exercising finer-granularity // behavior of our Strings. addTo(&stringTests, "StringWalk_ascii_characters", run_StringWalk_ascii_characters) addTo(&stringTests, "StringWalk_ascii_characters_Backwards", run_StringWalk_ascii_characters_Backwards) addTo(&stringTests, "StringWalk_ascii_unicodeScalars", run_StringWalk_ascii_unicodeScalars) addTo(&stringTests, "StringWalk_ascii_unicodeScalars_Backwards", run_StringWalk_ascii_unicodeScalars_Backwards) addTo(&stringTests, "StringWalk_chinese_characters", run_StringWalk_chinese_characters) addTo(&stringTests, "StringWalk_chinese_characters_Backwards", run_StringWalk_chinese_characters_Backwards) addTo(&stringTests, "StringWalk_chinese_unicodeScalars", run_StringWalk_chinese_unicodeScalars) addTo(&stringTests, "StringWalk_chinese_unicodeScalars_Backwards", run_StringWalk_chinese_unicodeScalars_Backwards) addTo(&stringTests, "StringWalk_japanese_characters", run_StringWalk_japanese_characters) addTo(&stringTests, "StringWalk_japanese_characters_Backwards", run_StringWalk_japanese_characters_Backwards) addTo(&stringTests, "StringWalk_japanese_unicodeScalars", run_StringWalk_japanese_unicodeScalars) addTo(&stringTests, "StringWalk_japanese_unicodeScalars_Backwards", run_StringWalk_japanese_unicodeScalars_Backwards) addTo(&stringTests, "StringWalk_korean_characters", run_StringWalk_korean_characters) addTo(&stringTests, "StringWalk_korean_characters_Backwards", run_StringWalk_korean_characters_Backwards) addTo(&stringTests, "StringWalk_korean_unicodeScalars", run_StringWalk_korean_unicodeScalars) addTo(&stringTests, "StringWalk_korean_unicodeScalars_Backwards", run_StringWalk_korean_unicodeScalars_Backwards) addTo(&stringTests, "StringWalk_tweet_characters", run_StringWalk_tweet_characters) addTo(&stringTests, "StringWalk_tweet_characters_Backwards", run_StringWalk_tweet_characters_Backwards) addTo(&stringTests, "StringWalk_tweet_unicodeScalars", run_StringWalk_tweet_unicodeScalars) addTo(&stringTests, "StringWalk_tweet_unicodeScalars_Backwards", run_StringWalk_tweet_unicodeScalars_Backwards) addTo(&stringTests, "StringWalk_utf16_characters", run_StringWalk_utf16_characters) addTo(&stringTests, "StringWalk_utf16_characters_Backwards", run_StringWalk_utf16_characters_Backwards) addTo(&stringTests, "StringWalk_utf16_unicodeScalars", run_StringWalk_utf16_unicodeScalars) addTo(&stringTests, "StringWalk_utf16_unicodeScalars_Backwards", run_StringWalk_utf16_unicodeScalars_Backwards) main()
apache-2.0
b6cf409b9a6b89a666ac9042778b6c6b
71.198895
152
0.858356
5.180917
false
true
false
false
DMeechan/Rick-and-Morty-Soundboard
Rick and Morty Soundboard/Pods/Eureka/Source/Validations/RuleLength.swift
3
2943
// RuleLength.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct RuleMinLength: RuleType { let min: UInt public var id: String? public var validationError: ValidationError public init(minLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have at least \(minLength) characters" min = minLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.characters.count < Int(min) ? validationError : nil } } public struct RuleMaxLength: RuleType { let max: UInt public var id: String? public var validationError: ValidationError public init(maxLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters" max = maxLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.characters.count > Int(max) ? validationError : nil } } public struct RuleExactLength: RuleType { let length: UInt public var id: String? public var validationError: ValidationError public init(exactLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters" length = exactLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.characters.count != Int(length) ? validationError : nil } }
apache-2.0
946a9918f850fdc0bf0e3f64943d3966
35.333333
86
0.697587
4.605634
false
false
false
false
qinting513/PandaTV
PandaTV/PandaTV/Classes/Tools/Common.swift
1
409
// // Common.swift // PandaTV // // Created by QinTing on 2017/9/14. // Copyright © 2017年 QinTing. All rights reserved. // import UIKit let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height let kStatusBarHeight: CGFloat = 20 let kNavigationBarHeight: CGFloat = 44 let kTabBarHeight: CGFloat = 49 let kBgColor = UIColor(gray: 244) class Common: NSObject { }
apache-2.0
059c272c5c9d47de83468165044b9dc5
19.3
51
0.736453
3.383333
false
false
false
false
kylef/Requests
Sources/URL.swift
1
838
struct URL { let scheme: String let hostname: String let port: Int16 let path: String init?(string: String) { let parts = string.split("://", maxSplit: 1) if parts.count != 2 { scheme = "" hostname = "" port = 80 path = "" return nil } scheme = parts[0] let parts1 = parts[1].split("/") if parts1.count < 2 { hostname = "" port = 80 path = "" return nil } path = "/" + parts1[1..<parts1.count].joinWithSeparator("/") let address = parts1[0] let parts2 = address.split(":", maxSplit: 1) if parts2.count > 1 { hostname = parts2[0] if let port = Int16(parts2[1]) { self.port = port } else { port = 80 return nil } } else { hostname = address port = 80 } } }
bsd-2-clause
249c9969821e8c6929aaa77d379d7b3c
18.045455
64
0.502387
3.707965
false
false
false
false
arjungupta99/SwiftChess
SwiftChess/Pieces/King.swift
1
2505
// // King.swift // Chess // // Created by Arjun Gupta on 2/24/16. // Copyright © 2016 ArjunGupta. All rights reserved. // import Foundation class King:Piece { var hasCheck = false var castlingPossible = true override func canMove(end end:(Int, Int), endPiece:Piece? = nil, registeredMove:Bool = true) -> Bool { let start = self.position //Castling if (self.castlingPossible == true && endPiece == nil && self.hasCheck == false) { if (abs(end.0 - start.0) == 2 && self.board.checkClearStraightPath(start: start, end: end) == true) { var rookPiece:Piece? var rookStartSquare:Square? var rookEndSquare:Square? if (end.0 - start.0 == -2) { //Left side rookStartSquare = (self.colorIsWhite == true) ? self.board.squares[0][0] : board.squares[7][0] rookEndSquare = (self.colorIsWhite == true) ? self.board.squares[0][3] : board.squares[7][3] rookPiece = rookStartSquare!.occupyingPiece } else { //Right side rookStartSquare = (self.colorIsWhite == true) ? self.board.squares[0][7] : board.squares[7][7] rookEndSquare = (self.colorIsWhite == true) ? self.board.squares[0][5] : board.squares[7][5] rookPiece = rookStartSquare!.occupyingPiece } if let theRook = rookPiece as? Rook { if (theRook.castlingPossible == true) { self.board.moveOccupyingPieceFromSquare(rookStartSquare!, endSquare: rookEndSquare!) DebugLog("Casteling Executed") return true } } } } if (abs(end.0 - start.0) > 1 || abs(end.1 - start.1) > 1) { return false } if (abs(end.0 - start.0) == 1 || abs(end.1 - start.1) == 1) { return true } return false } override func name() -> String { return "king" } override func didMove() { self.castlingPossible = false } override func getMovementPath(end:(Int, Int)) -> [Square]? { return nil } }
mit
fa508f1d7e9b977e4f418bb7edef6266
31.960526
114
0.476038
4.104918
false
false
false
false
paulicelli/RadioButton
RadioButton/RadioButtonsView.swift
1
4372
/* ------------------------------------------------------------------------------ MIT License Copyright (c) 2017 Sabino Paulicelli 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. ------------------------------------------------------------------------------ RadioButtonsView.swift ------------------------------------------------------------------------------ */ import UIKit @objc protocol RadioButtonsViewDelegate { @objc optional func didSelectButton(_ aButton: RoundButton?) } @IBDesignable class RadioButtonsView: UIStackView { var shouldLetDeselect = true var buttons = [RoundButton]() weak var delegate : RadioButtonsViewDelegate? = nil private(set) weak var currentSelectedButton: RoundButton? = nil @IBInspectable var number: Int = 2 { didSet { number = max(number, 2) setupButtons() } } func setupButtons() { if !buttons.isEmpty { buttons.forEach { self.removeArrangedSubview($0) } buttons.removeAll() } for i in 0..<self.number { let button = RoundButton() button.setTitle("\(i)", for: .normal) button.addTarget(self, action: #selector(pressed(_:)), for: UIControlEvents.touchUpInside) buttons.append(button) } } func pressed(_ sender: RoundButton) { if (sender.isSelected) { if shouldLetDeselect { sender.isSelected = false currentSelectedButton = nil } }else { buttons.forEach { $0.isSelected = false } sender.isSelected = true currentSelectedButton = sender } delegate?.didSelectButton?(currentSelectedButton) } override init(frame: CGRect) { super.init(frame: frame) setupButtons() } required init(coder: NSCoder) { super.init(coder: coder) setupButtons() } override var intrinsicContentSize: CGSize { return CGSize(width: self.bounds.width, height: UIViewNoIntrinsicMetric) } override func layoutSubviews() { self.translatesAutoresizingMaskIntoConstraints = false buttons.forEach { self.addArrangedSubview($0) } let constraints: [NSLayoutConstraint] = { var constraints = [NSLayoutConstraint]() constraints.append(NSLayoutConstraint(item: buttons[0], attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0) ) for i in 1..<buttons.count { constraints.append(NSLayoutConstraint(item: buttons[i], attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: buttons[i - 1], attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0) ) } return constraints }() self.addConstraints(constraints) } }
mit
0eed2085ad0d5692dd9a36efe259b470
31.87218
85
0.57022
5.730013
false
false
false
false
dongdonggaui/FakeWeChat
FakeWeChat/src/Utls/AppContext.swift
1
4808
// // AppContext.swift // FakeWeChat // // Created by huangluyang on 15/12/28. // Copyright © 2015年 huangluyang. All rights reserved. // import UIKit import Chameleon import Kingfisher class AppContext : NSObject { enum IconSizeType : Int { case Smallest case Small case Middle case Big case Biggest } enum IconStyle : Int { case Square case Round case RoundCorner } struct ImageCacheKey { static let SearchTimelineIcon = "searchTimeline" static let SearchArticleIcon = "searchArticel" static let SearchCelebrityIcon = "searchCelebrity" static let RedirectIcon = "redirect" static let CollectIcon = "collect" static let DeleteIcon = "delelte" static let MoreIcon = "more" } // MARK: - Global Resource static let globalImageCache = KingfisherManager.sharedManager.cache // MARK: - Placeholder static func avatarPlaceholder() -> UIImage { var avatar = imageWithCacheKey("avatarPlaceholder") if avatar == nil { avatar = UIImage.fontAwesomeIconWithName(.User, textColor: UIColor.whiteColor(), size: CGSizeMake(36, 36)).squared(UIColor.lightGrayColor(), style: .Square) let imageData = UIImageJPEGRepresentation(avatar!, 0.9) globalImageCache.storeImage(avatar!, originalData: imageData, forKey: "avatarPlaceholder") } return avatar! } // MARK: - Conversation // MARK: - Search Resource static let globalSearchTintColor = FlatSkyBlueDark() static func globalSearchTimelineIcon(sizeType: IconSizeType = .Biggest) -> UIImage { return clearIcon(withTitle: "圈", sizeType: sizeType).backgrounded(FlatBlue()) } static func globalSearchArticleIcon(sizeType: IconSizeType = .Biggest) -> UIImage { return clearIcon(withTitle: "文", sizeType: sizeType).backgrounded(FlatPink()) } static func globalSearchCelebrityIcon(sizeType: IconSizeType = .Biggest) -> UIImage { return clearIcon(withTitle: "众", sizeType: sizeType).backgrounded(FlatSand()) } // MARK: - Message List Resource static let messageListViewTextDrawAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.boldSystemFontOfSize(17)] static let messageListViewFunctionToolbarIconSize = CGSizeMake(24, 24) static func redirectIcon() -> UIImage { return icon(withTitle: "转", sizeType: .Big, style: .RoundCorner) } static func collectIcon() -> UIImage { return icon(withTitle: "藏", sizeType: .Big, style: .RoundCorner) } static func deleteIcon() -> UIImage { return icon(withTitle: "删", sizeType: .Big, style: .RoundCorner) } static func moreIcon() -> UIImage { return icon(withTitle: "···", sizeType: .Big, style: .RoundCorner) } // MARK: - Utilities static func clearIcon(withTitle title: String, sizeType: IconSizeType = .Middle) -> UIImage { return icon(withTitle: title, sizeType: sizeType, style: .Square, backgroundColor: UIColor.clearColor(), foregroundColor: UIColor.whiteColor()) } static func icon(withTitle title: String, sizeType: IconSizeType = .Big, style: IconStyle = .Round, backgroundColor: UIColor = FlatBlue(), foregroundColor: UIColor = UIColor.whiteColor()) -> UIImage { let firstChar = title.substringToIndex(title.startIndex.advancedBy(1)) let cacheKey = firstChar.cacheKey(sizeType) var image = imageWithCacheKey(cacheKey) if image == nil { let imageSize = CGSize.size(sizeType) let attributes = [NSForegroundColorAttributeName: foregroundColor, NSFontAttributeName: UIFont.boldSystemFontOfSize(CGFloat.fontSize(sizeType))] image = UIImage.tq_imageFromString(title, backgroundColor: backgroundColor, attributes: attributes, size: imageSize) ?? UIImage(color: foregroundColor, size: imageSize) globalImageCache.storeImage(image!, originalData: UIImagePNGRepresentation(image!), forKey: cacheKey) } return image! } static func imageWithCacheKey(key: String) -> UIImage? { let cachedResult = globalImageCache.isImageCachedForKey(key) var cachedImage: UIImage? = nil if let cacheType = cachedResult.cacheType { switch cacheType { case .Memory: cachedImage = globalImageCache.retrieveImageInMemoryCacheForKey(key) case .Disk: cachedImage = globalImageCache.retrieveImageInDiskCacheForKey(key, scale: UIScreen.mainScreen().scale) default: break } } return cachedImage } }
mit
8f01a7ef10725bfaa220007e1c60f85c
38.586777
204
0.665762
4.804413
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_301_SellMainController.swift
1
11855
// // SLV_301_SellMainController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 판매 메인 컨트롤러 */ import Foundation import UIKit import SnapKit import RealmSwift class SLV_301_SellMainController: SLVBaseStatusHiddenController { var tr_presentTransition: TRViewControllerTransitionDelegate? @IBOutlet weak var directButton: UIButton! @IBOutlet weak var balletButton: UIButton! @IBOutlet weak var sellGuideButton: UIButton! @IBOutlet weak var saveListButton: UIButton! @IBOutlet weak var callKakaoButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var saveView: UIView! @IBOutlet weak var kakaoView: UIView! @IBOutlet weak var saveLabel: UILabel! @IBOutlet weak var kakaoLabel: UILabel! @IBOutlet weak var topForLogo: NSLayoutConstraint! @IBOutlet weak var topForTitle: NSLayoutConstraint! @IBOutlet weak var topForDirectButton: NSLayoutConstraint! @IBOutlet weak var topForGuide: NSLayoutConstraint! var aniObjects: [AnyObject]? override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } func settupLayout() { let height = UIScreen.main.bounds.size.height self.topForLogo.constant = height * 0.131 self.topForTitle.constant = height * 0.042 self.topForDirectButton.constant = height * 0.057 self.topForGuide.constant = height * 0.028 self.closeButton.translatesAutoresizingMaskIntoConstraints = false self.kakaoView.translatesAutoresizingMaskIntoConstraints = false self.saveView.translatesAutoresizingMaskIntoConstraints = false self.resetAppearLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(false) tabController.hideFab() // self.setupAppearAnimation() self.resetSellerData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.isNavigationBarHidden = true self.navigationBar?.barHeight = 0 self.playAppearAnimation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.resetAppearLayout() } override func viewDidLoad() { super.viewDidLoad() self.settupLayout() self.readyInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func resetSellerData() { TempInputInfoModel.shared.isGenderPass = false } func readyInfo() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let closeHidePoint = CGPoint(x: w, y: h) //46, 16 //65, 85 let w_spacing = CGFloat(16 + 32) let h_spacing = CGFloat(46 + 42) let h_spacing_close = CGFloat(16 + 16) let v_height = h - h_spacing let v_height_close = h - h_spacing_close let tempPoint = CGPoint(x: w_spacing, y: v_height) let kakaoPoint = CGPoint(x: (w*2) - w_spacing, y: v_height) let closePoint = CGPoint(x: w, y: v_height_close) let views = [ [self.saveView, tempPoint, closeHidePoint], [self.kakaoView, kakaoPoint, closeHidePoint], [self.closeButton, closePoint, closeHidePoint]] self.aniObjects = views as [AnyObject]? } func resetAppearLayout() { //46, 16 //65, 85 self.kakaoLabel.isHidden = true self.saveLabel.isHidden = true self.kakaoView.isHidden = true self.saveView.isHidden = true self.closeButton.isHidden = true let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let views = [self.saveView, self.kakaoView, self.closeButton] _ = views.map() { let view = $0! as UIView // view.cheetah.move(w, h).run() // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) view.snp.remakeConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } } } func setupAppearAnimation() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height self.closeButton.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.kakaoView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.saveView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } // _ = self.aniObjects!.map() { // let list = $0 as! [AnyObject] // let hide = list.last as! CGPoint // let view = list.first as! UIView // view.isHidden = true // let point = list[1] as! CGPoint // let x = hide.x - point.x // let y = hide.y - point.y //// view.cheetah.move(x, y).delay(0.01).wait(0.02).run().remove() //// RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) // } } func playAppearAnimation() { // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1)) _ = self.aniObjects!.map() { let list = $0 as! [AnyObject] (list.first as! UIView).isHidden = false let point = list[1] as! CGPoint let hide = list.last as! CGPoint let x = point.x - hide.x let y = point.y - hide.y let view = list.first as! UIView view.cheetah.move(x, y).duration(0.2).delay(0.01).easeInBack.wait(0.02).run() RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) } self.kakaoLabel.isHidden = false self.saveLabel.isHidden = false } @IBAction func touchDirectSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = true TempInputInfoModel.shared.isNewCase = true } @IBAction func touchBalletSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = false TempInputInfoModel.shared.isNewCase = true } @IBAction func touchPopupGuide(_ sender: Any) { } @IBAction func touchTempList(_ sender: Any) { let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "saveListNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLV_3a2_SellTempSaveListController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.twitter) { print("Present finished.") } } @IBAction func touchKakao(_ sender: Any) { // let board = UIStoryboard(name:"Sell", bundle: nil) // let controller = board.instantiateViewController(withIdentifier: "SLV_361_SellDirectFinalSNSShareController") as! SLV_361_SellDirectFinalSNSShareController // self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { // } let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "addrNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLVAddressSearchController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.fade) { print("Present finished.") } } @IBAction func touchSellClose(_ sender: Any) { TempInputInfoModel.shared.saveCurrentModel() tabController.closePresent() { } } } extension SLV_301_SellMainController: ModalTransitionDelegate { func modalViewControllerDismiss(callbackData data:AnyObject?) { log.debug("SLV_301_SellMainController.modalViewControllerDismiss(callbackData:)") tr_dismissViewController(completion: { if let back = data { let cb = back as! [String: AnyObject] let key = cb["command"] as! String if key != nil { if key == "next" { let step = cb["step"] as! Int let board = UIStoryboard(name:"Sell", bundle: nil) switch step { case 1: self.delay(time: 0.2) { let controller = board.instantiateViewController(withIdentifier: "SLV_380_SellBallet1SellerInfoController") as! SLV_380_SellBallet1SellerInfoController self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 2: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_320_SellDirectStep2ItemInfoController") as! SLV_320_SellDirectStep2ItemInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 3: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_330_SellDirectStep3AdditionalInfoController") as! SLV_330_SellDirectStep3AdditionalInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 4: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_340_SellDirectStep4PriceController") as! SLV_340_SellDirectStep4PriceController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 5: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_350_SellDirectStep5SellerInfoController") as! SLV_350_SellDirectStep5SellerInfoController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break default: break } } } } }) } }
mit
0fb55202a12d02acce0e6ff032f14259
40.363636
204
0.592646
4.852338
false
false
false
false
OatmealCode/Oatmeal
Pod/Classes/Container/Reflections.swift
1
3353
// // Reflections.swift // Pods // // Created by Michael Kantor on 12/17/15. // // import Foundation //Used to store already reflected classes public class Reflections : Resolveable { public static var entityName : String? = "Reflections" typealias reflected = [String: properties] private var mirrors : reflected public subscript(key : String) -> properties?{ get{ return get(key) } set(newProp) { if let value = newProp { set(key,value : value) } } } public required init() { mirrors = reflected() } public func get(key:String) -> properties? { if let mirror = mirrors[key] { return mirror } return nil } static func getBundleName(member : Resolveable? = nil) -> String { var bundleName = NSBundle.mainBundle() if let m = member as? AnyObject { bundleName = NSBundle(forClass: m.dynamicType) } let name = String(bundleName.infoDictionary?["CFBundleName"]) return name .replace(" ", withString: "_") .replace("-", withString: "_") } public func set(key:String, value : properties) { var props = value let resolutionAttempts = Property() resolutionAttempts.value = 0 resolutionAttempts.label = "resolutionAttempts" props["resolutionAttempts"] = resolutionAttempts mirrors[key] = props } public func reflect(member:Resolveable) -> properties { var reflectedProperties = properties() let reflectedMember = Mirror(reflecting: member) //First we're going to reflect the type and grab the types of properties if let children = AnyRandomAccessCollection(reflectedMember.children) { for (optionalPropertyName, value) in children { if let name = optionalPropertyName { let propMirror = Mirror(reflecting: value) let type = Reflections.open(value) let property = Property(mirror: propMirror, label : name,value : value, type : type) if let (_,optionalValue) = propMirror.children.first where propMirror.children.count != 0 { property.unwrappedOptional = optionalValue } reflectedProperties[name] = property } } } self[member.getName()] = reflectedProperties return reflectedProperties } class func open(any: Any?) -> Any.Type { let mi = Mirror(reflecting: any) if let children = AnyRandomAccessCollection(mi.children) { if mi.children.count == 0 { return NullElement.self } for (_, value) in children { return value.dynamicType } } return mi.subjectType } public func has(key:String)->Bool { return get(key) != nil } }
mit
d24575c5774f36ed6dd6e9e508ef47bc
25.409449
110
0.515956
5.247261
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Service/Network/BBGenerator.swift
1
7695
// // BBGenerator.swift // bitboylabs-ios-base // // Created by 조백근 on 2016. 10. 17.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import Foundation import Alamofire import ReachabilitySwift //import Argo /* Alamofire 참고 : https://github.com/Alamofire/Alamofire */ class BBGenerator: NSObject { public typealias recvCallBack = (AnyObject, Bool) -> Void let reachability = Reachability(hostname: SLV_URL)! // 싱글턴. static let shared = BBGenerator() override private init() { super.init() // 초기화. workReachability() } //MARK: alamofire 샘플 func searchAlbulms(_ keyword: String, done: @escaping recvCallBack) { /* var param: [String: AnyObject] = [:] param = param.merge(dict: itunes_param_base) param = param.merge(dict: ["term": keyword as AnyObject]) Alamofire.request(itunes_api_url, method: .get, parameters: param) .responseJSON { response in // if let val = response.result.value { if let data = response.data { // let json: JSON = JSON(val)["results"] let json: Dictionary<String, AnyObject>? /*Any?*/ = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, AnyObject> if json != nil { log.debug(json.debugDescription) // let count = json!["resultCount"] as! Int let result = json!["results"] as! AnyObject done(result, true) } else { log.error("Error: no data!") done(empty, false) } }else{ log.error("Error: \(response)") done(empty, false) } } */ //moya itunesProvider.request(.searchAlbums(keyword)) { result in // log.info("moya response") // log.debug(result.debugDescription) switch result { case let .success(moyaResponse): let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etc log.info("status code : \(statusCode)") let json: Dictionary<String, AnyObject>? /*Any?*/ = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, AnyObject> //-> SwiftyJson if json != nil { log.debug(json.debugDescription) // let count = json!["resultCount"] as! Int let result = json!["results"] as AnyObject done(result, true) } else { log.error("Error: no data!") done(empty, false) } // do something in your app case let .failure(error): log.error("Error: \(error.localizedDescription)") done(empty, false) } } } //MARK: Reachability func workReachability() { reachability.whenReachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { if reachability.isReachableViaWiFi { log.info("Reachable via WiFi") } else { log.info("Reachable via Cellular") } } } reachability.whenUnreachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { log.info("Not reachable") } } do { try reachability.startNotifier() } catch { print("Unable to start notifier") } } } class BBNetworkReachability: NSObject { // 싱글턴. static let shared = BBNetworkReachability() var reachability: Reachability? override private init() { super.init() // Start reachability without a hostname intially //52.79.81.3:3000 setupReachability(SLV_URL, useClosures: true) startNotifier() // After 5 seconds, stop and re-start reachability, this time using a hostname let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5) DispatchQueue.main.asyncAfter(deadline: dispatchTime) { self.stopNotifier() self.setupReachability("google.com", useClosures: true) self.startNotifier() let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5) DispatchQueue.main.asyncAfter(deadline: dispatchTime) { self.stopNotifier() self.setupReachability("invalidhost", useClosures: true) self.startNotifier() } } } func setupReachability(_ hostName: String?, useClosures: Bool) { log.info("--- set up with host name: \(hostName)") let reachability = hostName == nil ? Reachability() : Reachability(hostname: hostName!) self.reachability = reachability if useClosures { reachability?.whenReachable = { reachability in DispatchQueue.main.async { self.updateLabelColourWhenReachable(reachability) } } reachability?.whenUnreachable = { reachability in DispatchQueue.main.async { self.updateLabelColourWhenNotReachable(reachability) } } } else { Noti.addObserver(self, selector: #selector(BBNetworkReachability.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability) } } func startNotifier() { log.info("--- start notifier") do { try reachability?.startNotifier() } catch { log.error("Unable to start\nnotifier") return } } func stopNotifier() { log.info("--- stop notifier") reachability?.stopNotifier() Noti.removeObserver(self, name: ReachabilityChangedNotification, object: nil) reachability = nil } func updateLabelColourWhenReachable(_ reachability: Reachability) { print("\(reachability.description) - \(reachability.currentReachabilityString)") if reachability.isReachableViaWiFi { log.info("Reachable via WiFi") } else { log.info("Reachable via Cellular") } } func updateLabelColourWhenNotReachable(_ reachability: Reachability) { print("\(reachability.description) - \(reachability.currentReachabilityString)") log.info("NotReachable") } func reachabilityChanged(_ note: Notification) { let reachability = note.object as! Reachability if reachability.isReachable { updateLabelColourWhenReachable(reachability) } else { updateLabelColourWhenNotReachable(reachability) } } deinit { stopNotifier() } }
mit
dadbcc6f442d64e093865f287ebe1e97
33.196429
184
0.536423
5.409605
false
false
false
false
elkanaoptimove/OptimoveSDK
OptimoveSDK/Optimove/Entities/Event/RealtimeEvent.swift
1
2114
// // RealtimeEvent.swift // OptimoveSDK // // Created by Elkana Orbach on 13/05/2018. // Copyright © 2018 Optimove. All rights reserved. // import Foundation class RealtimeEvent: Encodable { var tid:String var cid:String? var visitorid:String? var eid:String var context:[String:Any] enum CodingKeys:String,CodingKey { case tid case cid case visitorid case eid case context } struct ContextKey:CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { return nil } } init( tid:String, cid:String?,visitorid:String?, eid:String, context:[String:Any]) { self.tid = tid self.visitorid = (cid != nil) ? nil : visitorid self.cid = cid ?? nil self.eid = eid self.context = context } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(tid, forKey: .tid) try container.encodeIfPresent(cid, forKey: .cid) try container.encodeIfPresent(eid, forKey: .eid) try container.encodeIfPresent(visitorid, forKey: .visitorid) var contextContainer = container.nestedContainer(keyedBy: ContextKey.self, forKey: .context) for (key,value) in context { let key = ContextKey(stringValue: key)! switch value { case let v as String: try contextContainer.encode(v, forKey: key) case let v as Int: try contextContainer.encode(v, forKey: key) case let v as Double: try contextContainer.encode(v, forKey: key) case let v as Float: try contextContainer.encode(v, forKey: key) case let v as Bool: try contextContainer.encode(v, forKey: key) default: print("Type \(type(of: value)) not supported") } } } }
mit
a365022e49700432708e278749ad513c
27.945205
100
0.584004
4.242972
false
false
false
false
igerry/ProjectEulerInSwift
ProjectEulerInSwift/Euler/Problem15.swift
1
723
import Foundation /* Lattice paths Problem 15 137846528820 Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? */ class Problem15 { func solution() -> Int { let n:Int = 20 + 1 var values = [Int:Int]() for i in 0...n { for j in 0...n { if i == 0 || j == 0 { values[i*n + j] = 1 } else { values[i*n + j] = values[i*n + j-1]! + values[(i-1)*n + j]! } } } return values[n*n - 1]! } }
apache-2.0
ca7e72a83da36615cefc75cb9f34b857
20.848485
153
0.474341
3.697436
false
false
false
false
Jnosh/SwiftBinaryHeapExperiments
Tests/ClosureHeapTests.swift
1
3355
// // ClosureHeapTests.swift // BinaryHeap // // Created by Janosch Hildebrand on 05/12/15. // Copyright © 2015 Janosch Hildebrand. All rights reserved. // import XCTest import Framework // FIXME: Ideally we would just reuse the standard shared tests // But we currently can't do that as we can't conform the closure heaps to BinaryHeapType // For now we duplicate the tests. Alternatively could initialize the arrays outside the tests // but that would require a lot of boilerplate initialization code + passing the heaps as // inout args to have them uniquely referenced. // MARK: Tests func runInitTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type) -> Heap { let heap = heapType.init() assertEmpty(heap) return heap } func runInsertTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, element: Heap.Element) { var heap = runInitTest(heapType) heap.insert(element) XCTAssert(heap.count == 1, "Element inserted") XCTAssert(heap.first == element, "Element inserted") assertInvariants(&heap) } func runRemoveTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, element: Heap.Element) { var heap = runInitTest(heapType) heap.insert(element) let root = heap.removeFirst() XCTAssert(element == root, "Element removed") assertEmpty(heap) assertInvariants(&heap) } func runRemoveAllTest<Heap: ClosureBinaryHeapType where Heap.Element : Comparable>(heapType: Heap.Type, elements: [Heap.Element]) { var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Remove heap.removeAll(keepCapacity: false) assertEmpty(heap) assertInvariants(&heap) } func runOrderTest<Heap: ClosureBinaryHeapType, Element : Comparable where Element == Heap.Element>(heapType: Heap.Type, elements: [Element]) { let sortedElements = elements.sort() var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Remove var heapElements = [Element]() while !heap.isEmpty { heapElements.append(heap.removeFirst()) } assertEmpty(heap) assertInvariants(&heap) XCTAssert(sortedElements == heapElements, "Correct order") } func runCoWTest<Heap: ClosureBinaryHeapType, Element : Comparable where Element == Heap.Element>(heapType: Heap.Type, elements: [Element]) { var heap = runInitTest(heapType) insertElements(&heap, elements: elements) assertInvariants(&heap) // Copy var copy = heap // Remove var heapElements = [Element]() while !heap.isEmpty { heapElements.append(heap.removeFirst()) } // TODO: Should also test that other mutating funcs work with CoW (insert, removeAll, popFirst, ...) assertEmpty(heap) assertInvariants(&heap) XCTAssert(heapElements.count == elements.count, "Correct count") XCTAssert(copy.count == elements.count, "Elements not removed") XCTAssert(copy.first != nil, "Elements not removed") assertInvariants(&copy) var copyElements = [Element]() while !copy.isEmpty { copyElements.append(copy.removeFirst()) } assertEmpty(copy) assertInvariants(&copy) XCTAssert(heapElements == copyElements, "Same contents") }
mit
a49df69df371e5a97eb77e724a77ea3a
29.770642
142
0.714371
4.085262
false
true
false
false
Mioke/SwiftArchitectureWithPOP
SwiftyArchitecture/Base/Assistance/Extensions/UIView+Extensions.swift
1
1189
// // UIView+Extensions.swift // swiftArchitecture // // Created by jiangkelan on 5/12/16. // Copyright © 2016 KleinMioke. All rights reserved. // import Foundation import UIKit extension UIView { public var x: CGFloat { set { var frame = self.frame frame.origin.x = newValue self.frame = frame } get { return frame.origin.x } } public var y: CGFloat { set { var frame = self.frame frame.origin.y = newValue self.frame = frame } get { return frame.origin.y } } public var height: CGFloat { get { return frame.size.height } set { var f = frame f.size.height = newValue frame = f } } public var width: CGFloat { get { return frame.size.width } set { var f = frame f.size.width = newValue frame = f } } } public func CGRectGetCenter(_ rect: CGRect) -> CGPoint { return CGPoint(x: rect.midX, y: rect.midY) }
mit
256922eef004bc1c0649f9b3def28bab
18.16129
56
0.476431
4.335766
false
false
false
false
Mazy-ma/DemoBySwift
PullToRefresh/PullToRefresh/PullToRefresh/RefreshConstant.swift
1
685
// // RefreshConstant.swift // PullToRefresh // // Created by Mazy on 2017/12/5. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit /// 主要存储一些常量值 let RefreshViewHeight: CGFloat = 40 let RefreshSlowAnimationDuration: TimeInterval = 0.3 let RefreshHeaderTimeKey: String = "RefreshHeaderView" let RefreshContentOffset: String = "contentOffset" let RefreshContentSize: String = "contentSize" let RefreshLabelTextColor: UIColor = UIColor.lightGray let RefreshLabelTextFont: UIFont = UIFont.systemFont(ofSize: 10) // 屏幕宽高 let SCREEN_WIDTH : CGFloat = UIScreen.main.bounds.width let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.height
apache-2.0
495260311e268481a0c1927361f1d966
26.333333
64
0.768293
3.836257
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Differentiator/Sources/Differentiator/ItemPath.swift
6
771
// // ItemPath.swift // RxDataSources // // Created by Krunoslav Zaher on 1/9/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation public struct ItemPath { public let sectionIndex: Int public let itemIndex: Int public init(sectionIndex: Int, itemIndex: Int) { self.sectionIndex = sectionIndex self.itemIndex = itemIndex } } extension ItemPath : Equatable { } public func == (lhs: ItemPath, rhs: ItemPath) -> Bool { return lhs.sectionIndex == rhs.sectionIndex && lhs.itemIndex == rhs.itemIndex } extension ItemPath: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(sectionIndex.byteSwapped.hashValue) hasher.combine(itemIndex.hashValue) } }
mit
45d8cf1653785cc3067756cbb8a1018c
20.388889
81
0.681818
4.184783
false
false
false
false
davecom/SwiftGraph
SwiftGraphSampleApp/AppDelegate.swift
2
7068
// // AppDelegate.swift // SwiftGraph // // Copyright (c) 2014-2019 David Kopec // // 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. // NOTE: This sample app may run a bit slowly when compiled for DEBUG/without compiler optimizations turned on. // For a better sense of how to use SwiftGraph see the unit tests. import AppKit import QuartzCore import Cocoa import SwiftGraph class NineTailView: NSView { var position: NineTailPosition = NineTailPosition(matrix: [[.Heads, .Heads, .Heads],[.Heads, .Heads, .Heads], [.Heads, .Heads, .Heads]]) { didSet { for i in 0..<position.positionMatrix.count { for j in 0..<position.positionMatrix[0].count { CATransaction.begin() CATransaction.setValue(NSNumber(value: 2.5), forKey: kCATransactionAnimationDuration) pennyLayers[i][j].contents = NSImage(named: position.positionMatrix[i][j].rawValue)! CATransaction.commit() } } } } var pennyLayers:[[CALayer]] = [[CALayer]]() override func awakeFromNib() { wantsLayer = true let width: CGFloat = self.bounds.size.width let height: CGFloat = self.bounds.size.height for i in 0..<position.positionMatrix.count { pennyLayers.append([CALayer]()) for _ in 0..<position.positionMatrix[0].count { pennyLayers[i].append(CALayer()) } } for i in 0..<position.positionMatrix.count { for j in 0..<position.positionMatrix[0].count { pennyLayers[i][j].contents = NSImage(named: "heads") pennyLayers[i][j].frame = CGRect(x: CGFloat(CGFloat(i) * (width/3)), y: CGFloat(CGFloat(j) * (height/3)), width: (width/3), height: (height/3)) layer?.addSublayer(pennyLayers[i][j]) } } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let width: CGFloat = self.bounds.size.width let height: CGFloat = self.bounds.size.height let bPath:NSBezierPath = NSBezierPath() bPath.move(to: NSMakePoint(width/3, 0)) bPath.line(to: NSMakePoint(width/3, height)) bPath.move(to: NSMakePoint(width/3 * 2, 0)) bPath.line(to: NSMakePoint(width/3 * 2, height)) bPath.move(to: NSMakePoint(0, height/3)) bPath.line(to: NSMakePoint(width, height/3)) bPath.move(to: NSMakePoint(0, height/3 * 2)) bPath.line(to: NSMakePoint(width, height/3 * 2)) bPath.stroke() } override func mouseDown(with theEvent: NSEvent) { let width: CGFloat = self.bounds.size.width let height: CGFloat = self.bounds.size.height let mousePlace:NSPoint = self.convert(theEvent.locationInWindow, from: nil) let row: Int = Int(mousePlace.x / (width / 3)) let col: Int = Int(mousePlace.y / (height / 3)) position = position.flip(row, column: col) } } enum Coin: String, Codable { case Heads = "heads" case Tails = "tails" mutating func flip() { if self == .Heads { self = .Tails } else { self = .Heads } } } struct NineTailPosition: Equatable, Codable { fileprivate var positionMatrix: [[Coin]] init(matrix: [[Coin]]) { positionMatrix = matrix } mutating func flipHelper(_ row: Int, column: Int) { //ignore off board requests if (row >= 0 && row < positionMatrix.count && column >= 0 && column < positionMatrix[0].count) { positionMatrix[row][column].flip() } } func flip(_ row: Int, column: Int) -> NineTailPosition { var newPosition = NineTailPosition(matrix: positionMatrix) newPosition.flipHelper(row, column: column) newPosition.flipHelper(row - 1, column: column) newPosition.flipHelper(row + 1, column: column) newPosition.flipHelper(row, column: column + 1) newPosition.flipHelper(row, column: column - 1) return newPosition } } func ==(lhs: NineTailPosition, rhs: NineTailPosition) -> Bool { for i in 0..<3 { for j in 0..<3 { if lhs.positionMatrix[i][j] != rhs.positionMatrix[i][j] { return false } } } return true } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var ntView: NineTailView! let ntGraph: UnweightedGraph<NineTailPosition> = UnweightedGraph<NineTailPosition>() var path: [NineTailPosition] = [NineTailPosition]() var timer:Timer? func addPositionAndChildren(_ position: NineTailPosition, parent: Int) { let index: Int? = ntGraph.indexOfVertex(position) if let place = index { ntGraph.addEdge(fromIndex: parent, toIndex: place, directed: true) } else { let child: Int = ntGraph.addVertex(position) if (parent != -1) { ntGraph.addEdge(fromIndex: parent, toIndex: child, directed: true) } for i in 0..<3 { for j in 0..<3 { let flipped = position.flip(i, column: j) addPositionAndChildren(flipped, parent: child) } } } } func applicationDidFinishLaunching(_ aNotification: Notification) { window.makeKeyAndOrderFront(self) ntView.needsDisplay = true //redraw it if it wasn't automatically //add all the vertices addPositionAndChildren(NineTailPosition(matrix: [[.Heads, .Heads, .Heads],[.Heads, .Heads, .Heads], [.Heads, .Heads, .Heads]]), parent: -1) } @objc func timerFire(_ timer: Timer) { if !path.isEmpty { ntView.position = path.removeFirst() } else { timer.invalidate() } } @IBAction func solve(_ sender: AnyObject) { let temp = ntGraph.bfs(from: ntView.position, to: NineTailPosition(matrix: [[.Tails, .Tails, .Tails],[.Tails, .Tails, .Tails], [.Tails, .Tails, .Tails]])) path = ntGraph.edgesToVertices(edges: temp) timer = Timer.scheduledTimer(timeInterval: 2.5, target: self, selector: #selector(AppDelegate.timerFire(_:)), userInfo: nil, repeats: true) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
apache-2.0
64f4fc673e99fb6b610faa07e1c2d8c0
36.005236
162
0.60399
4.062069
false
false
false
false
tndatacommons/OfficeHours-iOS
OfficeHours/AddCourseController.swift
1
4584
// // AddCourseController.swift // OfficeHours // // Created by Ismael Alonso on 12/8/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit class AddCourseController: UIViewController{ @IBOutlet weak var code1: UITextField! @IBOutlet weak var code2: UITextField! @IBOutlet weak var code3: UITextField! @IBOutlet weak var code4: UITextField! @IBOutlet weak var activity: UIActivityIndicatorView! @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var courseContainer: UIView! @IBOutlet weak var courseName: UILabel! @IBOutlet weak var courseMeetingTime: UILabel! @IBOutlet weak var courseLastMeetingDate: UILabel! @IBOutlet weak var courseInstructor: UILabel! var delegate: AddCourseDelegate! var course: CourseModel! override func viewDidLoad(){ super.viewDidLoad() code1.addTarget(self, action: #selector(AddCourseController.codeValueChanged(_:)), for: UIControlEvents.editingChanged) code2.addTarget(self, action: #selector(AddCourseController.codeValueChanged(_:)), for: UIControlEvents.editingChanged) code3.addTarget(self, action: #selector(AddCourseController.codeValueChanged(_:)), for: UIControlEvents.editingChanged) code4.addTarget(self, action: #selector(AddCourseController.codeValueChanged(_:)), for: UIControlEvents.editingChanged) code1.becomeFirstResponder() } func codeValueChanged(_ sender: UITextField){ if sender == code1{ if code1.text?.characters.count == 1{ code2.becomeFirstResponder() } } else if sender == code2{ if code2.text?.characters.count == 1{ code3.becomeFirstResponder() } } else if sender == code3{ if code3.text?.characters.count == 1{ code4.becomeFirstResponder() } } else if sender == code4{ if code4.text?.characters.count == 1{ code4.resignFirstResponder() code1.isEnabled = false code2.isEnabled = false code3.isEnabled = false code4.isEnabled = false activity.isHidden = false errorLabel.isHidden = true let code = "\(code1.text!)\(code2.text!)\(code3.text!)\(code4.text!)" print(code) DispatchQueue.main.asyncAfter(deadline: .now() + 2){ if code == "1234"{ self.errorLabel.isHidden = true self.activity.isHidden = true self.courseContainer.isHidden = false let course = CourseModel(code: "COMP 1900", name: "Intro to CS", meetingTime: "MW 7", lastMeetingDate: "12/14", instructorName: "Someboody") self.setCourse(course: course) } else{ self.errorLabel.isHidden = false self.activity.isHidden = true self.code1.text = "" self.code2.text = "" self.code3.text = "" self.code4.text = "" self.code1.isEnabled = true self.code2.isEnabled = true self.code3.isEnabled = true self.code4.isEnabled = true self.code1.becomeFirstResponder() } } } } } func setCourse(course: CourseModel){ self.course = course; courseName.text = course.getDisplayName() courseMeetingTime.text = course.getMeetingTime() courseLastMeetingDate.text = course.getLastMeetingDate() courseInstructor.text = course.getInstructorName() } @IBAction func addCourse(){ self.delegate.onCourseAdded(course: course) _ = self.navigationController?.popViewController(animated: true) } } extension AddCourseController: UITextFieldDelegate{ func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{ return (textField.text?.characters.count)! < 1 && string.characters.count < 2 } } protocol AddCourseDelegate{ func onCourseAdded(course: CourseModel) }
apache-2.0
43fc7ceb7f4a17310b9e42f3ab8b75a7
35.959677
164
0.569932
5.097887
false
false
false
false
ianyh/Highball
Highball/ImagesViewController.swift
1
2278
// // ImagesViewController.swift // Highball // // Created by Ian Ynda-Hummel on 9/1/14. // Copyright (c) 2014 ianynda. All rights reserved. // import UIKit class ImagesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var imagesCollectionView: UICollectionView! var post: Post? override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 imagesCollectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) imagesCollectionView.dataSource = self imagesCollectionView.delegate = self imagesCollectionView.pagingEnabled = true imagesCollectionView.showsHorizontalScrollIndicator = false imagesCollectionView.showsVerticalScrollIndicator = false imagesCollectionView.registerClass(ImageCollectionViewCell.self, forCellWithReuseIdentifier: ImageCollectionViewCell.cellIdentifier) view.addSubview(imagesCollectionView) } override func viewDidAppear(animated: Bool) { imagesCollectionView.reloadData() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return post?.photos.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ImageCollectionViewCell.cellIdentifier, forIndexPath: indexPath) guard let imageCell = cell as? ImageCollectionViewCell else { return cell } let postPhoto = post!.photos[indexPath.row] imageCell.contentWidth = collectionView.frame.size.width imageCell.photo = postPhoto imageCell.onTapHandler = { self.dismissViewControllerAnimated(true, completion: nil) } return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { dismissViewControllerAnimated(true, completion: nil) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return collectionView.frame.size } }
mit
d0f06dfe296978de5d0bf51166bbbc0d
34.59375
166
0.813872
5.165533
false
false
false
false
cacawai/Tap2Read
tap2read/tap2read/CategoryModel.swift
1
1028
// // CategoryModel.swift // tap2read // // Created by 徐新元 on 16/8/28. // Copyright © 2016年 Last4 Team. All rights reserved. // import UIKit import HandyJSON class CategoryModel: HandyJSON { var categoryId:NSInteger? var cardId:NSInteger? var titleJson:[String:String]? var categoryFolder:String? required init() {} func getImageFileUrl() -> URL? { let categoryFolderUrl = URL(fileURLWithPath: self.categoryFolder!) let imageFileUrl = categoryFolderUrl.appendingPathComponent("image.jpg") return imageFileUrl } func getCategoryJsonFileUrl() -> URL? { let categoryFolderUrl = URL(fileURLWithPath: self.categoryFolder!) let categoryJsonFileUrl = categoryFolderUrl.appendingPathComponent("category.json") return categoryJsonFileUrl } func titleWithLanguage(language:String!) -> String? { if titleJson?[language] == nil { return titleJson?["en"] } return titleJson?[language] } }
mit
0bd28cefce60086620093ccc09aa6e0e
25.128205
91
0.668302
4.411255
false
false
false
false
dreamsxin/swift
test/Constraints/patterns.swift
3
4846
// RUN: %target-parse-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is IntegerLiteralConvertible case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () } // Raise an error if pattern productions are used in expressions. var b = var a // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // TODO: should warn that cast can't succeed with currently known conformances () case .HairForceOne: // expected-error{{enum case 'HairForceOne' not found in type 'HairType'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break case nil: break } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x, terminator: "") case let x?: print(x, terminator: "") case 4???: break case nil??: break case nil?: break default: break } // <rdar://problem/21995744> QoI: Binary operator '~=' cannot be applied to operands of type 'String' and 'String?' switch ("foo" as String?) { case "what": break // expected-error{{expression pattern of type 'String' cannot match values of type 'String?'}} default: break } // Test some value patterns. let x : Int? = nil extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} for var x in 0...100 {} // rdar://20167543 for (let x) in 0...100 {} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} switch $0 { case .A: return 1 default: return 2 } } }
apache-2.0
103ce1b5f0c1d0cda5be16002b3d234e
20.633929
208
0.624845
3.321453
false
false
false
false
tnantoka/generative-swift
GenerativeSwift/Controllers/HelloFormViewController.swift
1
2113
// // HelloFormViewController.swift // GenerativeSwift // // Created by Tatsuya Tobioka on 4/16/16. // Copyright © 2016 tnantoka. All rights reserved. // import UIKit import C4 class HelloFormViewController: BaseCanvasController { var form = [Shape]() var point = Point(0, 0) override init() { super.init() title = "Hello Form" trash = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateCircle() } override func setup() { let _ = canvas.addPanGestureRecognizer { locations, center, translation, velocity, state in self.point = center self.updateCircle() } let _ = canvas.addTapGestureRecognizer { locations, center, state in self.point = center self.updateCircle() } point = Point(canvas.center.x, canvas.center.y * 0.4) } func updateCircle() { let circleResolution = Int(map(point.y, min: 64, max: canvas.height, toMin: 2, toMax: 80)) let radius = point.x / 2 + 0.5 let angle = M_PI * 2 / Double(circleResolution) createForm(circleResolution, radius: radius, angle: angle) } func createForm(_ circleResolution: Int, radius: Double, angle: Double) { for shape in form { shape.removeFromSuperview() } form = [Shape]() (0...circleResolution).forEach { i in let points = [canvas.center, circlePoint(i, angle: angle, radius: radius)] let line = Line(points) line.lineWidth = point.y / 20 line.lineCap = .Square canvas.add(line) form.append(line) } } func circlePoint(_ i: Int, angle: Double, radius: Double) -> Point { let x = canvas.center.x + cos(angle * Double(i)) * radius let y = canvas.center.y + sin(angle * Double(i)) * radius return Point(x, y) } }
apache-2.0
751402d01b23f5d27cc779f3d089bf87
28.746479
99
0.579072
4.15748
false
false
false
false
liyanhuadev/ObjectMapper-Plugin
ObjectMapper-Plugin/RegexSwift/Options.swift
2
2833
#if swift(>=3.0) private typealias _OptionSet = OptionSet #else private typealias _OptionSet = OptionSetType #endif /// `Options` defines alternate behaviours of regular expressions when matching. public struct Options: _OptionSet { /// Ignores the case of letters when matching. /// /// Example: /// /// let a = Regex("a", options: .IgnoreCase) /// a.allMatches("aA").map { $0.matchedString } // ["a", "A"] public static let IgnoreCase = Options(rawValue: 1) /// Ignore any metacharacters in the pattern, treating every character as /// a literal. /// /// Example: /// /// let parens = Regex("()", options: .IgnoreMetacharacters) /// parens.matches("()") // true public static let IgnoreMetacharacters = Options(rawValue: 1 << 1) /// By default, "^" matches the beginning of the string and "$" matches the /// end of the string, ignoring any newlines. With this option, "^" will /// the beginning of each line, and "$" will match the end of each line. /// /// let foo = Regex("^foo", options: .AnchorsMatchLines) /// foo.allMatches("foo\nbar\nfoo\n").count // 2 public static let AnchorsMatchLines = Options(rawValue: 1 << 2) /// Usually, "." matches all characters except newlines (\n). Using this /// this options will allow "." to match newLines /// /// let newLines = Regex("test.test", options: .DotMatchesLineSeparators) /// newLines.allMatches("test\ntest").count // 1 public static let DotMatchesLineSeparators = Options(rawValue: 1 << 3) // MARK: OptionSetType public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } #if swift(>=3.0) typealias _RegularExpressionOptions = NSRegularExpression.Options #else typealias _RegularExpressionOptions = NSRegularExpressionOptions #endif internal extension Options { /// Transform an instance of `Regex.Options` into the equivalent `NSRegularExpressionOptions`. /// /// - returns: The equivalent `NSRegularExpressionOptions`. func toNSRegularExpressionOptions() -> _RegularExpressionOptions { var options = _RegularExpressionOptions() #if swift(>=3.0) if contains(.IgnoreCase) { options.insert(.caseInsensitive) } if contains(.IgnoreMetacharacters) { options.insert(.ignoreMetacharacters) } if contains(.AnchorsMatchLines) { options.insert(.anchorsMatchLines) } if contains(.DotMatchesLineSeparators) { options.insert(.dotMatchesLineSeparators) } #else if contains(.IgnoreCase) { options.insert(.CaseInsensitive) } if contains(.IgnoreMetacharacters) { options.insert(.IgnoreMetacharacters) } if contains(.AnchorsMatchLines) { options.insert(.AnchorsMatchLines) } if contains(.DotMatchesLineSeparators) { options.insert(.DotMatchesLineSeparators) } #endif return options } } import Foundation
mit
73b3e380c8495d8469c0957e6e72aa0c
33.975309
96
0.700671
4.454403
false
false
false
false
starhoshi/SyncPlanet
SyncPlanet/Sync2HealthKitViewController.swift
1
4158
// // Sync2HealthKitViewController.swift // SyncPlanet // // Created by Kensuke Hoshikawa on 2015/07/05. // Copyright (c) 2015年 star__hoshi. All rights reserved. // import UIKit class Sync2HealthKitViewController: UIViewController { @IBOutlet weak var innerscan: UILabel! @IBOutlet weak var sphygmomanometer: UILabel! @IBOutlet weak var pedometer: UILabel! @IBOutlet weak var syncplanet: UIImageView! @IBOutlet weak var update: UILabel! @IBOutlet weak var progressBar: UIProgressView! var flg = false override func viewDidLoad() { super.viewDidLoad() if let date: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("updated_at") { update.text = "Last Update: " + DateFormatter().format(date as! NSDate,style: "yyyy/MM/dd HH:mm:ss") }else { update.text = "No Sync Info." } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func clickSync(sender: UIButton) { self.update.text = "情報取得中…" self.innerscan.text = "体組成測定情報: -" self.sphygmomanometer.text = "血圧測定情報: -" self.pedometer.text = "歩数測定情報: -" self.progressBar.hidden = false self.progressBar.progress = 0.0 SyncHealth().requestAuthorization() { (status) in if status { self.startInnerscan() } else { self.fetchError("ヘルスケア連携が許可されていません") } } } func startInnerscan(){ SyncHealth().fetchInnerscan(){ (error) in if error == nil { self.completeFetch(TANITA_STATUS.INNER_SCAN) } else { self.fetchError("エラーが発生しました。もう一度Syncして下さい") } } } func startSphygmomanometer(){ SyncHealth().fetchSphygmomanometer(){ (error) in if error == nil { self.completeFetch(TANITA_STATUS.SPHYGMOMANOMETER) } else { self.fetchError("エラーが発生しました。もう一度Syncして下さい") } } } func startPedometer(){ SyncHealth().fetchPedometer(){ (error) in if error == nil { self.completeFetch(TANITA_STATUS.PEDOMETER) } else { self.fetchError("エラーが発生しました。もう一度Syncして下さい") } } } func fetchError(text:String){ print("false") progressBar.hidden = true update.text = text } func completeFetch(status: TANITA_STATUS){ print("complete Fetch") switch status{ case .INNER_SCAN: self.innerscan.text = "体組成測定情報: ✔" self.progressBar.progress = 1/3 startSphygmomanometer() case .SPHYGMOMANOMETER: self.sphygmomanometer.text = "血圧測定情報: ✔" self.progressBar.progress = 2/3 startPedometer() case .PEDOMETER: self.pedometer.text = "歩数測定情報: ✔" self.progressBar.progress = 3/3 NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"updated_at") if let date: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("updated_at") { self.update.text = "Last Update: " + DateFormatter().format(date as! NSDate,style: "yyyy/MM/dd HH:mm:ss") } self.progressBar.hidden = true } } @IBAction func clickSupport(sender: AnyObject) { let url = NSURL(string: "https://dl.dropboxusercontent.com/u/43623483/syncplanet/privacypolicy.html") if UIApplication.sharedApplication().canOpenURL(url!){ UIApplication.sharedApplication().openURL(url!) } } } enum TANITA_STATUS { case INNER_SCAN case SPHYGMOMANOMETER case PEDOMETER }
mit
1d1fb3351d74e195900647eee0230313
30.780488
121
0.585466
3.963489
false
false
false
false
apple/swift-tools-support-core
Tests/TSCBasicTests/miscTests.swift
1
2997
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCTestSupport import TSCBasic class miscTests: XCTestCase { func testExecutableLookup() throws { try testWithTemporaryDirectory { path in let pathEnv1 = path.appending(component: "pathEnv1") try localFileSystem.createDirectory(pathEnv1) let pathEnvClang = pathEnv1.appending(component: "clang") try localFileSystem.writeFileContents(pathEnvClang, bytes: "") let pathEnv = [path.appending(component: "pathEnv2"), pathEnv1] try! Process.checkNonZeroExit(args: "chmod", "+x", pathEnvClang.pathString) // nil and empty string should fail. XCTAssertNil(lookupExecutablePath(filename: nil, currentWorkingDirectory: path, searchPaths: pathEnv)) XCTAssertNil(lookupExecutablePath(filename: "", currentWorkingDirectory: path, searchPaths: pathEnv)) // Absolute path to a binary should return it. var exec = lookupExecutablePath(filename: pathEnvClang.pathString, currentWorkingDirectory: path, searchPaths: pathEnv) XCTAssertEqual(exec, pathEnvClang) // This should lookup from PATH variable since executable is not present in cwd. exec = lookupExecutablePath(filename: "clang", currentWorkingDirectory: path, searchPaths: pathEnv) XCTAssertEqual(exec, pathEnvClang) // Create the binary relative to cwd and make it executable. let clang = path.appending(component: "clang") try localFileSystem.writeFileContents(clang, bytes: "") try! Process.checkNonZeroExit(args: "chmod", "+x", clang.pathString) // We should now find clang which is in cwd. exec = lookupExecutablePath(filename: "clang", currentWorkingDirectory: path, searchPaths: pathEnv) XCTAssertEqual(exec, clang) } } func testEnvSearchPaths() throws { let cwd = AbsolutePath(path: "/dummy") let paths = getEnvSearchPaths(pathString: "something:.:abc/../.build/debug:/usr/bin:/bin/", currentWorkingDirectory: cwd) XCTAssertEqual(paths, try ["/dummy/something", "/dummy", "/dummy/.build/debug", "/usr/bin", "/bin"].map({ try AbsolutePath(validating: $0)})) } func testEmptyEnvSearchPaths() throws { let cwd = AbsolutePath(path: "/dummy") let paths = getEnvSearchPaths(pathString: "", currentWorkingDirectory: cwd) XCTAssertEqual(paths, []) let nilPaths = getEnvSearchPaths(pathString: nil, currentWorkingDirectory: cwd) XCTAssertEqual(nilPaths, []) } }
apache-2.0
965fd364585da4ee5069ac33989a035b
45.828125
149
0.668669
4.945545
false
true
false
false
hejunbinlan/GRDB.swift
GRDB/Record/DatabaseStorable.swift
2
9314
// MARK: - DatabaseStorable protocol DatabaseStorable : DatabaseTableMapping { var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { get } } // MARK: - DataMapper /// DataMapper takes care of DatabaseStorable CRUD final class DataMapper { /// The database let db: Database /// The storable let storable: DatabaseStorable /// DataMapper keeps a copy the storable's storedDatabaseDictionary, so /// that this dictionary is built once whatever the database operation. /// It is guaranteed to have at least one (key, value) pair. let storedDatabaseDictionary: [String: DatabaseValueConvertible?] /// The table name let databaseTableName: String /// The table primary key let primaryKey: PrimaryKey /** An excerpt from storedDatabaseDictionary whose keys are primary key columns. It is nil when storable has no primary key. */ lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in let columns = self.primaryKey.columns guard columns.count > 0 else { return nil } let storedDatabaseDictionary = self.storedDatabaseDictionary var dictionary: [String: DatabaseValueConvertible?] = [:] for column in columns { dictionary[column] = storedDatabaseDictionary[column] } return dictionary }() /** An excerpt from storedDatabaseDictionary whose keys are primary key columns. It is able to resolve a row in the database. It is nil when the primaryKeyDictionary is nil or unable to identify a row in the database. */ lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in // IMPLEMENTATION NOTE // // https://www.sqlite.org/lang_createtable.html // // > According to the SQL standard, PRIMARY KEY should always // > imply NOT NULL. Unfortunately, due to a bug in some early // > versions, this is not the case in SQLite. Unless the column // > is an INTEGER PRIMARY KEY or the table is a WITHOUT ROWID // > table or the column is declared NOT NULL, SQLite allows // > NULL values in a PRIMARY KEY column. SQLite could be fixed // > to conform to the standard, but doing so might break legacy // > applications. Hence, it has been decided to merely document // > the fact that SQLite allowing NULLs in most PRIMARY KEY // > columns. // // What we implement: we consider that the primary key is missing if // and only if *all* columns of the primary key are NULL. // // For tables with a single column primary key, we comply to the // SQL standard. // // For tables with multi-column primary keys, we let the user // store NULL in all but one columns of the primary key. guard let dictionary = self.primaryKeyDictionary else { return nil } for case let value? in dictionary.values { return dictionary } return nil }() // MARK: - Initializer init(_ db: Database, _ storable: DatabaseStorable) { // Fail early if databaseTable is nil guard let databaseTableName = storable.dynamicType.databaseTableName() else { fatalError("Nil returned from \(storable.dynamicType).databaseTableName()") } // Fail early if database table does not exist. guard let primaryKey = db.primaryKeyForTable(named: databaseTableName) else { fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(storable.dynamicType).databaseTableName()") } // Fail early if storedDatabaseDictionary is empty let storedDatabaseDictionary = storable.storedDatabaseDictionary guard storedDatabaseDictionary.count > 0 else { fatalError("Invalid empty dictionary returned from \(storable.dynamicType).storedDatabaseDictionary") } self.db = db self.storable = storable self.storedDatabaseDictionary = storedDatabaseDictionary self.databaseTableName = databaseTableName self.primaryKey = primaryKey } // MARK: - Statement builders func insertStatement() -> UpdateStatement { let insertStatement = db.updateStatement(DataMapper.insertSQL(tableName: databaseTableName, insertedColumns: Array(storedDatabaseDictionary.keys))) insertStatement.arguments = StatementArguments(storedDatabaseDictionary.values) return insertStatement } /// Returns nil if there is no column to update func updateStatement() -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { fatalError("Invalid primary key in \(storable)") } // Don't update primary key columns var updatedDictionary = storedDatabaseDictionary for column in primaryKeyDictionary.keys { updatedDictionary.removeValueForKey(column) } // We need something to update. guard updatedDictionary.count > 0 else { return nil } // Update let updateStatement = db.updateStatement(DataMapper.updateSQL(tableName: databaseTableName, updatedColumns: Array(updatedDictionary.keys), conditionColumns: Array(primaryKeyDictionary.keys))) updateStatement.arguments = StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values)) return updateStatement } func deleteStatement() -> UpdateStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { fatalError("Invalid primary key in \(storable)") } // Delete let deleteStatement = db.updateStatement(DataMapper.deleteSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) deleteStatement.arguments = StatementArguments(primaryKeyDictionary.values) return deleteStatement } func reloadStatement() -> SelectStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { fatalError("Invalid primary key in \(storable)") } // Fetch let reloadStatement = db.selectStatement(DataMapper.reloadSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) reloadStatement.arguments = StatementArguments(primaryKeyDictionary.values) return reloadStatement } /// SELECT statement that returns a row if and only if the primary key /// matches a row in the database. func existsStatement() -> SelectStatement { // Fail early if primary key does not resolve to a database row. guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else { fatalError("Invalid primary key in \(storable)") } // Fetch let existsStatement = db.selectStatement(DataMapper.existsSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys))) existsStatement.arguments = StatementArguments(primaryKeyDictionary.values) return existsStatement } // MARK: - SQL query builders private class func insertSQL(tableName tableName: String, insertedColumns: [String]) -> String { let columnSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",") let valuesSQL = Array(count: insertedColumns.count, repeatedValue: "?").joinWithSeparator(",") return "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))" } private class func updateSQL(tableName tableName: String, updatedColumns: [String], conditionColumns: [String]) -> String { let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(",") return "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL(conditionColumns))" } private class func deleteSQL(tableName tableName: String, conditionColumns: [String]) -> String { return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" } private class func existsSQL(tableName tableName: String, conditionColumns: [String]) -> String { return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" } private class func reloadSQL(tableName tableName: String, conditionColumns: [String]) -> String { return "SELECT * FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))" } private class func whereSQL(conditionColumns: [String]) -> String { return conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ") } }
mit
8e61454d58cfb991dbaad3ee5dfe1d01
41.921659
199
0.672858
5.469172
false
true
false
false