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
SanctionCo/pilot-ios
pilot/ProfilePasswordResetCell.swift
1
994
// // ProfilePasswordResetCell.swift // pilot // // Created by Nick Eckert on 12/30/17. // Copyright © 2017 sanction. All rights reserved. // import Foundation import UIKit class ProfilePasswordResetCell: UITableViewCell { var resetMessage: UILabel = { let message = UILabel() message.translatesAutoresizingMaskIntoConstraints = false message.text = "Password Reset" return message }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(resetMessage) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() setupResetMessage() } func setupResetMessage() { resetMessage.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true resetMessage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true } }
mit
23611a054f8e78bcf962b96d7cfb2d7d
23.219512
93
0.73716
4.576037
false
false
false
false
fabiomassimo/eidolon
Kiosk/App/AppDelegate.swift
1
2866
import UIKit import ARAnalytics import SDWebImage import ReactiveCocoa import Keys import Stripe @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate { dynamic weak var helpViewController: HelpViewController? var helpButton: UIButton! weak var webViewController: UIViewController? public var window: UIWindow? = UIWindow(frame:CGRectMake(0, 0, UIScreen.mainScreen().bounds.height, UIScreen.mainScreen().bounds.width)) public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Disable sleep timer UIApplication.sharedApplication().idleTimerDisabled = true // Set up network layer if StubResponses.stubResponses() { Provider.sharedProvider = Provider.StubbingProvider() } // I couldn't figure how to swizzle this out like we do in objc. if let inTests: AnyClass = NSClassFromString("XCTest") { return true } // Clear possible old contents from cache and defaults. let imageCache = SDImageCache.sharedImageCache() imageCache.clearDisk() let defaults = NSUserDefaults.standardUserDefaults() defaults.removeObjectForKey(XAppToken.DefaultsKeys.TokenKey.rawValue) defaults.removeObjectForKey(XAppToken.DefaultsKeys.TokenExpiry.rawValue) let auctionStoryboard = UIStoryboard.auction() window?.rootViewController = auctionStoryboard.instantiateInitialViewController() as? UIViewController window?.makeKeyAndVisible() let keys = EidolonKeys() Stripe.setDefaultPublishableKey(keys.stripePublishableKey()) let mixpanelToken = AppSetup.sharedState.useStaging ? keys.mixpanelStagingAPIClientKey() : keys.mixpanelProductionAPIClientKey() ARAnalytics.setupWithAnalytics([ ARHockeyAppBetaID: keys.hockeyBetaSecret(), ARHockeyAppLiveID: keys.hockeyProductionSecret(), ARMixpanelToken: mixpanelToken ]) setupHelpButton() setupUserAgent() logger.log("App Started") ARAnalytics.event("Session Started") return true } func setupUserAgent() { let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as! String? let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as! String? let webView = UIWebView(frame: CGRectZero) let oldAgent = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent") let agentString = "\(oldAgent) Artsy-Mobile/\(version!) Eigen/\(build!) Kiosk Eidolon" let defaults = NSUserDefaults.standardUserDefaults() let userAgentDict = ["UserAgent" as NSObject : agentString] defaults.registerDefaults(userAgentDict) } }
mit
cfb6f717e8333b43ca8d5d4f0e1cbd31
36.710526
140
0.7097
5.664032
false
false
false
false
stupidfive/SwiftDataStructuresAndAlgorithms
SwiftDataStructuresAndAlgorithms/RedBlackTree.swift
1
3998
// // RedBlackTree.swift // SwiftDataStructuresAndAlgorithms // // Created by George Wu on 9/28/15. // Copyright © 2015 George Wu. All rights reserved. // import Foundation enum RBTNodeColor: Int { case Red = 0 case Black = 1 } class RedBlackTree<KeyT: Comparable, ValueT>: BinarySearchTree<KeyT, ValueT> { override func insert(key: KeyT, value: ValueT) { let node = RBTNode(key: key, value: value) insertNodeReplacingDuplicate(node) insertCase1(node) } private func insertCase1(node: RBTNode<KeyT, ValueT>) { if node.parent == nil { node.color = .Black } else { insertCase2(node) } } private func insertCase2(node: RBTNode<KeyT, ValueT>) { if (node.parent! as! RBTNode<KeyT, ValueT>).color == .Black { return } else { insertCase3(node) } } private func insertCase3(node: RBTNode<KeyT, ValueT>) { let uncle = node.uncle(node) let grandParent: RBTNode<KeyT, ValueT> if uncle != nil && uncle!.color == .Red { (node.parent! as! RBTNode<KeyT, ValueT>).color = .Black uncle!.color = .Black grandParent = node.grandParent(node)! grandParent.color = .Red insertCase1(grandParent) } else { insertCase4(node) } } private func insertCase4(node: RBTNode<KeyT, ValueT>) { let grandParent = node.grandParent(node)! var case5Node = node if node === node.parent!.rightChild && node.parent === grandParent.leftChild { rotateLeft(node, parent: node.parent as! RBTNode<KeyT, ValueT>) case5Node = node.leftChild as! RBTNode<KeyT, ValueT> } else if node === node.parent!.leftChild && node.parent === grandParent.rightChild { rotateRight(node, parent: node.parent as! RBTNode<KeyT, ValueT>) case5Node = node.rightChild as! RBTNode<KeyT, ValueT> } insertCase5(case5Node) } private func insertCase5(node: RBTNode<KeyT, ValueT>) { let grandParent = node.grandParent(node) (node.parent! as! RBTNode<KeyT, ValueT>).color = .Black grandParent!.color = .Red if (node === node.parent!.leftChild) { rotateRight(node.parent! as! RBTNode<KeyT, ValueT>, parent: grandParent!) } else { rotateLeft(node.parent! as! RBTNode<KeyT, ValueT>, parent: grandParent!) } } private func rotateRight(node: RBTNode<KeyT, ValueT>, parent: RBTNode<KeyT, ValueT>) { let grandParent = parent.parent // link up with grandParent if grandParent == nil { root = node node.parent = nil } else { if parent === grandParent!.leftChild { grandParent!.leftChild = node } else { grandParent!.rightChild = node } node.parent = grandParent } parent.leftChild = node.rightChild parent.leftChild?.parent = parent node.rightChild = parent parent.parent = node } private func rotateLeft(node: RBTNode<KeyT, ValueT>, parent: RBTNode<KeyT, ValueT>) { let grandParent = parent.parent // link up with grandParent if grandParent == nil { root = node node.parent = nil } else { if parent === grandParent!.leftChild { grandParent!.leftChild = node } else { grandParent!.rightChild = node } node.parent = grandParent } parent.rightChild = node.leftChild parent.rightChild?.parent = parent node.leftChild = parent parent.parent = node } } private class RBTNode<KeyT: Comparable, ValueT>: BSTNode<KeyT, ValueT> { var color: RBTNodeColor = .Red private func grandParent(node: RBTNode<KeyT, ValueT>) -> RBTNode<KeyT, ValueT>? { if node.parent != nil { return node.parent!.parent as? RBTNode<KeyT, ValueT> } else { return nil } } private func uncle(node: RBTNode<KeyT, ValueT>) -> RBTNode<KeyT, ValueT>? { guard let grandParent = grandParent(node) else { return nil } if node.parent === grandParent.leftChild { return grandParent.rightChild as? RBTNode<KeyT, ValueT> } else { return grandParent.leftChild as? RBTNode<KeyT, ValueT> } } override init(key: KeyT, value: ValueT) { super.init(key: key, value: value) } }
mit
c518fcc379377af60aaaa144c315a232
22.374269
87
0.669002
3.081727
false
false
false
false
GitOyoung/LibraryManagement
LibraryManagement/SCenterViewController.swift
1
1913
// // SCenterViewController.swift // LibraryManagement // // Created by oyoung on 15/11/30. // Copyright © 2015年 Oyoung. All rights reserved. // import UIKit class SCenterViewController: UIViewController { var logoutButton: UIButton? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.parentViewController?.navigationItem.title = "个人中心" self.setButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setButton() { let center = UIView.CGRectGetCenter(self.view.frame) var size = self.view.frame.size size.height = 40 logoutButton = UIButton(type: UIButtonType.RoundedRect) logoutButton?.backgroundColor = UIColor.purpleColor() logoutButton?.titleLabel?.textColor = UIColor.whiteColor() logoutButton?.setTitle("退出登录", forState: UIControlState.Normal) logoutButton?.addTarget(self, action: Selector("OnLogout:"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(logoutButton!) logoutButton?.makeConstriantCenter(center) logoutButton?.makeConstraintSize(size) } @IBAction func OnLogout(sender: UIButton) { NSNotificationCenter.defaultCenter().postNotificationName("LOGOUT", object: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
2bd5e5f6ae062fbd382a3e2de61c1a9c
29.548387
117
0.665787
5.174863
false
false
false
false
duliodenis/logincontroller
Login/Login/Controllers/LoginController.swift
1
12165
// // LoginController.swift // Login // // Created by Dulio Denis on 10/12/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit protocol LoginControllerDelegate: class { func finishedLogIn() } class LoginController: UIViewController, LoginControllerDelegate { let cellId = "cellId" let loginCellId = "loginCellId" // constraint variables used for animation var pageControlBottomAnchor: NSLayoutConstraint? var skipButtonBottomAnchor: NSLayoutConstraint? var nextButtonBottomAnchor: NSLayoutConstraint? let pages: [Page] = { let firstPage = Page(title: "What's the Move in Your Hood", message: "Find out where the fun is in your neighborhood.", imageName: "Page1") let secondPage = Page(title: "Chat with Your Friends", message: "Stay in touch with your neighborhood friends so you catch all the fun.", imageName: "Page2") let thirdPage = Page(title: "Share Your Moments", message: "Share your moments with those in your neighborhood.", imageName: "Page3") return [firstPage, secondPage, thirdPage] }() lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.backgroundColor = .white cv.delegate = self cv.dataSource = self cv.isPagingEnabled = true return cv }() lazy var pageControl: UIPageControl = { let pc = UIPageControl() pc.pageIndicatorTintColor = .lightGray pc.numberOfPages = self.pages.count + 1 pc.currentPageIndicatorTintColor = UIColor.rgb(41, 128, 185) return pc }() lazy var skipButton: UIButton = { let btn = UIButton(type: .system) btn.setTitle("Skip", for: .normal) btn.setTitleColor(UIColor.rgb(41, 128, 185), for: .normal) btn.addTarget(self, action: #selector(skipPages), for: .touchUpInside) return btn }() lazy var nextButton: UIButton = { let btn = UIButton(type: .system) btn.setTitle("Next", for: .normal) btn.setTitleColor(UIColor.rgb(41, 128, 185), for: .normal) btn.addTarget(self, action: #selector(nextPage), for: .touchUpInside) return btn }() override func viewDidLoad() { super.viewDidLoad() observeKeyboardNotifications() view.addSubview(collectionView) view.addSubview(pageControl) view.addSubview(skipButton) view.addSubview(nextButton) skipButtonBottomAnchor = skipButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: nil, topConstant: 0, leftConstant: 10, bottomConstant: 16, rightConstant: 0, widthConstant: 60, heightConstant: 50)[2] nextButtonBottomAnchor = nextButton.anchor(top: nil, left: nil, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 16, rightConstant: 10, widthConstant: 60, heightConstant: 50)[2] collectionView.anchorToTop(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor) registerCells() pageControlBottomAnchor = pageControl.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 40)[1] } func skipPages() { let indexPath = IndexPath(item: pages.count, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) pageControl.currentPage = pages.count animatePage() } func nextPage() { if pageControl.currentPage == pages.count { return } let indexPath = IndexPath(item: pageControl.currentPage + 1, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) pageControl.currentPage += 1 // take care of the last page animation animatePage() } func animatePage() { if pageControl.currentPage == pages.count { moveConstraintsOffScreen() UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.view.layoutIfNeeded() }, completion: nil) } } fileprivate func moveConstraintsOffScreen() { pageControlBottomAnchor?.constant = 50 skipButtonBottomAnchor?.constant = 0 nextButtonBottomAnchor?.constant = 0 } fileprivate func moveConstraintsOnScreen() { pageControlBottomAnchor?.constant = 0 skipButtonBottomAnchor?.constant = 50 nextButtonBottomAnchor?.constant = 50 } fileprivate func observeKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name: .UIKeyboardDidHide, object: nil) } func keyboardShow() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { let y: CGFloat = UIDevice.current.orientation.isLandscape ? -110 : -70 self.view.frame = CGRect(x: 0, y: y, width: self.view.frame.width, height: self.view.frame.height) }, completion: nil) } func keyboardHide() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) }, completion: nil) } func scrollViewDidScroll(_ scrollView: UIScrollView) { view.endEditing(true) } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let pageNumber = Int(targetContentOffset.pointee.x / view.frame.width) pageControl.currentPage = pageNumber // if we are on the last page of the Onboarding if pageNumber == pages.count { moveConstraintsOffScreen() } else { moveConstraintsOnScreen() } // animate layout if needed UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.view.layoutIfNeeded() }, completion: nil) } fileprivate func registerCells() { collectionView.register(PageCell.self, forCellWithReuseIdentifier: cellId) collectionView.register(LoginCell.self, forCellWithReuseIdentifier: loginCellId) } func finishedLogIn() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController guard let mainNavigationController = rootViewController as? MainNavigationController else { return } mainNavigationController.viewControllers = [HomeController()] UserDefaults.standard.setIsLoggedIn(value: true) dismiss(animated: true, completion: nil) } } extension LoginController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pages.count + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // set-up the Login Cell if indexPath.item == pages.count { let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell loginCell.delegate = self return loginCell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PageCell cell.page = pages[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height) } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { collectionView.collectionViewLayout.invalidateLayout() let indexPath = IndexPath(item: pageControl.currentPage, section: 0) DispatchQueue.main.async { self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) self.collectionView.reloadData() } } } extension UIView { func anchorToTop(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) { anchorWithConstantsToTop(top: top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0) } func anchorWithConstantsToTop(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false if let top = top { topAnchor.constraint(equalTo: top, constant: topConstant).isActive = true } if let bottom = bottom { bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant).isActive = true } if let left = left { leftAnchor.constraint(equalTo: left, constant: leftConstant).isActive = true } if let right = right { rightAnchor.constraint(equalTo: right, constant: -rightConstant).isActive = true } } func anchor(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } } extension UIColor { static func rgb(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1) } }
mit
b62db0663e21328bb42a1d96c33f6b5e
38.23871
346
0.653979
5.207192
false
false
false
false
curious-inc/dry-api-swift
lib/DryApiClient.swift
1
280817
import Foundation; public class DryApiError: NSObject { public let code: String; public let message: String; init(_ code: String, _ message: String){ self.code = code; self.message = message; } class func withError(error: NSError) -> DryApiError { return(DryApiError("NSError.\(error.code)", error.localizedDescription)); } class func withDictionary(dictionary: NSDictionary) -> DryApiError { var code = "no_code"; var message = "no_message"; if let c = dictionary["code"] as? NSString { code = c as String; } if let m = dictionary["message"] as? NSString { message = m as String; } return(DryApiError(code, message)); } public override var description: String { return("code: \(self.code) message: \(self.message)"); } } public class DryApiClientBase : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { var _endpoint = ""; public var debug = false; public let null = NSNull(); init(_ endpoint: String){ _endpoint = endpoint; } var _tags = NSMutableDictionary(); func tags() -> NSDictionary { return(_tags.copy() as! NSDictionary); } func tags(key: String) -> String? { return(_tags[key] as! String?); } func tags(key: String, _ val: String) -> DryApiClientBase { _tags[key] = val; return (self); } var _unsafeDomains: Array<String> = []; func addUnsafeDomain(domain: String) { _unsafeDomains.append(domain); } public func URLSession(_ session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){ // print("https circumvent test host: \(challenge.protectionSpace.host)"); if(_unsafeDomains.indexOf(challenge.protectionSpace.host) != nil){ var credential: NSURLCredential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!); completionHandler(.UseCredential, credential); }else{ completionHandler(.CancelAuthenticationChallenge, nil); } } } var _session: NSURLSession?; func session() -> NSURLSession { if(_session != nil){ return(_session!); } var configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration(); configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Never if(_unsafeDomains.count > 0){ _session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil); }else{ _session = NSURLSession(configuration: configuration); } return(_session!); } func postRequest(url: String, _ data: NSData, _ callback: ((error: DryApiError?, data: NSData?)->())){ let session = self.session(); let nsurl = NSURL(string: url); let request = NSMutableURLRequest(URL: nsurl!); request.HTTPMethod = "POST"; request.HTTPBody = data; // request.setValue("text/plain", forHTTPHeaderField: "Content-Type") let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in if(error != nil){ return callback(error: DryApiError.withError(error!), data: nil); } if let response = response as? NSHTTPURLResponse { if response.statusCode != 200 { return callback(error: DryApiError("not_200", "The server reply was: \(response.statusCode), we only accept 200"), data: nil); } } return callback(error: nil, data: data); }); task.resume() } func postRequestWithString(url: String, _ data: String, _ callback: ((error: DryApiError?, data: NSData?)->())){ return postRequest(url, data.dataUsingEncoding(NSUTF8StringEncoding)!, callback); } func dataToString(data: NSData) -> String{ if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return(string as String); }else{ return(""); } } func responseToArgs(data: NSData?, _ callback: ((error: DryApiError?, args: [AnyObject?]?)->())){ var args: [AnyObject?] = []; if(data == nil){ callback(error: DryApiError("no_data", "No data received."), args: nil); } let data = data!; self.parse(data, { (error, response) in if(error != nil){ return callback(error: error, args: nil); } let response = response! if(self.debug){ print("reponse json: \(response)"); print("reponse string: \(self.dataToString(data))"); } if let params = response["params"] as? NSArray { let error:AnyObject? = response["error"]; if(!(error is NSNull)){ if let error = error as? NSDictionary? { if let error = error { return callback(error: DryApiError.withDictionary(error), args: nil); } } return callback(error: DryApiError("no_code", "object: \(error)"), args: nil); } for key in params { if let key = key as? String { if(key == "error"){ continue; } if let val = response[key] as? NSNull { args.append(nil); }else{ args.append(response[key]); } }else{ return callback(error: DryApiError("malformed_response", "Params contained non string. params: \(params)"), args: nil); } } if(self.debug){ print("processed args: \(args)"); } return callback(error: nil, args: args); }else{ return callback(error: DryApiError("malformed_response", "Response was missing params."), args: nil); } }); } func parse(data: NSData, _ callback: ((error: DryApiError?, response: NSDictionary?)->())){ do { // let result = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0)) as? NSDictionary let result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? NSDictionary callback(error: nil, response: result); } catch let error as NSError { callback(error: DryApiError.withError(error), response: nil); } // var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError) as? NSDictionary } func dataify(value: AnyObject, _ callback: ((error: DryApiError?, response: NSData?)->())){ do { let data = try NSJSONSerialization.dataWithJSONObject(value, options: NSJSONWritingOptions()) callback(error: nil, response: data); } catch let error as NSError { callback(error: DryApiError.withError(error), response: nil); } } func getValue(dict: [String: AnyObject?], _ key: String) -> AnyObject? { if let x:AnyObject? = dict[key] { return(x); }else{ return(nil); } } func logOutgoingMessage(data: NSData?){ if let data = data { if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { print("outgoingMessage data(string): \(str)"); } } } func callEndpointGetArgs(outgoingMessage: NSDictionary, _ callback: ((error: DryApiError?, args: [AnyObject?]?)->())){ self.dataify(outgoingMessage, { (error, data) in if(error != nil){ return callback(error: error, args: nil); } if(self.debug){ self.logOutgoingMessage(data); } self.postRequest(self._endpoint, data!, { (error, response) in if(error != nil){ return callback(error: error, args: nil); } self.responseToArgs(response, { (error, args) in if(error != nil){ return callback(error: error, args: nil); } else{ callback(error: nil, args: args); } }); }); }); } func badSignatureError(index: Int, _ val: AnyObject?) -> DryApiError{ let error: DryApiError = DryApiError("bad_signature", "Your callback didn't match the request format for arg[\(index)]. value: (\(val))"); return(error); } } public class DryApiClient : DryApiClientBase { func call(methodName: String, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<OA>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<OA, OB>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<OA, OB, OC>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<OA, OB, OC, OD>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<OA, OB, OC, OD, OE>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<OA, OB, OC, OD, OE, OF>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, OA>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE, OF>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE, OF, OG>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE, OF, OG, OH>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, ID: NSObject, IE: NSObject, IF: NSObject, IG: NSObject, IH: NSObject, II: NSObject, IJ: NSObject, OA, OB, OC, OD, OE, OF, OG, OH, OI, OJ>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ inArg3: ID, _ inArg4: IE, _ inArg5: IF, _ inArg6: IG, _ inArg7: IH, _ inArg8: II, _ inArg9: IJ, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?, outArg3: OD?, outArg4: OE?, outArg5: OF?, outArg6: OG?, outArg7: OH?, outArg8: OI?, outArg9: OJ?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2","3","4","5","6","7","8","9"], "0": inArg0, "1": inArg1, "2": inArg2, "3": inArg3, "4": inArg4, "5": inArg5, "6": inArg6, "7": inArg7, "8": inArg8, "9": inArg9 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil, outArg3: nil, outArg4: nil, outArg5: nil, outArg6: nil, outArg7: nil, outArg8: nil, outArg9: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } if(args.count <= 3){ args.append(nil); } if(args[3] != nil && ((args[3] as? OD) == nil)){ return errorOut(3, args[3]); } if(args.count <= 4){ args.append(nil); } if(args[4] != nil && ((args[4] as? OE) == nil)){ return errorOut(4, args[4]); } if(args.count <= 5){ args.append(nil); } if(args[5] != nil && ((args[5] as? OF) == nil)){ return errorOut(5, args[5]); } if(args.count <= 6){ args.append(nil); } if(args[6] != nil && ((args[6] as? OG) == nil)){ return errorOut(6, args[6]); } if(args.count <= 7){ args.append(nil); } if(args[7] != nil && ((args[7] as? OH) == nil)){ return errorOut(7, args[7]); } if(args.count <= 8){ args.append(nil); } if(args[8] != nil && ((args[8] as? OI) == nil)){ return errorOut(8, args[8]); } if(args.count <= 9){ args.append(nil); } if(args[9] != nil && ((args[9] as? OJ) == nil)){ return errorOut(9, args[9]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?, outArg3: args[3] as! OD?, outArg4: args[4] as! OE?, outArg5: args[5] as! OF?, outArg6: args[6] as! OG?, outArg7: args[7] as! OH?, outArg8: args[8] as! OI?, outArg9: args[9] as! OJ?); }); } }
apache-2.0
c1304c3e42610b39f05155d552bab895
43.531716
539
0.46375
3.364528
false
false
false
false
bm842/TradingLibrary
Sources/PlaybackInstrument.swift
2
11304
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import Foundation extension OrderCreation { func info(withId id: String, timestamp: Timestamp) -> OrderInfo? { guard let setEntry = entry, let setExpiry = expiry else { return nil } return OrderInfo(orderId: id, time: timestamp, type: type, side: side, units: units, entry: setEntry, stopLoss: stopLoss, takeProfit: takeProfit, expiry: setExpiry) } } public class PlaybackInstrument: GenericInstrument, Instrument { var currentTick: Tick? open override func submitOrder(_ info: OrderCreation, completion: @escaping (RequestStatus, _ execution: OrderExecution) -> ()) { guard let tick = currentTick else { completion(PlaybackStatus.noTick, .none) return } var execution: OrderExecution = .none switch info.type { case .market: let remainingUnits = consolidateUnits(side: info.side, units: info.units, atTick: tick) let openedTradeId: String? if remainingUnits > 0 { let tradeId = "\(Timestamp.now.nanoSeconds)" let newTradeInfo = TradeInfo(tradeId: tradeId, time: tick.time, side: info.side, units: remainingUnits, entry: tick.entryPrice(toSide: info.side), stopLoss: info.stopLoss, takeProfit: info.takeProfit) openedTradeId = tradeId let trade = PlaybackTrade(instrument: self, info: newTradeInfo) genericAccount.internalOpenTrades.append(trade) notify(tradeEvent: .tradeCreated(info: newTradeInfo)) } else { openedTradeId = nil } execution = .orderFilled(tradeId: openedTradeId) case .marketIfTouched: let orderId = "\(Timestamp.now.nanoSeconds)" let openedOrder = info.info(withId: orderId, timestamp: tick.time)! let order = PlaybackOrder(instrument: self, info: openedOrder) genericAccount.internalOpenOrders.append(order) notify(tradeEvent: .orderCreated(info: openedOrder)) execution = OrderExecution.orderCreated(orderId: orderId) default: log.error("%f: order type not implemented") } completion(PlaybackStatus.success, execution) } ///- assuming all trades are with this instrument func consolidateUnits(side: Side, units: UInt, atTick tick: Tickable) -> UInt { var remainingUnits = units for trade in account!.openTrades where remainingUnits > 0 && trade.side != side { let closedUnits = min(trade.openUnits, remainingUnits) remainingUnits -= closedUnits reduceTrade(withId: trade.id, atTime: tick.time, units: closedUnits, atPrice: tick.exitPrice(fromSide: side), reason: .reverseOrder) } return remainingUnits } func fillOrder(atTime time: Timestamp, atPrice price: Price) { } public func inject(tradeWithInfo info: TradeInfo) -> Trade { let trade = PlaybackTrade(instrument: self, info: info) genericAccount.internalOpenTrades.append(trade) return trade } public func inject(orderWithInfo info: OrderInfo) -> Order { let order = PlaybackOrder(instrument: self, info: info) genericAccount.internalOpenOrders.append(order) return order } public func inject(time: Timestamp) { for order in account!.openOrders { if time >= order.expiry { order.expire(atTime: time) } } } ///- assuming all orders are with this instrument public func inject(tick: Tick) { defer { currentTick = tick } let time = tick.time inject(time: time) guard let previousTick = currentTick else { return } for order in account!.openOrders { let price = tick.entryPrice(toSide: order.side) let previousPrice = previousTick.entryPrice(toSide: order.side) switch order.type { case .marketIfTouched: if price >= order.entry && previousPrice < order.entry || price <= order.entry && previousPrice > order.entry { let remainingUnits = consolidateUnits(side: order.side, units: order.units, atTick: tick) let openedTradeId: String? if remainingUnits > 0 { let tradeId = "\(Timestamp.now.nanoSeconds)" let newTradeInfo = TradeInfo(tradeId: tradeId, time: time, side: order.side, units: remainingUnits, entry: price, stopLoss: order.stopLoss, takeProfit: order.takeProfit) openedTradeId = tradeId let trade = PlaybackTrade(instrument: self, info: newTradeInfo) genericAccount.internalOpenTrades.append(trade) notify(tradeEvent: .tradeCreated(info: newTradeInfo)) } else { openedTradeId = nil } let orderClosed = TradeEvent.orderClosed(info: OrderClosure(orderId: order.id, time: time, reason: .filled(price: price, openedTradeId: openedTradeId))) let _ = genericAccount.removeOrder(order.id) notify(tradeEvent: orderClosed) } default: log.error("%f: order type not handled") } } for trade in account!.openTrades { if let stopLoss = trade.stopLoss { if tick.touches(stopLoss: stopLoss, atSide: trade.side) { trade.close(atTime: time, atPrice: tick.exitPrice(fromSide: trade.side), reason: .stopLossFilled) continue } } if let takeProfit = trade.takeProfit { if tick.touches(takeProfit: takeProfit, atSide: trade.side) { trade.close(atTime: time, atPrice: tick.exitPrice(fromSide: trade.side), reason: .takeProfitFilled) } } } } /*open func startRatesStreaming(_ queue: DispatchQueue, handler: @escaping (RatesEvent) -> ()) -> RequestStatus { log.warning("%f: not implemented") return PlaybackStatus.success } open func stopRatesStreaming() { log.error("%f: not implemented") } open func startEventsStreaming(_ queue: DispatchQueue, handler: @escaping (TradeEvent) -> ()) { log.error("%f: not implemented") } open func stopEventsStreaming() { log.error("%f: not implemented") }*/ open override func quote(_ completion: @escaping (RequestStatus, _ tick: Tick?) -> ()) { completion(PlaybackStatus.success, currentTick) } public var emulatesNotificationDelay = false let emulatedDelayQueue = DispatchQueue(label: "emulatedDelayQueue") override func notify(tradeEvent event: TradeEvent) { if emulatesNotificationDelay { let minDelay = 0.5 let maxDelay = 2.0 let nanoSecondsDelay = UInt64((minDelay + Double(arc4random_uniform(1000))/1000.0 * (maxDelay - minDelay)) * 1_000_000_000) emulatedDelayQueue.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + nanoSecondsDelay)) { super.notify(tradeEvent: event) } } else { super.notify(tradeEvent: event) } } }
mit
fa59fc6e3e8aa67088015d21310e036d
34.325
141
0.477176
5.856995
false
false
false
false
6ag/BaoKanIOS
BaoKanIOS/Classes/Module/Profile/Controller/JFProfileFeedbackViewController.swift
1
5443
// // JFProfileFeedbackViewController.swift // BaoKanIOS // // Created by zhoujianfeng on 16/5/26. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit class JFProfileFeedbackViewController: JFBaseTableViewController { override func viewDidLoad() { super.viewDidLoad() prepareUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.statusBarStyle = UIStatusBarStyle.default navigationController?.setNavigationBarHidden(false, animated: true) } deinit { NotificationCenter.default.removeObserver(self) } /** 准备UI */ fileprivate func prepareUI() { let headerView = UIView() headerView.frame = view.bounds headerView.backgroundColor = BACKGROUND_COLOR headerView.addSubview(contentTextView) headerView.addSubview(contactTextField) headerView.addSubview(commitButton) tableView.tableHeaderView = headerView NotificationCenter.default.addObserver(self, selector: #selector(didChangeValueForContentTextView(_:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil) } /** 内容文本改变事件 */ @objc fileprivate func didChangeValueForContentTextView(_ notification: Notification) { changeCommitState() } /** 联系人文本改变事件 */ @objc fileprivate func didChangeValueForContactTextField(_ field: UITextField) { changeCommitState() } /** 提交按钮点击事件 */ @objc fileprivate func didTappedCommitButton(_ commitButton: UIButton) { tableView.isUserInteractionEnabled = false JFProgressHUD.showWithStatus("正在提交") let parameters = [ "content" : contentTextView.text, "contact" : contactTextField.text! ] as [String : Any] JFNetworkTool.shareNetworkTool.post("http://120.24.79.174/jiansan/feedback.php", parameters: parameters as [String : AnyObject]?) { (success, result, error) in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.tableView.isUserInteractionEnabled = true JFProgressHUD.showSuccessWithStatus("谢谢支持") // 返回上一级控制器 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) { _ = self.navigationController?.popViewController(animated: true) } } } } /** 改变提交按钮状态 */ fileprivate func changeCommitState() { if contentTextView.text.characters.count >= 10 && (contactTextField.text?.characters.count)! >= 5 { commitButton.isEnabled = true commitButton.backgroundColor = UIColor(red:0.871, green:0.259, blue:0.294, alpha:1) } else { commitButton.isEnabled = false commitButton.backgroundColor = UIColor(red:0.733, green:0.733, blue:0.733, alpha:1) } } /// 内容文本框 lazy var contentTextView: UITextView = { let contentTextView = UITextView(frame: CGRect(x: MARGIN, y: 10, width: SCREEN_WIDTH - MARGIN * 2, height: 200)) contentTextView.layer.cornerRadius = CORNER_RADIUS return contentTextView }() /// 联系方式文本框 lazy var contactTextField: UITextField = { let contactTextField = UITextField(frame: CGRect(x: MARGIN, y: self.contentTextView.frame.maxY + MARGIN, width: SCREEN_WIDTH - MARGIN * 2, height: 40)) contactTextField.layer.cornerRadius = CORNER_RADIUS contactTextField.backgroundColor = UIColor.white contactTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: MARGIN, height: 0)) contactTextField.attributedPlaceholder = NSAttributedString(string: "请输入您的联系方式 QQ/Email/手机", attributes: [ NSForegroundColorAttributeName : UIColor(red:0.833, green:0.833, blue:0.833, alpha:1), NSFontAttributeName : UIFont.systemFont(ofSize: 14) ]) contactTextField.leftViewMode = .always contactTextField.addTarget(self, action: #selector(didChangeValueForContactTextField(_:)), for: UIControlEvents.editingChanged) return contactTextField }() /// 提交按钮 lazy var commitButton: UIButton = { let commitButton = UIButton(type: UIButtonType.system) commitButton.frame = CGRect(x: MARGIN, y: self.contactTextField.frame.maxY + MARGIN, width: SCREEN_WIDTH - MARGIN * 2, height: 40) commitButton.setTitle("提交", for: UIControlState()) commitButton.setTitleColor(UIColor.white, for: UIControlState()) commitButton.layer.cornerRadius = CORNER_RADIUS commitButton.isEnabled = false commitButton.backgroundColor = UIColor(red:0.733, green:0.733, blue:0.733, alpha:1) commitButton.addTarget(self, action: #selector(didTappedCommitButton(_:)), for: UIControlEvents.touchUpInside) return commitButton }() }
apache-2.0
0ce168bfe1926c7518e7c1a76d9c8243
36.404255
175
0.63595
4.755636
false
false
false
false
fgengine/quickly
Quickly/Collection/QCollectionController.swift
1
25637
// // Quickly // open class QCollectionController : NSObject, IQCollectionController, CollectionCellDelegate, IQCollectionDecorDelegate { public typealias CollectionView = IQCollectionController.CollectionView public typealias Decor = IQCollectionController.Decor public typealias Cell = IQCollectionController.Cell public weak var collectionView: CollectionView? = nil { didSet { if self.collectionView != nil { self.configure() } } } public var sections: [IQCollectionSection] = [] { willSet { self._unbindSections() } didSet { self._bindSections() } } public var items: [IQCollectionItem] { get { return self.sections.flatMap({ (section: IQCollectionSection) -> [IQCollectionItem] in return section.items }) } } public var selectedItems: [IQCollectionItem] { set(value) { guard let collectionView = self.collectionView else { return } if let selectedIndexPaths = collectionView.indexPathsForSelectedItems { for indexPath in selectedIndexPaths { collectionView.deselectItem(at: indexPath, animated: false) } } for item in value { collectionView.selectItem(at: item.indexPath, animated: false, scrollPosition: []) } } get { guard let collectionView = self.collectionView, let selectedIndexPaths = collectionView.indexPathsForSelectedItems else { return [] } return selectedIndexPaths.compactMap({ (indexPath: IndexPath) -> IQCollectionItem? in return self.sections[indexPath.section].items[indexPath.item] }) } } public var canMove: Bool = true public private(set) var isBatchUpdating: Bool = false public private(set) var decors: [IQCollectionDecor.Type] public private(set) var cells: [IQCollectionCell.Type] private var _aliasDecors: [QMetatype : IQCollectionDecor.Type] private var _aliasCells: [QMetatype : IQCollectionCell.Type] private var _observer: QObserver< IQCollectionControllerObserver > public init( cells: [IQCollectionCell.Type] ) { self.decors = [] self._aliasDecors = [:] self.cells = cells self._aliasCells = [:] self._observer = QObserver< IQCollectionControllerObserver >() super.init() } public init( decors: [IQCollectionDecor.Type], cells: [IQCollectionCell.Type] ) { self.decors = decors self._aliasDecors = [:] self.cells = cells self._aliasCells = [:] self._observer = QObserver< IQCollectionControllerObserver >() super.init() } open func configure() { if let collectionView = self.collectionView { for type in self.decors { type.register(collectionView: collectionView, kind: UICollectionView.elementKindSectionHeader) type.register(collectionView: collectionView, kind: UICollectionView.elementKindSectionFooter) } for type in self.cells { type.register(collectionView: collectionView) } } self.rebuild() } open func rebuild() { self.reload() } open func add(observer: IQCollectionControllerObserver, priority: UInt) { self._observer.add(observer, priority: priority) } open func remove(observer: IQCollectionControllerObserver) { self._observer.remove(observer) } open func section(index: Int) -> IQCollectionSection { return self.sections[index] } open func index(section: IQCollectionSection) -> Int? { return self.sections.firstIndex { (existSection: IQCollectionSection) -> Bool in return existSection === section } } open func header(index: Int) -> IQCollectionData? { return self.sections[index].header } open func index(header: IQCollectionData) -> Int? { return self.sections.firstIndex(where: { (existSection: IQCollectionSection) -> Bool in return existSection.header === header }) } open func footer(index: Int) -> IQCollectionData? { return self.sections[index].footer } open func index(footer: IQCollectionData) -> Int? { return self.sections.firstIndex(where: { (existSection: IQCollectionSection) -> Bool in return existSection.footer === footer }) } open func item(indexPath: IndexPath) -> IQCollectionItem { return self.sections[indexPath.section].items[indexPath.item] } open func item(predicate: (IQCollectionItem) -> Bool) -> IQCollectionItem? { for section in self.sections { for item in section.items { if predicate(item) { return item } } } return nil } open func indexPath(item: IQCollectionItem) -> IndexPath? { return item.indexPath } open func indexPath(predicate: (IQCollectionItem) -> Bool) -> IndexPath? { for existSection in self.sections { for existItem in existSection.items { if predicate(existItem) == true { return existItem.indexPath } } } return nil } open func dequeue(data: IQCollectionData, kind: String, indexPath: IndexPath) -> Decor? { guard let collectionView = self.collectionView, let decorClass = self._decorClass(data: data), let decorView = decorClass.dequeue(collectionView: collectionView, kind: kind, indexPath: indexPath) else { return nil } decorView.collectionDelegate = self return decorView } open func dequeue(item: IQCollectionItem, indexPath: IndexPath) -> Cell? { guard let collectionView = self.collectionView, let cellClass = self._cellClass(item: item), let cellView = cellClass.dequeue(collectionView: collectionView, indexPath: indexPath) else { return nil } cellView.collectionDelegate = self return cellView } open func reload() { guard let collectionView = self.collectionView else { return } collectionView.reloadData() self._notifyUpdate() } open func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) { #if DEBUG assert(self.isBatchUpdating == false, "Recurcive calling IQCollectionController.performBatchUpdates()") #endif guard let collectionView = self.collectionView else { return } self.isBatchUpdating = true collectionView.performBatchUpdates(updates, completion: { [weak self] (finish: Bool) in if let self = self { self.isBatchUpdating = false self._notifyUpdate() } completion?(finish) }) } open func insertSection(_ sections: [IQCollectionSection], index: Int) { self.sections.insert(contentsOf: sections, at: index) self._bindSections(from: index, to: self.sections.endIndex) var indexSet = IndexSet() for section in self.sections { if let sectionIndex = section.index { indexSet.insert(sectionIndex) } } if indexSet.count > 0 { if let collectionView = self.collectionView { collectionView.insertSections(indexSet) } } } open func deleteSection(_ sections: [IQCollectionSection]) { var indexSet = IndexSet() for section in sections { if let index = self.sections.firstIndex(where: { return ($0 === section) }) { indexSet.insert(index) } } if indexSet.count > 0 { for index in indexSet.reversed() { let section = self.sections[index] self.sections.remove(at: index) section.unbind() } self._bindSections(from: indexSet.first!, to: self.sections.endIndex) if let collectionView = self.collectionView { collectionView.deleteSections(indexSet) } } } open func reloadSection(_ sections: [IQCollectionSection]) { var indexSet = IndexSet() for section in sections { if let index = self.sections.firstIndex(where: { return ($0 === section) }) { indexSet.insert(index) } } if indexSet.count > 0 { if let collectionView = self.collectionView { collectionView.reloadSections(indexSet) } } } open func scroll(item: IQCollectionItem, scroll: UICollectionView.ScrollPosition, animated: Bool) { guard let collectionView = self.collectionView, let indexPath = self.indexPath(item: item) else { return } collectionView.scrollToItem(at: indexPath, at: scroll, animated: animated) } open func isSelected(item: IQCollectionItem) -> Bool { guard let collectionView = self.collectionView, let selectedIndexPaths = collectionView.indexPathsForSelectedItems, let indexPath = self.indexPath(item: item) else { return false } return selectedIndexPaths.contains(indexPath) } open func select(item: IQCollectionItem, scroll: UICollectionView.ScrollPosition, animated: Bool) { guard let collectionView = self.collectionView, let indexPath = self.indexPath(item: item) else { return } collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: scroll) } open func deselect(item: IQCollectionItem, animated: Bool) { guard let collectionView = self.collectionView, let indexPath = self.indexPath(item: item) else { return } collectionView.deselectItem(at: indexPath, animated: animated) } open func deselectAll(animated: Bool) { guard let collectionView = self.collectionView else { return } if let selectedItems = collectionView.indexPathsForSelectedItems { for selectedItem in selectedItems.reversed() { collectionView.deselectItem(at: selectedItem, animated: animated) } } } open func update(header: IQCollectionData, animated: Bool) { if #available(iOS 9.0, *) { guard let collectionView = self.collectionView, let index = self.index(header: header), let decor = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: index)) as? IQCollectionDecor else { return } decor.set(any: header, spec: collectionView, animated: animated) if self.isBatchUpdating == false { self._notifyUpdate() } } } open func update(footer: IQCollectionData, animated: Bool) { if #available(iOS 9.0, *) { guard let collectionView = self.collectionView, let index = self.index(footer: footer), let decor = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionFooter, at: IndexPath(item: 0, section: index)) as? IQCollectionDecor else { return } decor.set(any: footer, spec: collectionView, animated: animated) if self.isBatchUpdating == false { self._notifyUpdate() } } } open func update(item: IQCollectionItem, animated: Bool) { guard let collectionView = self.collectionView, let indexPath = self.indexPath(item: item), let cell = collectionView.cellForItem(at: indexPath) as? IQCollectionCell else { return } cell.set(any: item, spec: collectionView, animated: animated) if self.isBatchUpdating == false { self._notifyUpdate() } } } // MARK: Private private extension QCollectionController { func _bindSections() { var sectionIndex: Int = 0 for section in self.sections { section.bind(self, sectionIndex) sectionIndex += 1 } } func _bindSections(from: Int, to: Int) { for index in from..<to { self.sections[index].bind(self, index) } } func _unbindSections() { for section in self.sections { section.unbind() } } func _notifyUpdate() { self._observer.notify({ $0.update(self) }) } func _decorClass(data: IQCollectionData) -> IQCollectionDecor.Type? { let dataMetatype = QMetatype(data) if let metatype = self._aliasDecors.first(where: { return $0.key == dataMetatype }) { return metatype.value } let usings = self.decors.filter({ return $0.using(any: data) }) guard usings.count > 0 else { return nil } if usings.count > 1 { let typeOfData = type(of: data) let levels = usings.compactMap({ (type) -> (IQCollectionDecor.Type, UInt)? in guard let level = type.usingLevel(any: typeOfData) else { return nil } return (type, level) }) let sorted = levels.sorted(by: { return $0.1 > $1.1 }) let decorType = sorted.first!.0 self._aliasDecors[dataMetatype] = decorType return decorType } else { let decorType = usings.first! self._aliasDecors[dataMetatype] = decorType return decorType } } func _cellClass(item: IQCollectionItem) -> IQCollectionCell.Type? { let rowMetatype = QMetatype(item) if let metatype = self._aliasCells.first(where: { return $0.key == rowMetatype }) { return metatype.value } let usings = self.cells.filter({ return $0.using(any: item) }) guard usings.count > 0 else { return nil } if usings.count > 1 { let typeOfData = type(of: item) let levels = usings.compactMap({ (type) -> (IQCollectionCell.Type, UInt)? in guard let level = type.usingLevel(any: typeOfData) else { return nil } return (type, level) }) let sorted = levels.sorted(by: { return $0.1 > $1.1 }) let cellType = sorted.first!.0 self._aliasCells[rowMetatype] = cellType return cellType } else { let cellType = usings.first! self._aliasCells[rowMetatype] = cellType return cellType } } } // MARK: UIScrollViewDelegate extension QCollectionController : UIScrollViewDelegate { @objc open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { let collectionView = self.collectionView! self._observer.notify({ $0.beginScroll(self, collectionView: collectionView) }) } @objc open func scrollViewDidScroll(_ scrollView: UIScrollView) { let collectionView = self.collectionView! self._observer.notify({ $0.scroll(self, collectionView: collectionView) }) } @objc open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer< CGPoint >) { let collectionView = self.collectionView! var targetContentOffsets: [CGPoint] = [] self._observer.notify({ if let contentOffset = $0.finishScroll(self, collectionView: collectionView, velocity: velocity) { targetContentOffsets.append(contentOffset) } }) if targetContentOffsets.count > 0 { var avgTargetContentOffset = targetContentOffsets.first! if targetContentOffsets.count > 1 { for nextTargetContentOffset in targetContentOffsets { avgTargetContentOffset = CGPoint( x: (avgTargetContentOffset.x + nextTargetContentOffset.x) / 2, y: (avgTargetContentOffset.y + nextTargetContentOffset.y) / 2 ) } } targetContentOffset.pointee = avgTargetContentOffset } } @objc open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate == false { let collectionView = self.collectionView! self._observer.notify({ $0.endScroll(self, collectionView: collectionView) }) } } @objc open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let collectionView = self.collectionView! self._observer.notify({ $0.endScroll(self, collectionView: collectionView) }) } @objc open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { let collectionView = self.collectionView! self._observer.notify({ $0.beginZoom(self, collectionView: collectionView) }) } @objc open func scrollViewDidZoom(_ scrollView: UIScrollView) { let collectionView = self.collectionView! self._observer.notify({ $0.zoom(self, collectionView: collectionView) }) } @objc open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { let collectionView = self.collectionView! self._observer.notify({ $0.endZoom(self, collectionView: collectionView) }) } } // MARK: UICollectionViewDataSource extension QCollectionController : UICollectionViewDataSource { @objc open func numberOfSections( in collectionView: UICollectionView ) -> Int { return self.sections.count } @objc open func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection index: Int ) -> Int { let section = self.section(index: index) if section.hidden == true { return 0 } return section.items.count } @objc open func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let item = self.item(indexPath: indexPath) return self.dequeue(item: item, indexPath: indexPath).unsafelyUnwrapped } @objc open func collectionView( _ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath ) -> UICollectionReusableView { var data: IQCollectionData? = nil if kind == UICollectionView.elementKindSectionHeader { data = self.header(index: indexPath.section) } else if kind == UICollectionView.elementKindSectionFooter { data = self.footer(index: indexPath.section) } return self.dequeue(data: data!, kind: kind, indexPath: indexPath).unsafelyUnwrapped } @objc open func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { let section = self.section(index: indexPath.section) if section.canMove == false { return false; } let item = section.items[indexPath.item] return item.canMove; } } // MARK: UICollectionViewDelegate extension QCollectionController : UICollectionViewDelegate { @objc open func collectionView( _ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath ) { if let collectionCell = cell as? IQCollectionCell { let item = self.item(indexPath: indexPath) collectionCell.set(any: item, spec: collectionView as! IQContainerSpec, animated: false) collectionCell.beginDisplay() } } @objc open func collectionView( _ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath ) { if let collectionCell = cell as? IQCollectionCell { collectionCell.endDisplay() } } @objc open func collectionView( _ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath ) { var data: IQCollectionData? = nil if elementKind == UICollectionView.elementKindSectionHeader { data = self.header(index: indexPath.section) } else if elementKind == UICollectionView.elementKindSectionFooter { data = self.footer(index: indexPath.section) } if let safeData = data { if let collectionDecor = view as? IQCollectionDecor { collectionDecor.set(any: safeData, spec: collectionView as! IQContainerSpec, animated: false) } } } @objc open func collectionView( _ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath ) -> Bool { let item = self.item(indexPath: indexPath) return item.canSelect } @objc open func collectionView( _ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath ) -> Bool { let item = self.item(indexPath: indexPath) return item.canSelect } @objc open func collectionView( _ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath ) -> Bool { let item = self.item(indexPath: indexPath) return item.canDeselect } } // MARK: UICollectionViewDelegateFlowLayout extension QCollectionController : UICollectionViewDelegateFlowLayout { @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let section = self.section(index: indexPath.section) let item = self.item(indexPath: indexPath) if let cellClass = self._cellClass(item: item) { return cellClass.size(any: item, layout: collectionViewLayout, section: section, spec: collectionView as! IQContainerSpec) } return CGSize.zero } @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt index: Int ) -> UIEdgeInsets { let section = self.section(index: index) if let inset = section.insets { return inset } if let layout = collectionViewLayout as? UICollectionViewFlowLayout { return layout.sectionInset } return UIEdgeInsets.zero } @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt index: Int ) -> CGFloat { let section = self.section(index: index) if let minimumLineSpacing = section.minimumLineSpacing { return minimumLineSpacing } if let layout = collectionViewLayout as? UICollectionViewFlowLayout { return layout.minimumInteritemSpacing } return 0 } @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt index: Int ) -> CGFloat { let section = self.section(index: index) if let minimumInteritemSpacing = section.minimumInteritemSpacing { return minimumInteritemSpacing } if let layout = collectionViewLayout as? UICollectionViewFlowLayout { return layout.minimumInteritemSpacing } return 0 } @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection sectionIndex: Int ) -> CGSize { let section = self.section(index: sectionIndex) if let data = section.header { if let decorClass = self._decorClass(data: data) { return decorClass.size(any: data, layout: collectionViewLayout, section: section, spec: collectionView as! IQContainerSpec) } } return CGSize.zero } @objc open func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection sectionIndex: Int ) -> CGSize { let section = self.section(index: sectionIndex) if let data = section.footer { if let decorClass = self._decorClass(data: data) { return decorClass.size(any: data, layout: collectionViewLayout, section: section, spec: collectionView as! IQContainerSpec) } } return CGSize.zero } }
mit
586e8d156268634748f74a79419faff0
34.312672
181
0.614932
5.243813
false
false
false
false
longitachi/ZLPhotoBrowser
Example/Example/Kingfisher/Cache/ImageCache.swift
1
38382
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif extension Notification.Name { /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger /// this notification. /// /// The `object` of this notification is the `ImageCache` object which sends the notification. /// A list of removed hashes (files) could be retrieved by accessing the array under /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. /// By checking the array, you could know the hash codes of files are removed. public static let KingfisherDidCleanDiskCache = Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") } /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" /// Cache type of a cached image. /// - none: The image is not cached yet when retrieving it. /// - memory: The image is cached in memory. /// - disk: The image is cached in disk. public enum CacheType { /// The image is not cached yet when retrieving it. case none /// The image is cached in memory. case memory /// The image is cached in disk. case disk /// Whether the cache type represents the image is already cached or not. public var cached: Bool { switch self { case .memory, .disk: return true case .none: return false } } } /// Represents the caching operation result. public struct CacheStoreResult { /// The cache result for memory cache. Caching an image to memory will never fail. public let memoryCacheResult: Result<(), Never> /// The cache result for disk cache. If an error happens during caching operation, /// you can get it from `.failure` case of this `diskCacheResult`. public let diskCacheResult: Result<(), KingfisherError> } extension KFCrossPlatformImage: CacheCostCalculable { /// Cost of an image public var cacheCost: Int { return kf.cost } } extension Data: DataTransformable { public func toData() throws -> Data { return self } public static func fromData(_ data: Data) throws -> Data { return data } public static let empty = Data() } /// Represents the getting image operation from the cache. /// /// - disk: The image can be retrieved from disk cache. /// - memory: The image can be retrieved memory cache. /// - none: The image does not exist in the cache. public enum ImageCacheResult { /// The image can be retrieved from disk cache. case disk(KFCrossPlatformImage) /// The image can be retrieved memory cache. case memory(KFCrossPlatformImage) /// The image does not exist in the cache. case none /// Extracts the image from cache result. It returns the associated `Image` value for /// `.disk` and `.memory` case. For `.none` case, `nil` is returned. public var image: KFCrossPlatformImage? { switch self { case .disk(let image): return image case .memory(let image): return image case .none: return nil } } /// Returns the corresponding `CacheType` value based on the result type of `self`. public var cacheType: CacheType { switch self { case .disk: return .disk case .memory: return .memory case .none: return .none } } } /// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`. /// `ImageCache` is a high level abstract for storing an image as well as its data to disk memory and disk, and /// retrieving them back. /// /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create /// your own cache object and configure its storages as your need. This class also provide an interface for you to set /// the memory and disk storage config. open class ImageCache { // MARK: Singleton /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no /// other cache specified. The `name` of this default cache is "default", and you should not use this name /// for any of your customize cache. public static let `default` = ImageCache(name: "default") // MARK: Public Properties /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage> /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let diskStorage: DiskStorage.Backend<Data> private let ioQueue: DispatchQueue /// Closure that defines the disk cache path from a given path and cacheName. public typealias DiskCachePathClosure = (URL, String) -> URL // MARK: Initializers /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`. /// /// - Parameters: /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache. /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache. public init( memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>, diskStorage: DiskStorage.Backend<Data>) { self.memoryStorage = memoryStorage self.diskStorage = diskStorage let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)" ioQueue = DispatchQueue(label: ioQueueName) let notifications: [(Notification.Name, Selector)] #if !os(macOS) && !os(watchOS) #if swift(>=4.2) notifications = [ (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) ] #else notifications = [ (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)), (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)), (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache)) ] #endif #elseif os(macOS) notifications = [ (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)), ] #else notifications = [] #endif notifications.forEach { NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil) } } /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created /// with a default config based on the `name`. /// /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. The `name` should not be an empty string. public convenience init(name: String) { try! self.init(name: name, cacheDirectoryURL: nil, diskCachePathClosure: nil) } /// Creates an `ImageCache` with a given `name`, cache directory `path` /// and a closure to modify the cache directory. /// /// - Parameters: /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. /// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the /// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache /// directory under user domain mask will be used. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates /// the final disk cache path. You could use it to fully customize your cache path. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given /// path. public convenience init( name: String, cacheDirectoryURL: URL?, diskCachePathClosure: DiskCachePathClosure? = nil) throws { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let totalMemory = ProcessInfo.processInfo.physicalMemory let costLimit = totalMemory / 4 let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config: .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) var diskConfig = DiskStorage.Config( name: name, sizeLimit: 0, directory: cacheDirectoryURL ) if let closure = diskCachePathClosure { diskConfig.cachePathBlock = closure } let diskStorage = try DiskStorage.Backend<Data>(config: diskConfig) diskConfig.cachePathBlock = nil self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Storing Images open func store(_ image: KFCrossPlatformImage, original: Data? = nil, forKey key: String, options: KingfisherParsedOptionsInfo, toDisk: Bool = true, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let identifier = options.processor.identifier let callbackQueue = options.callbackQueue let computedKey = key.computedKey(with: identifier) // Memory storage should not throw. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration) guard toDisk else { if let completionHandler = completionHandler { let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) callbackQueue.execute { completionHandler(result) } } return } ioQueue.async { let serializer = options.cacheSerializer if let data = serializer.data(with: image, original: original) { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: options.diskCacheExpiration, completionHandler: completionHandler) } else { guard let completionHandler = completionHandler else { return } let diskError = KingfisherError.cacheError( reason: .cannotSerializeImage(image: image, original: original, serializer: serializer)) let result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError)) callbackQueue.execute { completionHandler(result) } } } } /// Stores an image to the cache. /// /// - Parameters: /// - image: The image to be stored. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to /// data for caching in disk, it checks the image format based on `original` data to determine in /// which image format should be used. For other types of `serializer`, it depends on their /// implementation detail on how to use this original data. /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - serializer: The `CacheSerializer` /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory. /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue` /// value. /// - completionHandler: A closure which is invoked when the cache operation finishes. open func store(_ image: KFCrossPlatformImage, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { struct TempProcessor: ImageProcessor { let identifier: String func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return nil } } let options = KingfisherParsedOptionsInfo([ .processor(TempProcessor(identifier: identifier)), .cacheSerializer(serializer), .callbackQueue(callbackQueue) ]) store(image, original: original, forKey: key, options: options, toDisk: toDisk, completionHandler: completionHandler) } open func storeToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", expiration: StorageExpiration? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { ioQueue.async { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: expiration, completionHandler: completionHandler) } } private func syncStoreToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", callbackQueue: CallbackQueue = .untouch, expiration: StorageExpiration? = nil, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) let result: CacheStoreResult do { try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration) result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) } catch { let diskError: KingfisherError if let error = error as? KingfisherError { diskError = error } else { diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error)) } result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError) ) } if let completionHandler = completionHandler { callbackQueue.execute { completionHandler(result) } } } // MARK: Removing Images /// Removes the image for the given key from the cache. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - fromMemory: Whether this image should be removed from memory storage or not. /// If `false`, the image won't be removed from the memory storage. Default is `true`. /// - fromDisk: Whether this image should be removed from disk storage or not. /// If `false`, the image won't be removed from the disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the cache removing operation finishes. open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromMemory: Bool = true, fromDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) if fromMemory { try? memoryStorage.remove(forKey: computedKey) } if fromDisk { ioQueue.async{ try? self.diskStorage.remove(forKey: computedKey) if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } else { if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } func retrieveImage(forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .mainCurrentOrAsync, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { // No completion handler. No need to start working and early return. guard let completionHandler = completionHandler else { return } // Try to check the image from memory cache first. if let image = retrieveImageInMemoryCache(forKey: key, options: options) { let image = options.imageModifier?.modify(image) ?? image callbackQueue.execute { completionHandler(.success(.memory(image))) } } else if options.fromMemoryCacheOrRefresh { callbackQueue.execute { completionHandler(.success(.none)) } } else { // Begin to disk search. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) { result in switch result { case .success(let image): guard let image = image else { // No image found in disk storage. callbackQueue.execute { completionHandler(.success(.none)) } return } let finalImage = options.imageModifier?.modify(image) ?? image // Cache the disk image to memory. // We are passing `false` to `toDisk`, the memory cache does not change // callback queue, we can call `completionHandler` without another dispatch. var cacheOptions = options cacheOptions.callbackQueue = .untouch self.store( finalImage, forKey: key, options: cacheOptions, toDisk: false) { _ in callbackQueue.execute { completionHandler(.success(.disk(finalImage))) } } case .failure(let error): callbackQueue.execute { completionHandler(.failure(error)) } } } } } // MARK: Getting Images /// Gets an image for a given key from the cache, either from memory storage or disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the /// image retrieving operation finishes without problem, an `ImageCacheResult` value /// will be sent to this closure as result. Otherwise, a `KingfisherError` result /// with detail failing reason will be sent. open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .mainCurrentOrAsync, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { retrieveImage( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } func retrieveImageInMemoryCache( forKey key: String, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { let computedKey = key.computedKey(with: options.processor.identifier) return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration) } /// Gets an image for a given key from the memory storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or /// has already expired, `nil` is returned. open func retrieveImageInMemoryCache( forKey key: String, options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? { return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options)) } func retrieveImageInDiskCache( forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void) { let computedKey = key.computedKey(with: options.processor.identifier) let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue) loadingQueue.execute { do { var image: KFCrossPlatformImage? = nil if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) { image = options.cacheSerializer.image(with: data, options: options) } callbackQueue.execute { completionHandler(.success(image)) } } catch { if let error = error as? KingfisherError { callbackQueue.execute { completionHandler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets an image for a given key from the disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the operation finishes. open func retrieveImageInDiskCache( forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void) { retrieveImageInDiskCache( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } // MARK: Cleaning /// Clears the memory & disk storage of this cache. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. public func clearCache(completion handler: (() -> Void)? = nil) { clearMemoryCache() clearDiskCache(completion: handler) } /// Clears the memory storage of this cache. @objc public func clearMemoryCache() { try? memoryStorage.removeAll() } /// Clears the disk storage of this cache. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func clearDiskCache(completion handler: (() -> Void)? = nil) { ioQueue.async { do { try self.diskStorage.removeAll() } catch _ { } if let handler = handler { DispatchQueue.main.async { handler() } } } } /// Clears the expired images from memory & disk storage. This is an async operation. open func cleanExpiredCache(completion handler: (() -> Void)? = nil) { cleanExpiredMemoryCache() cleanExpiredDiskCache(completion: handler) } /// Clears the expired images from disk storage. open func cleanExpiredMemoryCache() { memoryStorage.removeExpired() } /// Clears the expired images from disk storage. This is an async operation. @objc func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } /// Clears the expired images from disk storage. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) { ioQueue.async { do { var removed: [URL] = [] let removedExpired = try self.diskStorage.removeExpiredValues() removed.append(contentsOf: removedExpired) let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues() removed.append(contentsOf: removedSizeExceeded) if !removed.isEmpty { DispatchQueue.main.async { let cleanedHashes = removed.map { $0.lastPathComponent } NotificationCenter.default.post( name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } } if let handler = handler { DispatchQueue.main.async { handler() } } } catch {} } } #if !os(macOS) && !os(watchOS) /// Clears the expired images from disk storage when app is in background. This is an async operation. /// In most cases, you should not call this method explicitly. /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return } func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) #if swift(>=4.2) task = UIBackgroundTaskIdentifier.invalid #else task = UIBackgroundTaskInvalid #endif } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTask { endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCache { endBackgroundTask(&backgroundTask!) } } #endif // MARK: Image Cache State /// Returns the cache type for a given `key` and `identifier` combination. /// This method is used for checking whether an image is cached in current cache. /// It also provides information on which kind of cache can it be found in the return value. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `CacheType` instance which indicates the cache status. /// `.none` means the image is not in cache or it is already expired. open func imageCachedType( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType { let computedKey = key.computedKey(with: identifier) if memoryStorage.isCached(forKey: computedKey) { return .memory } if diskStorage.isCached(forKey: computedKey) { return .disk } return .none } /// Returns whether the file exists in cache for a given `key` and `identifier` combination. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination. /// /// - Note: /// The return value does not contain information about from which kind of storage the cache matches. /// To get the information about cache type according `CacheType`, /// use `imageCachedType(forKey:processorIdentifier:)` instead. public func isCached( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool { return imageCachedType(forKey: key, processorIdentifier: identifier).cached } /// Gets the hash used as cache file name for the key. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The hash which is used as the cache file name. /// /// - Note: /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value /// returned by this method as the cache file name. You can use this value to check and match cache file /// if you need. open func hash( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileName(forKey: computedKey) } /// Calculates the size taken by the disk storage. /// It is the total file size of all cached files in the `diskStorage` on disk in bytes. /// /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue. open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) { ioQueue.async { do { let size = try self.diskStorage.totalSize() DispatchQueue.main.async { handler(.success(size)) } } catch { if let error = error as? KingfisherError { DispatchQueue.main.async { handler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets the cache path for the key. /// It is useful for projects with web view or anyone that needs access to the local file path. /// /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The disk path of cached image under the given `key` and `identifier`. /// /// - Note: /// This method does not guarantee there is an image already cached in the returned path. It just gives your /// the path that the image should be, if it exists in disk storage. /// /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk. open func cachePath( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileURL(forKey: computedKey).path } } extension Dictionary { func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(macOS) && !os(watchOS) // MARK: - For App Extensions extension UIApplication: KingfisherCompatible { } extension KingfisherWrapper where Base: UIApplication { public static var shared: UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard Base.responds(to: selector) else { return nil } return Base.perform(selector).takeUnretainedValue() as? UIApplication } } #endif extension String { func computedKey(with identifier: String) -> String { if identifier.isEmpty { return self } else { return appending("@\(identifier)") } } } extension ImageCache { /// Creates an `ImageCache` with a given `name`, cache directory `path` /// and a closure to modify the cache directory. /// /// - Parameters: /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. /// - path: Location of cache URL on disk. It will be internally pass to the initializer of `DiskStorage` as the /// disk cache directory. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates /// the final disk cache path. You could use it to fully customize your cache path. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given /// path. @available(*, deprecated, message: "Use `init(name:cacheDirectoryURL:diskCachePathClosure:)` instead", renamed: "init(name:cacheDirectoryURL:diskCachePathClosure:)") public convenience init( name: String, path: String?, diskCachePathClosure: DiskCachePathClosure? = nil) throws { let directoryURL = path.flatMap { URL(string: $0) } try self.init(name: name, cacheDirectoryURL: directoryURL, diskCachePathClosure: diskCachePathClosure) } }
mit
bd7acc805810283229ba64dc57b2a16c
43.943794
144
0.626752
5.242726
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructure/Cards/Card.swift
1
482
// // Card.swift // DataStructure // // Created by Jigs Sheth on 3/21/16. // Copyright © 2016 jigneshsheth.com. All rights reserved. // import Foundation public class Card { class public func shuffle<T>(input:[T]) -> [T]{ var input:[T] = input let len = input.count for i in 0..<len{ let index = Int(arc4random_uniform((UInt32(len - i)))) let temp = input[i] input[i] = input[index] input[index] = temp } return input } }
mit
fdce6db3d8c6d849d329faaf21d7a209
16.814815
60
0.592516
3.272109
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Foundation/BloomFilter/BitArray.swift
2
3948
// // BitArray.swift // BuildBloomFilteriOS // // Created by Tim Palade on 3/14/17. // Copyright © 2017 Tim Palade. All rights reserved. // import Foundation final class BitArray: NSObject, NSCoding { //Array of bits manipulation typealias wordType = UInt64 private var array: [wordType] = [] init(count:Int) { super.init() self.array = self.buildArray(count: count) } public func valueOfBit(at index:Int) -> Bool{ return self.valueOfBit(in: self.array, at: index) } public func setValueOfBit(value:Bool, at index: Int){ self.setValueOfBit(in: &self.array, at: index, value: value) } public func count() -> Int{ return self.array.count * intSize - 1 } //Archieve/Unarchive func archived() -> Data { return NSKeyedArchiver.archivedData(withRootObject: self) } class func unarchived(fromData data: Data) -> BitArray? { return NSKeyedUnarchiver.unarchiveObject(with: data) as? BitArray } //NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(self.array, forKey:"internalBitArray") } init?(coder aDecoder: NSCoder) { super.init() let array:[wordType] = aDecoder.decodeObject(forKey:"internalBitArray") as? [wordType] ?? [] self.array = array } //Private API private func valueOfBit(in array:[wordType], at index:Int) -> Bool{ checkIndexBound(index: index, lowerBound: 0, upperBound: array.count * intSize - 1) let (_arrayIndex, _bitIndex) = bitIndex(at:index) let bit = array[_arrayIndex] return valueOf(bit: bit, atIndex: _bitIndex) } private func setValueOfBit(in array: inout[wordType], at index:Int, value: Bool){ checkIndexBound(index: index, lowerBound: 0, upperBound: array.count * intSize - 1) let (_arrayIndex, _bitIndex) = bitIndex(at:index) let bit = array[_arrayIndex] let newBit = setValueFor(bit: bit, value: value, atIndex: _bitIndex) array[_arrayIndex] = newBit } //Constants private let intSize = MemoryLayout<wordType>.size * 8 //bit masks func invertedIndex(index:Int) -> Int{ return intSize - 1 - index } func mask(index:Int) -> wordType { checkIndexBound(index: index, lowerBound: 0, upperBound: intSize - 1) return 1 << wordType(invertedIndex(index: index)) } func negative(index:Int) -> wordType { checkIndexBound(index: index, lowerBound: 0, upperBound: intSize - 1) return ~(1 << wordType(invertedIndex(index: index))) } //return (arrayIndex for word containing the bit, bitIndex inside the word) private func bitIndex(at index:Int) -> (Int,Int){ return(index / intSize, index % intSize) } private func buildArray(count:Int) -> [wordType] { //words contain intSize bits each let numWords = count/intSize + 1 return Array.init(repeating: wordType(0), count: numWords) } //Bit manipulation private func valueOf(bit: wordType, atIndex index:Int) -> Bool { checkIndexBound(index: index, lowerBound: 0, upperBound: intSize - 1) return (bit & mask(index: index) != 0) } private func setValueFor(bit: wordType, value: Bool,atIndex index: Int) -> wordType{ checkIndexBound(index: index, lowerBound: 0, upperBound: intSize - 1) if value { return (bit | mask(index: index)) } return bit & negative(index: index) } //Util private func checkIndexBound(index:Int, lowerBound:Int, upperBound:Int){ if(index < lowerBound || index > upperBound) { NSException.init(name: NSExceptionName(rawValue: "BitArray Exception"), reason: "index out of bounds", userInfo: nil).raise() } } }
mpl-2.0
21cc8635d03cd9c4a27492d00ac36a8c
30.325397
137
0.616164
4.039918
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Views/InviteButton.swift
1
1269
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireCommonComponents final class InviteButton: IconButton { init(variant: ColorSchemeVariant = ColorScheme.default.variant) { super.init() clipsToBounds = true titleLabel?.font = FontSpec.normalSemiboldFont.font! applyStyle(.secondaryTextButtonStyle) layer.cornerRadius = 12 contentEdgeInsets = UIEdgeInsets(top: 4, left: 16, bottom: 4, right: 16) } override var isHighlighted: Bool { didSet { applyStyle(.secondaryTextButtonStyle) } } }
gpl-3.0
5d895940f28cc1efad106a71646949a4
31.538462
80
0.70922
4.597826
false
false
false
false
gregomni/swift
test/StringProcessing/Sema/regex_literal_type_inference.swift
3
1901
// RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking // REQUIRES: swift_in_compiler let r0 = #/./# let _: Regex<Substring> = r0 func takesRegex<Output>(_: Regex<Output>) {} takesRegex(#//#) // okay let r1 = #/.(.)/# // Note: We test its type with a separate statement so that we know the type // checker inferred the regex's type independently without contextual types. let _: Regex<(Substring, Substring)>.Type = type(of: r1) struct S {} // expected-error @+2 {{cannot assign value of type 'Regex<(Substring, Substring)>' to type 'Regex<S>'}} // expected-note @+1 {{arguments to generic parameter 'Output' ('(Substring, Substring)' and 'S') are expected to be equal}} let r2: Regex<S> = #/.(.)/# let r3 = #/(.)(.)/# let _: Regex<(Substring, Substring, Substring)>.Type = type(of: r3) let r4 = #/(?<label>.)(.)/# let _: Regex<(Substring, label: Substring, Substring)>.Type = type(of: r4) let r5 = #/(.(.(.)))/# let _: Regex<(Substring, Substring, Substring, Substring)>.Type = type(of: r5) let r6 = #/(?'we'.(?'are'.(?'regex'.)+)?)/# let _: Regex<(Substring, we: Substring, are: Substring?, regex: Substring?)>.Type = type(of: r6) let r7 = #/(?:(?:(.(.(.)*)?))*?)?/# // ^ 1 // ^ 2 // ^ 3 let _: Regex<(Substring, Substring??, Substring???, Substring????)>.Type = type(of: r7) let r8 = #/well(?<theres_no_single_element_tuple_what_can_we>do)/# let _: Regex<(Substring, theres_no_single_element_tuple_what_can_we: Substring)>.Type = type(of: r8) let r9 = #/(a)|(b)|(c)|d/# let _: Regex<(Substring, Substring?, Substring?, Substring?)>.Type = type(of: r9) let r10 = #/(a)|b/# let _: Regex<(Substring, Substring?)>.Type = type(of: r10) let r11 = #/()()()()()()()()/# let _: Regex<(Substring, Substring, Substring, Substring, Substring, Substring, Substring, Substring, Substring)>.Type = type(of: r11)
apache-2.0
cb328b9c1b777cd09f70364d14af6c19
38.604167
134
0.61494
3.244027
false
false
false
false
odemolliens/blockchain-ios-sdk
SDK_SWIFT/ODBlockChainWallet/ODBlockChainWallet/Domain/ODWallet.swift
1
2252
// //Copyright 2014 Olivier Demolliens - @odemolliens // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this // //file except in compliance with the License. You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under // //the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF // //ANY KIND, either express or implied. See the License for the specific language governing // //permissions and limitations under the License. // // import Foundation class ODWallet: NSObject { // MARK: Domain var guid : NSString; var address : NSString; var link : NSString; // MARK: Constructor override init() { self.guid = ""; self.address = ""; self.link = ""; } // MARK: Static Methods class func instantiateWithDictionnary(dic:NSDictionary) -> ODWallet { var createWallet : ODWallet = ODWallet(); createWallet.guid = dic.valueForKey("guid") as NSString!; createWallet.address = dic.valueForKey("address") as NSString!; createWallet.link = dic.valueForKey("link") as NSString!; return createWallet; } class func parseErrorResponseFromAPI(response:NSString) -> ODBCErrorAPI { if(response.isEqualToString(kBCWalletPasswordLength)){ return ODBCErrorAPI.PasswordLength; }else if(response.isEqualToString(kBCWalletApiKey)){ return ODBCErrorAPI.ApiKey; }else if(response.isEqualToString(kBCWalletEmail)){ return ODBCErrorAPI.Email; }else if(response.isEqualToString(kBCWalletAlphaNumeric)){ return ODBCErrorAPI.AlphaNumericOnly; }else if(response.isEqualToString(kBCWalletInvalidAdress) || response.isEqualToString(kBCWalletInvalidAdress2)){ return ODBCErrorAPI.Invalid; }else if(response.isEqualToString(kBCCommonNull) || response.isEqualToString(kBCCommonCloudFare)){ return ODBCErrorAPI.ApiUnavailable; }else{ return ODBCErrorAPI.Unknow; } } // MARK: Methods }
apache-2.0
fd3f431a67071c1b8aa29f9b444ae8d0
29.849315
120
0.667851
4.459406
false
false
false
false
zullevig/ZAStyles
ZAStyles/UIColor+ZAStyles.swift
1
1365
// // UIColor+ZAStyles.swift // ZAStyles // // Created by Zachary Ullevig on 7/11/15. // Copyright (c) 2015 Zachary Ullevig. All rights reserved. // import UIKit public typealias HexColor = UInt32 public let ZASSystemBlueHexColor:HexColor = 0x004080 public extension HexColor { func applyAlpha(alphaPercentage:Float) -> HexColor { // get hex value for given percent of a 255 opaque alpha let alpha:HexColor = HexColor(0xFF * alphaPercentage) // replace the existing alpha value with the newly computed alpha value let newHexColor:HexColor = HexColor(self & 0x00FFFFFF + ((alpha << 24) & 0xFF000000)) // return our resulting MCHexColor return newHexColor } } public extension UIColor { /** Initializes a new UIColor object directly from the hex colors provided by EUI :param: hexColor A hex code color definition of 8 characters, 2 each representing in order the Alpha, Red, Green, and Blue color components :returns: UIColor object */ convenience init(hexColor:HexColor) { let red:CGFloat = CGFloat((hexColor >> 16) & 0xff) / 255 let green:CGFloat = CGFloat((hexColor >> 8) & 0xff) / 255 let blue:CGFloat = CGFloat(hexColor & 0xff) / 255 let alpha:CGFloat = CGFloat((hexColor >> 24) & 0xff) / 255 self.init(red:red, green:green, blue:blue, alpha: alpha) } }
mit
2a8d353c3e6f4abf4b45eff264f62053
29.333333
141
0.692308
3.729508
false
false
false
false
PaulWoodIII/tipski
EmojiJSON/Sources/EmojiJSONTranslator.swift
1
2121
import Foundation class Emoji { var title : String var keywords : [String] var char : String var category : String var fts : String init(title incTitle: String, dictionary : [String: Any]){ title = incTitle keywords = dictionary["keywords"] as! [String] char = dictionary["char"] as! String category = dictionary["category"] as! String var composing = keywords.joined(separator: "|") composing = title + composing composing = char + composing composing = category + composing fts = composing } static let allEmojis : [Emoji] = { // let url = Bundle.main.url(forResource: "emojis", withExtension: "json") // let data = try! Data(contentsOf: url!) // let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) // let emojiDict = json as! [String: Any] let emojiDict = Emojis().values var emojis = [Emoji]() for key in emojiDict.keys { let dict = emojiDict[key] as! [String:Any] let e = Emoji(title: key, dictionary:dict) emojis.append(e) } return emojis }() static let json : String = { let emojiDicts = Emoji.allEmojis.map({ (e) -> [String:Any] in return e.dictionary }) let kVal = ["emoji":emojiDicts] let data = try! JSONSerialization.data(withJSONObject: kVal, options: .prettyPrinted) return String(data: data, encoding: .utf8)! }() var dictionary : [String:Any] { get { return ["t":title, "k":keywords, "c":char, "x":category] } } } extension Emoji : CustomStringConvertible { public var description: String { get { return "\(title): \(char)" } } } extension String { public var isEmoji : Bool { get { return Emoji.allEmojis.contains(where: { (e) -> Bool in return e.char == self }) } } }
mit
28594a909a2ea74f2fd03e08cc80a2fe
26.545455
93
0.538425
4.382231
false
false
false
false
LacieJiang/Custom-2048
Custom-2048/Custom-2048/Models/MoveOrder.swift
1
1263
// // MoveOrder.swift // Custom-2048 // // Created by liyinjiang on 6/17/14. // Copyright (c) 2014 liyinjiang. All rights reserved. // import UIKit class MoveOrder: NSObject { var source1: NSInteger = 0 var source2: NSInteger = 0 var destination: NSInteger = 0 var doubleMove: Bool = false var value: NSInteger = 0 class func singleMoveOrderWithSource(source:NSInteger, destination:NSInteger, newValue:NSInteger) -> MoveOrder { var order = MoveOrder() order.doubleMove = false order.source1 = source order.destination = destination order.value = newValue return order } class func doubleMoveOrderWithFirstSource(source:NSInteger, secondSource:NSInteger, destination:NSInteger, newValue:NSInteger) -> MoveOrder { var order: MoveOrder = MoveOrder() order.doubleMove = true order.source1 = source order.source2 = secondSource order.destination = destination order.value = newValue return order } func description() -> String { if (self.doubleMove) { return "MoveOrder (double, source1: \(source1), source2: \(source2), destination: \(destination), value:\(value))" } return "MoveOrder (single, source: \(source1), destination: \(destination), value: \(value))" } }
bsd-2-clause
d5c815544504cd551f41835fe3d6863f
28.372093
143
0.698337
4.035144
false
false
false
false
MessageKit/MessageKit
Example/Sources/AppDelegate.swift
1
2082
// MIT License // // Copyright (c) 2017-2019 MessageKit // // 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 @UIApplicationMain final internal class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let masterViewController = UINavigationController(rootViewController: LaunchViewController()) let splitViewController = UISplitViewController() splitViewController.viewControllers = UIDevice.current.userInterfaceIdiom == .pad ? [ masterViewController, UIViewController() ] : [masterViewController] splitViewController.preferredDisplayMode = .allVisible window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = splitViewController window?.makeKeyAndVisible() if UserDefaults.isFirstLaunch() { // Enable Text Messages UserDefaults.standard.set(true, forKey: "Text Messages") } return true } }
mit
c3b512319189e453f406977f5a7c0d8d
39.823529
119
0.752642
5.166253
false
false
false
false
OpenStreetMap-Monitoring/OsMoiOs
iOsmo/Extensions.swift
2
8116
// // Extensions.swift // iOsmo // // Created by Olga Grineva on 28/05/15. // Copyright (c) 2015 Olga Grineva. All rights reserved. // import Foundation extension URL{ func queryParams() -> [String:Any] { var info : [String:Any] = [String:Any]() if let queryString = self.query{ for parameter in queryString.components(separatedBy: "&"){ let parts = parameter.components(separatedBy: "=") if parts.count > 1{ let key = (parts[0] as NSString).removingPercentEncoding let value = (parts[1] as NSString).removingPercentEncoding if key != nil && value != nil{ info[key!] = value } } } } return info } } extension UIView { func roundCorners(_ corners:UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } } extension String { var hexColor: UIColor { let hex = trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt64() Scanner(string: hex).scanHexInt64(&int) let a, r, g, b: UInt64 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: return .clear } return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } } public extension UIDevice { /// pares the deveice name as the standard name var modelName: String { #if targetEnvironment(simulator) let identifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"]! #else var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } #endif switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" default: return identifier } } } extension UIViewController { func setupViewResizerOnKeyboardShown() { NotificationCenter.default.addObserver(self, selector: #selector(UIViewController.keyboardWillShowForResizing), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(UIViewController.keyboardWillHideForResizing), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShowForResizing(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let window = self.view.window?.frame { // We're not just minusing the kb height from the view height because // the view could already have been resized for the keyboard before self.view.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: window.origin.y + window.height - keyboardSize.height) } else { debugPrint("We're showing the keyboard and either the keyboard size or window is nil: panic widely.") } } @objc func keyboardWillHideForResizing(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let viewHeight = self.view.frame.height self.view.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: viewHeight + keyboardSize.height) } else { debugPrint("We're about to hide the keyboard and the keyboard size is nil. Now is the rapture.") } } }
gpl-3.0
be2800b4d5ab052c847469ffd43dd550
48.187879
137
0.502464
4.298729
false
false
false
false
douShu/weiboInSwift
weiboInSwift/weiboInSwift/Classes/Module/Home(首页)/StatusCell/StatusCell.swift
1
5399
// // StatusCell.swift // weiboInSwift // // Created by 逗叔 on 15/9/11. // Copyright © 2015年 逗叔. All rights reserved. // import UIKit let cellSubviewMargin: CGFloat = 8.0 /// 点击链接的协议 protocol StatusCellDelegate: NSObjectProtocol { func statusCellDidSelectedLinkText(text: String) } /// cell的标识符 enum StatusCellID: String { case NormalCell = "NormalCell" case RetweetCell = "RetweetCell" // 静态函数 static func cellID(status: Status) -> String { return status.retweeted_status == nil ? StatusCellID.NormalCell.rawValue : StatusCellID.RetweetCell.rawValue } } class StatusCell: UITableViewCell { // MARK: - ----------------------------- 属性 ----------------------------- /// 链接代理 var statusDelegate: StatusCellDelegate? /// 数据 var status: Status? { didSet { // 给topview传递模型 topView.status = status // 给内容文字赋值 contentLabel.attributedText = EmoticonPackage.emoticonText(status!.text!, font: contentLabel.font) // 给配图传模型 pictureView.status = status pictureViewHeightCons?.constant = pictureView.bounds.height pictureViewWidthCons?.constant = pictureView.bounds.width pictureViewTopCons?.constant = (pictureView.bounds.height == 0 ? 0 : cellSubviewMargin) pictureView.reloadData() } } // MARK: - ----------------------------- 设置cell高度 ----------------------------- func rowHeight(status: Status) -> CGFloat { self.status = status // 强行更新frame layoutIfNeeded() return CGRectGetMaxY(bottomView.frame) } // MARK: - ----------------------------- 构造方法 ----------------------------- override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubview() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - ----------------------------- 设置cell上的控件 ----------------------------- private func setupSubview() { contentView.addSubview(topView) contentView.addSubview(contentLabel) contentView.addSubview(pictureView) contentView.addSubview(bottomView) // 顶部视图 topView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 53)) // 内容标签 contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: cellSubviewMargin)) // contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: -2 * cellSubviewMargin)) // 配图 // let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: cellSubviewMargin)) // pictureViewHeightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height) // pictureViewWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width) // pictureViewTopCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top) // 底部视图 bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: -cellSubviewMargin, y: cellSubviewMargin)) // 底部约束 // contentView.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)) } // MARK: - ----------------------------- 懒加载控件 ----------------------------- lazy var topView: TopView = TopView() lazy var contentLabel: FFLabel = { let l = FFLabel(textLabelColor: UIColor.darkGrayColor(), fontSize: 15) // 设置下面属性, 避免label换行不准 l.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2 * cellSubviewMargin l.numberOfLines = 0 l.sizeToFit() /// 设置label的代理 l.labelDelegate = self return l }() lazy var bottomView: BottomView = BottomView() lazy var pictureView: PictureView = PictureView() // 图片视图的宽高约束 var pictureViewWidthCons: NSLayoutConstraint? var pictureViewHeightCons: NSLayoutConstraint? var pictureViewTopCons: NSLayoutConstraint? } extension StatusCell: FFLabelDelegate { func labelDidSelectedLinkText(label: FFLabel, text: String) { if text.hasPrefix("http://") { self.statusDelegate?.statusCellDidSelectedLinkText(text) } } }
mit
12c8da9383d7c159bfbf689be129a4a5
32.803922
254
0.609629
4.987464
false
false
false
false
willpowell8/JIRAMobileKit
JIRAMobileKit/Classes/ViewControllers/JIRALoginViewController.swift
1
3936
// // JIRALoginViewController.swift // Pods // // Created by Will Powell on 30/08/2017. // // import UIKit import MBProgressHUD protocol JIRALoginViewControllerDelegate { func loginDismissed() func loginOK() } class JIRALoginViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var usernameField:UITextField! @IBOutlet weak var passwordField:UITextField! @IBOutlet weak var hostLabel:UILabel! @IBOutlet weak var projectLabel:UILabel! var delegate:JIRALoginViewControllerDelegate? var onLoginCompletionBlock:(()->Void)? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "JIRA Login" hostLabel.text = JIRA.shared.host projectLabel.text = JIRA.shared.project let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(close)) self.navigationItem.leftBarButtonItem = cancelButton // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) usernameField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func close(){ usernameField.resignFirstResponder() passwordField.resignFirstResponder() delegate?.loginDismissed() dismiss(animated: true, completion: nil) } @IBAction func login(){ guard let username = usernameField.text, !username.isEmpty else { let alert = UIAlertController(title: "Missing Username", message: "Username cannot be blank", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in self.usernameField.becomeFirstResponder() }) present(alert, animated: true, completion: nil) return } guard let password = passwordField.text, !password.isEmpty else { let alert = UIAlertController(title: "Missing Password", message: "Password cannot be blank", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in self.passwordField.becomeFirstResponder() }) present(alert, animated: true, completion: nil) return } usernameField.resignFirstResponder() passwordField.resignFirstResponder() let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = .indeterminate hud.label.text = "Logging in ..." JIRA.shared.login(username: username, password: password) { (valid, error) in DispatchQueue.main.async { hud.hide(animated: true) guard valid == true else { self.loginFailure(error) return } self.dismiss(animated: true, completion: { if let completion = self.onLoginCompletionBlock { completion() } self.delegate?.loginOK() }) } } } func loginFailure(_ error:String?){ let errorStr = error ?? "Unknown error occured" let alert = UIAlertController(title: "Login Failure", message: errorStr, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Try Again", style: .default) { action in }) present(alert, animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == usernameField { passwordField.becomeFirstResponder() }else if textField == passwordField { login() } return true } }
mit
4af9aa6764b131e029d20cd9e5a445ad
34.142857
129
0.618394
5.34057
false
false
false
false
bgerstle/wikipedia-ios
Wikipedia/Code/WelcomeLanguagesAnimationView.swift
1
5075
import Foundation public class WelcomeLanguagesAnimationView : WelcomeAnimationView { lazy var bubbleLeftImgView: UIImageView = { let imgView = UIImageView(frame: self.bounds) imgView.image = UIImage(named: "ftux-left-bubble") imgView.contentMode = UIViewContentMode.ScaleAspectFit imgView.layer.zPosition = 102 imgView.layer.opacity = 0 imgView.layer.transform = self.wmf_scaleZeroAndLowerLeftTransform return imgView }() lazy var bubbleRightImgView: UIImageView = { let imgView = UIImageView(frame: self.bounds) imgView.image = UIImage(named: "ftux-right-bubble") imgView.contentMode = UIViewContentMode.ScaleAspectFit imgView.layer.zPosition = 101 imgView.layer.opacity = 0 imgView.layer.transform = self.wmf_scaleZeroAndLowerRightTransform return imgView }() lazy var dashedCircle: WelcomeCircleShapeLayer = { return WelcomeCircleShapeLayer( unitRadius: 0.31, unitOrigin: CGPointMake(0.508, 0.518), referenceSize: self.frame.size, isDashed: true, transform: self.wmf_scaleZeroTransform, opacity:0.0 ) }() lazy var solidCircle: WelcomeCircleShapeLayer = { return WelcomeCircleShapeLayer( unitRadius: 0.31, unitOrigin: CGPointMake(0.39, 0.5), referenceSize: self.frame.size, isDashed: false, transform: self.wmf_scaleZeroTransform, opacity:0.0 ) }() lazy var plus1: WelcomePlusShapeLayer = { return WelcomePlusShapeLayer( unitOrigin: CGPointMake(0.825, 0.225), unitWidth: 0.05, referenceSize: self.frame.size, transform: self.wmf_scaleZeroTransform, opacity: 0.0 ) }() lazy var plus2: WelcomePlusShapeLayer = { return WelcomePlusShapeLayer( unitOrigin: CGPointMake(0.755, 0.17), unitWidth: 0.05, referenceSize: self.frame.size, transform: self.wmf_scaleZeroTransform, opacity: 0.0 ) }() lazy var plus3: WelcomePlusShapeLayer = { return WelcomePlusShapeLayer( unitOrigin: CGPointMake(0.112, 0.353), unitWidth: 0.05, referenceSize: self.frame.size, transform: self.wmf_scaleZeroTransform, opacity: 0.0 ) }() lazy var line1: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.845, 0.865), unitWidth: 0.135, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndLeftTransform, opacity: 0.0 ) }() lazy var line2: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.255, 0.162), unitWidth: 0.135, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndLeftTransform, opacity: 0.0 ) }() lazy var line3: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.205, 0.127), unitWidth: 0.135, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndLeftTransform, opacity: 0.0 ) }() override public func didMoveToSuperview() { super.didMoveToSuperview() self.addSubview(self.bubbleLeftImgView) self.addSubview(self.bubbleRightImgView) _ = [ self.solidCircle, self.dashedCircle, self.plus1, self.plus2, self.plus3, self.line1, self.line2, self.line3 ].map({ (layer: CALayer) -> () in self.layer.addSublayer(layer) }) } public func beginAnimations() { CATransaction.begin() bubbleLeftImgView.layer.wmf_animateToOpacity(1.0, transform: CATransform3DIdentity, delay: 0.1, duration: 1.0 ) bubbleRightImgView.layer.wmf_animateToOpacity(1.0, transform: CATransform3DIdentity, delay: 0.3, duration: 1.0 ) self.solidCircle.wmf_animateToOpacity(0.04, transform: CATransform3DIdentity, delay: 0.3, duration: 1.0 ) let animate = { (layer: CALayer) -> () in layer.wmf_animateToOpacity(0.15, transform: CATransform3DIdentity, delay: 0.3, duration: 1.0 ) } _ = [ self.dashedCircle, self.plus1, self.plus2, self.plus3, self.line1, self.line2, self.line3 ].map(animate) CATransaction.commit() } }
mit
b5cb988f2cee8a406dc21d0a85c06b09
29.208333
74
0.55468
4.62204
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/Components/PXComponentView.swift
1
8043
import Foundation @objcMembers class PXComponentView: UIView { private var topGuideView = UIView() private var bottomGuideView = UIView() private var contentView = UIView() private lazy var carryMarginY: CGFloat = 0 var heightConstraint: NSLayoutConstraint? var matchGuidesHeightContraint: NSLayoutConstraint? var topGuideZeroHeightContraint: NSLayoutConstraint? var bottomGuideZeroHeightContraint: NSLayoutConstraint? init() { super.init(frame: CGRect.zero) initComponent() } func initComponent() { self.translatesAutoresizingMaskIntoConstraints = false topGuideView.translatesAutoresizingMaskIntoConstraints = false bottomGuideView.translatesAutoresizingMaskIntoConstraints = false contentView.translatesAutoresizingMaskIntoConstraints = false super.addSubview(topGuideView) super.addSubview(bottomGuideView) super.addSubview(contentView) PXLayout.pinTop(view: topGuideView).isActive = true PXLayout.pinBottom(view: bottomGuideView).isActive = true matchGuidesHeightContraint = PXLayout.matchHeight(ofView: topGuideView, toView: bottomGuideView) matchGuidesHeightContraint?.isActive = true topGuideZeroHeightContraint = PXLayout.setHeight(owner: topGuideView, height: 0) topGuideZeroHeightContraint?.isActive = false bottomGuideZeroHeightContraint = PXLayout.setHeight(owner: bottomGuideView, height: 0) bottomGuideZeroHeightContraint?.isActive = false PXLayout.centerHorizontally(view: contentView).isActive = true PXLayout.centerHorizontally(view: topGuideView).isActive = true PXLayout.centerHorizontally(view: bottomGuideView).isActive = true PXLayout.put(view: contentView, onBottomOf: topGuideView).isActive = true PXLayout.put(view: contentView, aboveOf: bottomGuideView).isActive = true PXLayout.matchWidth(ofView: contentView).isActive = true PXLayout.matchWidth(ofView: topGuideView).isActive = true PXLayout.matchWidth(ofView: bottomGuideView).isActive = true carryMarginY = 0 } public func pinContentViewToTop(margin: CGFloat = 0) { topGuideZeroHeightContraint?.isActive = true topGuideZeroHeightContraint?.constant = margin bottomGuideZeroHeightContraint?.isActive = false matchGuidesHeightContraint?.isActive = false } public func pinContentViewToBottom(margin: CGFloat = 0) { topGuideZeroHeightContraint?.isActive = false bottomGuideZeroHeightContraint?.isActive = true bottomGuideZeroHeightContraint?.constant = margin matchGuidesHeightContraint?.isActive = false } public func centerContentViewVertically() { topGuideZeroHeightContraint?.isActive = false bottomGuideZeroHeightContraint?.isActive = false matchGuidesHeightContraint?.isActive = true } public func removeMargins() { topGuideZeroHeightContraint?.isActive = true bottomGuideZeroHeightContraint?.isActive = true matchGuidesHeightContraint?.isActive = false } func fixHeight(height: CGFloat) { if let heightConstraint = self.heightConstraint { heightConstraint.constant = height } else { self.heightConstraint = PXLayout.setHeight(owner: self, height: height) self.heightConstraint?.isActive = true } self.layoutIfNeeded() } func prepareForRender() { for view in self.subviews { view.removeFromSuperview() } for constraint in self.constraints { constraint.isActive = false } initComponent() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func removeAllSubviews(except views: [UIView] = []) { for view in contentView.subviews { if !views.contains(view) { view.removeFromSuperview() } } carryMarginY = 0 } override public func addSubview(_ view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) } override func bringSubviewToFront(_ view: UIView) { self.contentView.bringSubviewToFront(view) } override func sendSubviewToBack(_ view: UIView) { self.contentView.sendSubviewToBack(view) } func addSubviewToComponentView(_ view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false super.addSubview(view) } public func addSubviewToBottom(_ view: UIView, withMargin margin: CGFloat = 0) { view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) if self.contentView.subviews.count == 1 { PXLayout.pinTop(view: view, withMargin: margin).isActive = true } else { putOnBottomOfLastView(view: view, withMargin: margin)?.isActive = true } carryMarginY += margin } override func addSeparatorLineToTop(height: CGFloat, horizontalMarginPercentage: CGFloat, color: UIColor = .pxMediumLightGray) { self.topGuideView.addSeparatorLineToTop(height: height, horizontalMarginPercentage: horizontalMarginPercentage, color: color) } override func addSeparatorLineToBottom(height: CGFloat, horizontalMarginPercentage: CGFloat, color: UIColor = .pxMediumLightGray) { self.bottomGuideView.addSeparatorLineToBottom(height: height, horizontalMarginPercentage: horizontalMarginPercentage, color: color) } override func addLine(yCoordinate: CGFloat, height: CGFloat, horizontalMarginPercentage: CGFloat, color: UIColor) { super.addLine(yCoordinate: yCoordinate, height: height, horizontalMarginPercentage: horizontalMarginPercentage, color: color) } // Pin first content view subview to top @discardableResult public func pinFirstSubviewToTop(withMargin margin: CGFloat = 0 ) -> NSLayoutConstraint? { guard let firstView = self.contentView.subviews.first else { return nil } carryMarginY += margin return PXLayout.pinTop(view: firstView, to: self.contentView, withMargin: margin) } // Pin last content view subview to bottom @discardableResult public func pinLastSubviewToBottom(withMargin margin: CGFloat = 0 ) -> NSLayoutConstraint? { guard let lastView = self.contentView.subviews.last else { return nil } carryMarginY += margin return PXLayout.pinBottom(view: lastView, to: self.contentView, withMargin: margin) } // Put view on bottom of content view last subview @discardableResult public func putOnBottomOfLastView(view: UIView, withMargin margin: CGFloat = 0) -> NSLayoutConstraint? { if !self.contentView.subviews.contains(view) { return nil } carryMarginY += margin for actualView in self.contentView.subviews.reversed() where actualView != view { return PXLayout.put(view: view, onBottomOf: actualView, withMargin: margin) } return nil } func getSubviews() -> [UIView] { return self.contentView.subviews } func getCarryMarginY() -> CGFloat { return carryMarginY } func isEmpty() -> Bool { return self.contentView.subviews.count == 0 } func getContentView() -> UIView { return contentView } func setBackground(color: UIColor?) { backgroundColor = color contentView.backgroundColor = color topGuideView.backgroundColor = color bottomGuideView.backgroundColor = color } } extension CALayer { func pxShadow(radius: CGFloat = 3, shadowOpacity: Float = 0.25) { self.shadowOffset = CGSize.zero self.shadowColor = UIColor.black.cgColor self.shadowRadius = radius self.shadowOpacity = shadowOpacity } }
mit
b6a1a3942434a4532f64f408701dc0b3
36.760563
139
0.692403
5.189032
false
false
false
false
fireflyexperience/SwiftStructures
SwiftStructures/SwiftStructures/Source/Factories/LinkedList.swift
1
6862
// // SwiftFactory.swift // SwiftStructures // // Created by Wayne Bishop on 6/7/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation public class LinkedList<T: Equatable> { //create a new LLNode instance private var head: LLNode<T> = LLNode<T>() public init() { } //the number of items public var count: Int { if (head.key == nil) { return 0 } else { var current: LLNode = head var x: Int = 1 //cycle through the list of items while ((current.next) != nil) { current = current.next! x++ } return x } } //empty list check public func isEmpty() ->Bool! { //check for nil conditions if (self.count == 0 || head.key == nil) { return true } else { return false } } //append a new item to a linked list public func addLink(key: T) { //establish the head node if (head.key == nil) { head.key = key return } //establish the iteration variables var current: LLNode? = head while (current != nil) { if (current?.next == nil) { var childToUse: LLNode = LLNode<T>() childToUse.key = key childToUse.previous = current current!.next = childToUse break } else { current = current?.next } } //end while } //print all keys for the class public func printAllKeys() { var current: LLNode! = head println("------------------") //assign the next instance while (current != nil) { println("link item is: \(current.key)") current = current.next } } //MARK: Key & index operations //obtain link at a specific index public func linkAtIndex(index: Int) ->LLNode<T>! { //check for nil conditions if ((index < 0) || (index > (self.count - 1)) || (head.key == nil)) { return nil } else { var current: LLNode<T>! = head var x: Int = 0 //cycle through the list of items while (index != x) { current = current.next x++ } return current } //end else } //end function //insert at specific index public func addLinkAtIndex(key: T, index: Int) { //check for nil conditions if ((index < 0) || (index > (self.count - 1))) { println("link index does not exist..") } //establish the head node if (head.key == nil) { head.key = key return } //establish the trailer, current and new items var current: LLNode<T>? = head var trailer: LLNode<T>? var listIndex: Int = 0 //iterate through the list to find the insertion point while (current != nil) { if (index == listIndex) { var childToUse: LLNode = LLNode<T>() //create the new node childToUse.key = key //connect the node infront of the current node childToUse.next = current childToUse.previous = trailer //use optional binding when using the trailer if let linktrailer = trailer { linktrailer.next = childToUse childToUse.previous = linktrailer } //point new node to the current / previous current!.previous = childToUse //replace the head node if required if (index == 0) { head = childToUse } break } //end if //iterate through to the next item trailer = current current = current?.next listIndex += 1 } //end while } //remove at specific index public func removeLinkAtIndex(index: Int) { //check for nil conditions if ((index < 0) || (index > (self.count - 1)) || (head.key == nil)) { println("link index does not exist..") return } var current: LLNode<T>? = head var trailer: LLNode<T>? var listIndex: Int = 0 //determine if the removal is at the head if (index == 0) { current = current?.next head = current! return } //iterate through the remaining items while (current != nil) { if (listIndex == index) { //redirect the trailer and next pointers trailer!.next = current?.next current = nil break } //update the assignments trailer = current current = current?.next listIndex++ } //end while } //end function //reverse the order of a linked list public func reverseLinkedList() { //if count == 1 or count == 0,no need to reverse if self.count <= 1{ return } var current : LLNode<T>? = head var next : LLNode<T>? = nil while(current != nil) { //reverse next = current!.next current!.next = current!.previous current!.previous = next if next == nil { head = current! } //move to next node current = next }//end while }//end function } //end class
mit
bfc54e77e2c753ffb089e2993e45bfc3
20.923323
77
0.403235
5.795608
false
false
false
false
ianthetechie/SwiftCGI-Demo
SwiftCGI Demo/Root.swift
1
808
// // Root.swift // SwiftCGI Demo // // Created by Ian Wagner on 3/16/15. // Copyright (c) 2015 Ian Wagner. All rights reserved. // import Foundation import SwiftCGI let rootHandler: RequestHandler = { request in var extraGreeting = "" if let sessionManager = request.getSessionManager() as RequestSessionManager<TransientMemorySessionManager>? { var sessionData: SessionData = sessionManager.getData() ?? [:] if sessionData["visited"] == "true" { extraGreeting = " again" } else { sessionData["visited"] = "true" } sessionManager.setData(sessionData) } return HTTPResponse(status: .OK, contentType: .TextPlain(.UTF8), body: "안녕하세요\(extraGreeting), Swifter! The time is now \(NSDate())") }
bsd-2-clause
be1c71bf36e2d160953889ea0da94c6d
28.592593
137
0.635338
4.26738
false
false
false
false
Nick-The-Uncharted/TagListView
TagListViewDemo/ViewController.swift
1
2639
// // ViewController.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit class ViewController: UIViewController, TagListViewDelegate { @IBOutlet weak var tagListView: TagListView! @IBOutlet weak var biggerTagListView: TagListView! @IBOutlet weak var biggestTagListView: TagListView! override func viewDidLoad() { super.viewDidLoad() tagListView.delegate = self tagListView.addTag("TagListView") tagListView.addTag("TEAChart") tagListView.addTag("To Be Removed") tagListView.addTag("To Be Removed") tagListView.addTag("Quark Shell") tagListView.removeTag("To Be Removed") tagListView.addTag("On tap will be removed").onTap = { [weak self] tagView in self?.tagListView.removeTagView(tagView) } let tagView = tagListView.addTag("gray") tagView.tagBackgroundColor = UIColor.grayColor() tagView.onTap = { tagView in print("Don’t tap me!") } biggerTagListView.delegate = self biggerTagListView.textFont = UIFont.systemFontOfSize(15) biggerTagListView.shadowRadius = 2 biggerTagListView.shadowOpacity = 0.4 biggerTagListView.shadowColor = UIColor.blackColor() biggerTagListView.shadowOffset = CGSizeMake(1, 1) biggerTagListView.addTag("Inboard") biggerTagListView.addTag("Pomotodo") biggerTagListView.addTag("Halo Word") biggerTagListView.alignment = .Center biggestTagListView.delegate = self biggestTagListView.textFont = UIFont.systemFontOfSize(24) biggestTagListView.addTag("all") biggestTagListView.addTag("your") biggestTagListView.addTag("tag") biggestTagListView.addTag("are") biggestTagListView.addTag("belong") biggestTagListView.addTag("to") biggestTagListView.addTag("us") biggestTagListView.alignment = .Right } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: TagListViewDelegate func tagPressed(title: String, tagView: TagView, sender: TagListView) { print("Tag pressed: \(title), \(sender)") tagView.selected = !tagView.selected } func tagRemoveButtonPressed(title: String, tagView: TagView, sender: TagListView) { print("Tag Remove pressed: \(title), \(sender)") sender.removeTagView(tagView) } }
mit
782a932af817375fb65c2000f9433c38
33.246753
87
0.656428
4.507692
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/Settings/HomePageSettingViewController.swift
8
5880
/* 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 class HomePageSettingViewController: SettingsTableViewController { /* variables for checkmark settings */ let prefs: Prefs var currentChoice: NewTabPage! var hasHomePage = false init(prefs: Prefs) { self.prefs = prefs super.init(style: .grouped) self.title = Strings.AppMenuOpenHomePageTitleString } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func generateSettings() -> [SettingSection] { // The Home button and the New Tab page can be set independently self.currentChoice = NewTabAccessors.getHomePage(self.prefs) self.hasHomePage = HomeButtonHomePageAccessors.getHomePage(self.prefs) != nil let onFinished = { self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey) self.tableView.reloadData() } let showTopSites = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabTopSites), subtitle: nil, accessibilityIdentifier: "HomeAsFirefoxHome", isChecked: {return self.currentChoice == NewTabPage.topSites}, onChecked: { self.currentChoice = NewTabPage.topSites onFinished() }) let showWebPage = WebPageSetting(prefs: prefs, prefKey: PrefsKeys.HomeButtonHomePageURL, defaultValue: nil, placeholder: Strings.CustomNewPageURL, accessibilityIdentifier: "HomeAsCustomURL", isChecked: {return !showTopSites.isChecked()}, settingDidChange: { (string) in self.currentChoice = NewTabPage.homePage self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey) self.tableView.reloadData() }) showWebPage.textField.textAlignment = .natural let section = SettingSection(title: NSAttributedString(string: Strings.NewTabSectionName), footerTitle: NSAttributedString(string: Strings.NewTabSectionNameFooter), children: [showTopSites, showWebPage]) let topsitesSection = SettingSection(title: NSAttributedString(string: Strings.SettingsTopSitesCustomizeTitle), footerTitle: NSAttributedString(string: Strings.SettingsTopSitesCustomizeFooter), children: [TopSitesSettings(settings: self)]) let isPocketEnabledDefault = Pocket.IslocaleSupported(Locale.current.identifier) let pocketSetting = BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.ASPocketStoriesVisible, defaultValue: isPocketEnabledDefault, attributedTitleText: NSAttributedString(string: Strings.SettingsNewTabPocket)) let pocketSection = SettingSection(title: NSAttributedString(string: Strings.SettingsNewTabASTitle), footerTitle: NSAttributedString(string: Strings.SettingsNewTabPocketFooter), children: [pocketSetting]) return [section, topsitesSection, pocketSection] } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.post(name: .HomePanelPrefsChanged, object: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.keyboardDismissMode = .onDrag } class TopSitesSettings: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var status: NSAttributedString { let num = self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows return NSAttributedString(string: String(format: Strings.TopSitesRowCount, num)) } override var accessibilityIdentifier: String? { return "TopSitesRows" } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.ASTopSitesTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = TopSitesRowCountSettingsController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } } class TopSitesRowCountSettingsController: SettingsTableViewController { let prefs: Prefs var numberOfRows: Int32 static let defaultNumberOfRows: Int32 = 2 init(prefs: Prefs) { self.prefs = prefs numberOfRows = self.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows super.init(style: .grouped) self.title = Strings.AppMenuTopSitesTitleString } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func generateSettings() -> [SettingSection] { let createSetting: (Int32) -> CheckmarkSetting = { num in return CheckmarkSetting(title: NSAttributedString(string: "\(num)"), subtitle: nil, isChecked: { return num == self.numberOfRows }, onChecked: { self.numberOfRows = num self.prefs.setInt(Int32(num), forKey: PrefsKeys.NumberOfTopSiteRows) self.tableView.reloadData() }) } let rows = [1, 2, 3, 4].map(createSetting) let section = SettingSection(title: NSAttributedString(string: Strings.TopSitesRowSettingFooter), footerTitle: nil, children: rows) return [section] } }
mpl-2.0
da3ad90f9dca03fe3ddd346c6dbf5af2
47.595041
277
0.718537
5.171504
false
false
false
false
ben-ng/swift
stdlib/public/SDK/XPC/XPC.swift
1
2935
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import XPC import _SwiftXPCOverlayShims //===----------------------------------------------------------------------===// // XPC Types //===----------------------------------------------------------------------===// public var XPC_TYPE_CONNECTION: xpc_type_t { return _swift_xpc_type_CONNECTION() } public var XPC_TYPE_ENDPOINT: xpc_type_t { return _swift_xpc_type_ENDPOINT() } public var XPC_TYPE_NULL: xpc_type_t { return _swift_xpc_type_NULL() } public var XPC_TYPE_BOOL: xpc_type_t { return _swift_xpc_type_BOOL() } public var XPC_TYPE_INT64: xpc_type_t { return _swift_xpc_type_INT64() } public var XPC_TYPE_UINT64: xpc_type_t { return _swift_xpc_type_UINT64() } public var XPC_TYPE_DOUBLE: xpc_type_t { return _swift_xpc_type_DOUBLE() } public var XPC_TYPE_DATE: xpc_type_t { return _swift_xpc_type_DATE() } public var XPC_TYPE_DATA: xpc_type_t { return _swift_xpc_type_DATA() } public var XPC_TYPE_STRING: xpc_type_t { return _swift_xpc_type_STRING() } public var XPC_TYPE_UUID: xpc_type_t { return _swift_xpc_type_UUID() } public var XPC_TYPE_FD: xpc_type_t { return _swift_xpc_type_FD() } public var XPC_TYPE_SHMEM: xpc_type_t { return _swift_xpc_type_SHMEM() } public var XPC_TYPE_ARRAY: xpc_type_t { return _swift_xpc_type_ARRAY() } public var XPC_TYPE_DICTIONARY: xpc_type_t { return _swift_xpc_type_DICTIONARY() } public var XPC_TYPE_ERROR: xpc_type_t { return _swift_xpc_type_ERROR() } public var XPC_TYPE_ACTIVITY: xpc_type_t { return _swift_xpc_type_ACTIVITY() } //===----------------------------------------------------------------------===// // Macros //===----------------------------------------------------------------------===// // xpc/xpc.h public let XPC_ERROR_KEY_DESCRIPTION: UnsafePointer<Int8> = _xpc_error_key_description public let XPC_EVENT_KEY_NAME: UnsafePointer<Int8> = _xpc_event_key_name public var XPC_BOOL_TRUE: xpc_object_t { return _swift_xpc_bool_true() } public var XPC_BOOL_FALSE: xpc_object_t { return _swift_xpc_bool_false() } public var XPC_ARRAY_APPEND: size_t { return -1 } // xpc/connection.h public var XPC_ERROR_CONNECTION_INTERRUPTED: xpc_object_t { return _swift_xpc_connection_interrupted() } public var XPC_ERROR_CONNECTION_INVALID: xpc_object_t { return _swift_xpc_connection_invalid() } public var XPC_ERROR_TERMINATION_IMMINENT: xpc_object_t { return _swift_xpc_connection_termination_imminent() }
apache-2.0
8b28ca9a714f1fc5ba2537b20902a004
23.663866
86
0.601022
3.27933
false
false
false
false
adrfer/swift
stdlib/public/SDK/AppKit/NSError.swift
5
1354
public extension NSCocoaError { public static var TextReadInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 65806) } public static var TextWriteInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 66062) } public static var ServiceApplicationNotFoundError: NSCocoaError { return NSCocoaError(rawValue: 66560) } public static var ServiceApplicationLaunchFailedError: NSCocoaError { return NSCocoaError(rawValue: 66561) } public static var ServiceRequestTimedOutError: NSCocoaError { return NSCocoaError(rawValue: 66562) } public static var ServiceInvalidPasteboardDataError: NSCocoaError { return NSCocoaError(rawValue: 66563) } public static var ServiceMalformedServiceDictionaryError: NSCocoaError { return NSCocoaError(rawValue: 66564) } public static var ServiceMiscellaneousError: NSCocoaError { return NSCocoaError(rawValue: 66800) } public static var SharingServiceNotConfiguredError: NSCocoaError { return NSCocoaError(rawValue: 67072) } public var isServiceError: Bool { return rawValue >= 66560 && rawValue <= 66817 } public var isSharingServiceError: Bool { return rawValue >= 67072 && rawValue <= 67327 } public var isTextReadWriteError: Bool { return rawValue >= 65792 && rawValue <= 66303 } }
apache-2.0
9fd8bc6fa2d242008ae7ce87c5d30be5
32.02439
74
0.764402
5.526531
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Views/NTExpandableView.swift
1
4465
// // NTExpandableView.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 7/3/17. // open class NTExpandableView: UIView { open var textLabel: NTLabel = { let label = NTLabel(style: .body) return label }() open var detailTextLabel: NTLabel = { let label = NTLabel(style: .footnote) return label }() open var toggleButton: NTButton = { let button = NTButton() button.backgroundColor = .clear button.rippleOverBounds = true button.trackTouchLocation = false button.ripplePercent = 1.1 button.image = Icon.Arrow.Down button.tintColor = Color.Default.Tint.View return button }() open override var backgroundColor: UIColor? { didSet { toggleButton.backgroundColor = backgroundColor if backgroundColor?.isDark == true { textLabel.textColor = .white detailTextLabel.textColor = UIColor.white.darker(by: 3) } } } fileprivate var isExpanded: Bool = false fileprivate var detailHeightConstraint: NSLayoutConstraint? // MARK: - Initialization convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func setup() { addSubview(textLabel) addSubview(detailTextLabel) addSubview(toggleButton) toggleButton.addTarget(self, action: #selector(handleToggle(_:)), for: .touchUpInside) textLabel.anchor(topAnchor, left: leftAnchor, bottom: detailTextLabel.topAnchor, right: toggleButton.leftAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 2, rightConstant: 2, widthConstant: 0, heightConstant: 20) toggleButton.anchor(topAnchor, left: nil, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 0) toggleButton.anchorHeightToItem(textLabel) toggleButton.anchorAspectRatio() detailHeightConstraint = detailTextLabel.anchorWithReturnAnchors(textLabel.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 2, rightConstant: 8, widthConstant: 0, heightConstant: .leastNonzeroMagnitude).last } // MARK: View Toggle @objc open func handleToggle(_ button: NTButton) { UIView.animate(withDuration: 0.3, animations: { if self.isExpanded { // Close button.imageView?.transform = CGAffineTransform.identity self.detailHeightConstraint?.isActive = true self.superview?.layoutIfNeeded() } else { // Open button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) self.detailHeightConstraint?.isActive = false self.superview?.layoutIfNeeded() } }) { success in if success { self.isExpanded = !self.isExpanded } } } }
mit
1cc28754daeb8e04d5a8546926cd5a2a
37.817391
289
0.65345
4.943522
false
false
false
false
shu223/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/CoordinatedAnimationsInterfaceController.swift
1
1287
// // CoordinatedAnimationsInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/12. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class CoordinatedAnimationsInterfaceController: WKInterfaceController { @IBOutlet weak var progressGroup: WKInterfaceGroup! @IBOutlet weak var picker: WKInterfacePicker! override func awake(withContext context: Any?) { super.awake(withContext: context) // create animated images and picker items var images: [UIImage]! = [] var pickerItems: [WKPickerItem]! = [] for i in 0...36 { let name = "progress-\(i)" images.append(UIImage(named: name)!) let pickerItem = WKPickerItem() pickerItem.title = "\(i)" pickerItems.append(pickerItem) } let progressImages = UIImage.animatedImage(with: images, duration: 0.0) progressGroup.setBackgroundImage(progressImages) picker.setCoordinatedAnimations([progressGroup]) picker.setItems(pickerItems) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } }
mit
c529cfe5df02ebce98e9c35da67e089b
25.244898
79
0.648523
4.871212
false
false
false
false
kusl/swift
stdlib/public/core/String.swift
3
31578
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// An arbitrary Unicode string value. /// /// Unicode-Correct /// =============== /// /// Swift strings are designed to be Unicode-correct. In particular, /// the APIs make it easy to write code that works correctly, and does /// not surprise end-users, regardless of where you venture in the /// Unicode character space. For example, the `==` operator checks /// for [Unicode canonical /// equivalence](http://www.unicode.org/glossary/#deterministic_comparison), /// so two different representations of the same string will always /// compare equal. /// /// Locale-Insensitive /// ================== /// /// The fundamental operations on Swift strings are not sensitive to /// locale settings. That's because, for example, the validity of a /// `Dictionary<String, T>` in a running program depends on a given /// string comparison having a single, stable result. Therefore, /// Swift always uses the default, /// un-[tailored](http://www.unicode.org/glossary/#tailorable) Unicode /// algorithms for basic string operations. /// /// Importing `Foundation` endows swift strings with the full power of /// the `NSString` API, which allows you to choose more complex /// locale-sensitive operations explicitly. /// /// Value Semantics /// =============== /// /// Each string variable, `let` binding, or stored property has an /// independent value, so mutations to the string are not observable /// through its copies: /// /// var a = "foo" /// var b = a /// b.appendContentsOf("bar") /// print("a=\(a), b=\(b)") // a=foo, b=foobar /// /// Strings use Copy-on-Write so that their data is only copied /// lazily, upon mutation, when more than one string instance is using /// the same buffer. Therefore, the first in any sequence of mutating /// operations may cost `O(N)` time and space, where `N` is the length /// of the string's (unspecified) underlying representation. /// /// Views /// ===== /// /// `String` is not itself a collection of anything. Instead, it has /// properties that present the string's contents as meaningful /// collections: /// /// - `characters`: a collection of `Character` ([extended grapheme /// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster)) /// elements, a unit of text that is meaningful to most humans. /// /// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode /// scalar /// values](http://www.unicode.org/glossary/#unicode_scalar_value)) /// the 21-bit codes that are the basic unit of Unicode. These /// values are equivalent to UTF-32 code units. /// /// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit /// elements of the string's UTF-16 encoding. /// /// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit /// elements of the string's UTF-8 encoding. /// /// Growth and Capacity /// =================== /// /// When a string's contiguous storage fills up, new storage must be /// allocated and characters must be moved to the new storage. /// `String` uses an exponential growth strategy that makes `append` a /// constant time operation *when amortized over many invocations*. /// /// Objective-C Bridge /// ================== /// /// `String` is bridged to Objective-C as `NSString`, and a `String` /// that originated in Objective-C may store its characters in an /// `NSString`. Since any arbitrary subclass of `NSString` can /// become a `String`, there are no guarantees about representation or /// efficiency in this case. Since `NSString` is immutable, it is /// just as though the storage was shared by some copy: the first in /// any sequence of mutating operations causes elements to be copied /// into unique, contiguous storage which may cost `O(N)` time and /// space, where `N` is the length of the string representation (or /// more, if the underlying `NSString` has unusual performance /// characteristics). public struct String { /// An empty `String`. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { @warn_unused_result public // @testable static func _fromWellFormedCodeUnitSequence< Encoding: UnicodeCodecType, Input: CollectionType where Input.Generator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> String { return String._fromCodeUnitSequence(encoding, input: input)! } @warn_unused_result public // @testable static func _fromCodeUnitSequence< Encoding: UnicodeCodecType, Input: CollectionType where Input.Generator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> String? { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(encoding, input: input, repairIllFormedSequences: false) if let stringBuffer = stringBufferOptional { return String(_storage: stringBuffer) } else { return .None } } @warn_unused_result public // @testable static func _fromCodeUnitSequenceWithRepair< Encoding: UnicodeCodecType, Input: CollectionType where Input.Generator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(encoding, input: input, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _BuiltinUnicodeScalarLiteralConvertible { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : UnicodeScalarLiteralConvertible { /// Create an instance initialized to `value`. public init(unicodeScalarLiteral value: String) { self = value } } extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(byteSize))) } } extension String : ExtendedGraphemeClusterLiteralConvertible { /// Create an instance initialized to `value`. public init(extendedGraphemeClusterLiteral value: String) { self = value } } extension String : _BuiltinUTF16StringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word ) { self = String( _StringCore( baseAddress: COpaquePointer(start), count: Int(numberOfCodeUnits), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _BuiltinStringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: COpaquePointer(start), count: Int(byteSize), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(byteSize))) } } } extension String : StringLiteralConvertible { /// Create an instance initialized to `value`. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escape(asASCII: false) } result += "\"" return result } } extension String { /// Return the number of code units occupied by this string /// in the given encoding. @warn_unused_result func _encodedLength< Encoding: UnicodeCodecType >(encoding: Encoding.Type) -> Int { var codeUnitCount = 0 let output: (Encoding.CodeUnit) -> Void = { _ in ++codeUnitCount } self._encode(encoding, output: output) return codeUnitCount } // FIXME: this function does not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode< Encoding: UnicodeCodecType >(encoding: Encoding.Type, output: (Encoding.CodeUnit) -> Void) { return _core.encode(encoding, output: output) } } #if _runtime(_ObjC) /// Compare two strings using the Unicode collation algorithm in the /// deterministic comparison mode. (The strings which are equivalent according /// to their NFD form are considered equal. Strings which are equivalent /// according to the plain Unicode collation algorithm are additionally ordered /// based on their NFD.) /// /// See Unicode Technical Standard #10. /// /// The behavior is equivalent to `NSString.compare()` with default options. /// /// - returns: /// * an unspecified value less than zero if `lhs < rhs`, /// * zero if `lhs == rhs`, /// * an unspecified value greater than zero if `lhs > rhs`. @_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation") public func _stdlib_compareNSStringDeterministicUnicodeCollation( lhs: AnyObject, _ rhs: AnyObject )-> Int32 #endif extension String : Equatable { } @warn_unused_result public func ==(lhs: String, rhs: String) -> Bool { if lhs._core.isASCII && rhs._core.isASCII { if lhs._core.count != rhs._core.count { return false } return _swift_stdlib_memcmp( lhs._core.startASCII, rhs._core.startASCII, rhs._core.count) == 0 } return lhs._compareString(rhs) == 0 } extension String : Comparable { } extension String { #if _runtime(_ObjC) /// This is consistent with Foundation, but incorrect as defined by Unicode. /// Unicode weights some ASCII punctuation in a different order than ASCII /// value. Such as: /// /// 0022 ; [*02FF.0020.0002] # QUOTATION MARK /// 0023 ; [*038B.0020.0002] # NUMBER SIGN /// 0025 ; [*038C.0020.0002] # PERCENT SIGN /// 0026 ; [*0389.0020.0002] # AMPERSAND /// 0027 ; [*02F8.0020.0002] # APOSTROPHE /// /// - Precondition: Both `self` and `rhs` are ASCII strings. @warn_unused_result public // @testable func _compareASCII(rhs: String) -> Int { var compare = Int(_swift_stdlib_memcmp( self._core.startASCII, rhs._core.startASCII, min(self._core.count, rhs._core.count))) if compare == 0 { compare = self._core.count - rhs._core.count } // This efficiently normalizes the result to -1, 0, or 1 to match the // behaviour of NSString's compare function. return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0) } #endif /// Compares two strings with the Unicode Collation Algorithm. @warn_unused_result @inline(never) @_semantics("stdlib_binary_only") // Hide the CF/ICU dependency public // @testable func _compareDeterministicUnicodeCollation(rhs: String) -> Int { // Note: this operation should be consistent with equality comparison of // Character. #if _runtime(_ObjC) return Int(_stdlib_compareNSStringDeterministicUnicodeCollation( _bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl())) #else switch (_core.isASCII, rhs._core.isASCII) { case (true, false): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf8_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (false, true): // Just invert it and recurse for this case. return -rhs._compareDeterministicUnicodeCollation(self) case (false, false): let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf16_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (true, true): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII) return Int(_swift_stdlib_unicode_compare_utf8_utf8( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) } #endif } @warn_unused_result public // @testable func _compareString(rhs: String) -> Int { #if _runtime(_ObjC) // We only want to perform this optimization on objc runtimes. Elsewhere, // we will make it follow the unicode collation algorithm even for ASCII. if (_core.isASCII && rhs._core.isASCII) { return _compareASCII(rhs) } #endif return _compareDeterministicUnicodeCollation(rhs) } } @warn_unused_result public func <(lhs: String, rhs: String) -> Bool { return lhs._compareString(rhs) < 0 } // Support for copy-on-write extension String { /// Append the elements of `other` to `self`. public mutating func appendContentsOf(other: String) { _core.append(other._core) } /// Append `x` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(x: UnicodeScalar) { _core.append(x) } var _utf16Count: Int { return _core.count } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringNFDHashValue") func _stdlib_NSStringNFDHashValue(str: AnyObject) -> Int @warn_unused_result @_silgen_name("swift_stdlib_NSStringASCIIHashValue") func _stdlib_NSStringASCIIHashValue(str: AnyObject) -> Int #endif extension String : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { #if _runtime(_ObjC) // Mix random bits into NSString's hash so that clients don't rely on // Swift.String.hashValue and NSString.hash being the same. #if arch(i386) || arch(arm) let hashOffset = Int(bitPattern: 0x88dd_cc21) #else let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21) #endif // FIXME(performance): constructing a temporary NSString is extremely // wasteful and inefficient. let cocoaString = unsafeBitCast( self._bridgeToObjectiveCImpl(), _NSStringCoreType.self) // If we have an ASCII string, we do not need to normalize. if self._core.isASCII { return hashOffset ^ _stdlib_NSStringASCIIHashValue(cocoaString) } else { return hashOffset ^ _stdlib_NSStringNFDHashValue(cocoaString) } #else if self._core.isASCII { return _swift_stdlib_unicode_hash_ascii( UnsafeMutablePointer<Int8>(_core.startASCII), Int32(_core.count)) } else { return _swift_stdlib_unicode_hash( UnsafeMutablePointer<UInt16>(_core.startUTF16), Int32(_core.count)) } #endif } } @warn_unused_result @effects(readonly) @_semantics("string.concat") public func + (lhs: String, rhs: String) -> String { var lhs = lhs if (lhs.isEmpty) { return rhs } lhs._core.append(rhs._core) return lhs } // String append public func += (inout lhs: String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } extension String { /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8Count: Int ) { resultStorage.initialize( String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8Count))) } } extension String { public typealias Index = CharacterView.Index /// The position of the first `Character` in `self.characters` if /// `self` is non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return characters.startIndex } /// The "past the end" position in `self.characters`. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return characters.endIndex } /// Access the `Character` at `position`. /// /// - Requires: `position` is a valid position in `self.characters` /// and `position != endIndex`. public subscript(i: Index) -> Character { return characters[i] } } @warn_unused_result public func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base == rhs._base } @warn_unused_result public func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base < rhs._base } extension String { /// Access the characters in the given `subRange`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(subRange: Range<Index>) -> String { return String(characters[subRange]) } } extension String { public mutating func reserveCapacity(n: Int) { withMutableCharacters { (inout v: CharacterView) in v.reserveCapacity(n) } } public mutating func append(c: Character) { withMutableCharacters { (inout v: CharacterView) in v.append(c) } } public mutating func appendContentsOf< S : SequenceType where S.Generator.Element == Character >(newElements: S) { withMutableCharacters { (inout v: CharacterView) in v.appendContentsOf(newElements) } } /// Create an instance containing `characters`. public init< S : SequenceType where S.Generator.Element == Character >(_ characters: S) { self._core = CharacterView(characters)._core } } extension String { @available(*, unavailable, message="call the 'joinWithSeparator()' method on the sequence of elements") public func join< S : SequenceType where S.Generator.Element == String >(elements: S) -> String { fatalError("unavailable function can't be called") } } extension SequenceType where Generator.Element == String { /// Interpose the `separator` between elements of `self`, then concatenate /// the result. For example: /// /// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz" @warn_unused_result public func joinWithSeparator(separator: String) -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { (s: Self) -> Int in var r = 0 for chunk in s { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize != 0 { var gen = generate() if let first = gen.next() { result.appendContentsOf(first) while let next = gen.next() { result.appendContentsOf(separator) result.appendContentsOf(next) } } } else { for x in self { result.appendContentsOf(x) } } return result } } extension String { /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceRange< C: CollectionType where C.Generator.Element == Character >( subRange: Range<Index>, with newElements: C ) { withMutableCharacters { (inout v: CharacterView) in v.replaceRange(subRange, with: newElements) } } /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceRange( subRange: Range<Index>, with newElements: String ) { replaceRange(subRange, with: newElements.characters) } /// Insert `newElement` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func insert(newElement: Character, atIndex i: Index) { withMutableCharacters { (inout v: CharacterView) in v.insert(newElement, atIndex: i) } } /// Insert `newElements` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count + newElements.count`). public mutating func insertContentsOf< S : CollectionType where S.Generator.Element == Character >(newElements: S, at i: Index) { withMutableCharacters { (inout v: CharacterView) in v.insertContentsOf(newElements, at: i) } } /// Remove and return the element at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func removeAtIndex(i: Index) -> Character { return withMutableCharacters { (inout v: CharacterView) in v.removeAtIndex(i) } } /// Remove the indicated `subRange` of characters. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func removeRange(subRange: Range<Index>) { withMutableCharacters { (inout v: CharacterView) in v.removeRange(subRange) } } /// Remove all characters. /// /// Invalidates all indices with respect to `self`. /// /// - parameter keepCapacity: If `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { withMutableCharacters { (inout v: CharacterView) in v.removeAll(keepCapacity: keepCapacity) } } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(str: AnyObject) -> _CocoaStringType @warn_unused_result @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(str: AnyObject) -> _CocoaStringType #else @warn_unused_result internal func _nativeUnicodeLowercaseString(str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } @warn_unused_result internal func _nativeUnicodeUppercaseString(str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } public var lowercaseString: String { if self._core.isASCII { let length = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: length, initialSize: length, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<length { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isUpper & 0x1) << 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest[i] = value &+ UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } public var uppercaseString: String { if self._core.isASCII { let length = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: length, initialSize: length, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<length { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isLower & 0x1) << 5 dest[i] = value &- UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } } // Index conversions extension String.Index { /// Construct the position in `characters` that corresponds exactly to /// `unicodeScalarIndex`. If no such position exists, the result is `nil`. /// /// - Requires: `unicodeScalarIndex` is an element of /// `characters.unicodeScalars.indices`. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within characters: String ) { if !unicodeScalarIndex._isOnGraphemeClusterBoundary { return nil } self.init(_base: unicodeScalarIndex) } /// Construct the position in `characters` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// - Requires: `utf16Index` is an element of /// `characters.utf16.indices`. public init?( _ utf16Index: String.UTF16Index, within characters: String ) { if let me = utf16Index.samePositionIn( characters.unicodeScalars )?.samePositionIn(characters) { self = me } else { return nil } } /// Construct the position in `characters` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// - Requires: `utf8Index` is an element of /// `characters.utf8.indices`. public init?( _ utf8Index: String.UTF8Index, within characters: String ) { if let me = utf8Index.samePositionIn( characters.unicodeScalars )?.samePositionIn(characters) { self = me } else { return nil } } /// Return the position in `utf8` that corresponds exactly /// to `self`. /// /// - Requires: `self` is an element of `String(utf8).indices`. @warn_unused_result public func samePositionIn( utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Return the position in `utf16` that corresponds exactly /// to `self`. /// /// - Requires: `self` is an element of `String(utf16).indices`. @warn_unused_result public func samePositionIn( utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`. /// /// - Requires: `self` is an element of `String(unicodeScalars).indices`. @warn_unused_result public func samePositionIn( unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } }
apache-2.0
83550f3ff7159dff3fe85647a055701c
30.864783
105
0.669137
4.09572
false
false
false
false
mownier/Umalahokan
Umalahokan/Source/UI/Message Writer/RecipientCellAnimator.swift
1
1753
// // RecipientCellAnimator.swift // Umalahokan // // Created by Mounir Ybanez on 10/03/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit protocol RecipientCellAnimator { func animation1(_ duration: TimeInterval, delay: TimeInterval) func animation2(_ duration: TimeInterval, delay: TimeInterval) } extension RecipientCell: RecipientCellAnimator { func animation1(_ duration: TimeInterval, delay: TimeInterval) { let from: CGAffineTransform = CGAffineTransform(scaleX: 0.001, y: 0.001) let to: CGAffineTransform = CGAffineTransform.identity strip.isHidden = true avatarImageView.transform = from displayNameLabel.transform = from onlineStatusIndicator.transform = from UIView.animate(withDuration: duration, delay: delay, animations: { self.avatarImageView.transform = to self.displayNameLabel.transform = to self.onlineStatusIndicator.transform = to }) { _ in self.strip.isHidden = false } } func animation2(_ duration: TimeInterval, delay: TimeInterval) { let from: CGAffineTransform = .identity let to: CGAffineTransform = CGAffineTransform(scaleX: 0.001, y: 0.001) strip.isHidden = true avatarImageView.transform = from displayNameLabel.transform = from onlineStatusIndicator.transform = from UIView.animate(withDuration: duration, delay: delay, animations: { self.avatarImageView.transform = to self.displayNameLabel.transform = to self.onlineStatusIndicator.transform = to }) { _ in self.isHidden = true } } }
mit
f14d9908a333c1221a522d4c57dc96ed
31.444444
80
0.64726
4.880223
false
false
false
false
cybertk/ShadowVPN-iOS
tunnel/PacketTunnelProvider.swift
1
7634
// // PacketTunnelProvider.swift // tunnel // // Created by clowwindy on 7/18/15. // Copyright © 2015 clowwindy. All rights reserved. // import NetworkExtension class PacketTunnelProvider: NEPacketTunnelProvider { var session: NWUDPSession? = nil var conf = [String: AnyObject]() var pendingStartCompletion: (NSError? -> Void)? var userToken: NSData? var chinaDNS: ChinaDNSRunner? var routeManager: RouteManager? // var wifi = ChinaDNSRunner.checkWiFiNetwork() var queue: dispatch_queue_t? override func startTunnelWithOptions(options: [String : NSObject]?, completionHandler: (NSError?) -> Void) { queue = dispatch_queue_create("shadowvpn.queue", DISPATCH_QUEUE_SERIAL) conf = (self.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration! self.pendingStartCompletion = completionHandler chinaDNS = ChinaDNSRunner(DNS: conf["dns"] as? String) if let userTokenString = conf["usertoken"] as? String { if userTokenString.characters.count == 16 { userToken = NSData.fromHexString(userTokenString) } } NSLog("setPassword") SVCrypto.setPassword(conf["password"] as! String) self.recreateUDP() let keyPath = "defaultPath" let options = NSKeyValueObservingOptions([.New, .Old]) self.addObserver(self, forKeyPath: keyPath, options: options, context: nil) NSLog("readPacketsFromTUN") self.readPacketsFromTUN() } func recreateUDP() { if self.session != nil { self.reasserting = true self.session = nil } dispatch_async(queue!) { () -> Void in if let serverAddress = self.protocolConfiguration.serverAddress { if let port = self.conf["port"] as? String { self.reasserting = false self.setTunnelNetworkSettings(nil) { (error: NSError?) -> Void in if let error = error { NSLog("%@", error) // simply kill the extension process since it does no harm and ShadowVPN is expected to be always on exit(1) } dispatch_async(self.queue!) { () -> Void in NSLog("recreateUDP") self.session = self.createUDPSessionToEndpoint(NWHostEndpoint(hostname: serverAddress, port: port), fromEndpoint: nil) self.updateNetwork() } } } } } } func updateNetwork() { NSLog("updateNetwork") let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: self.protocolConfiguration.serverAddress!) newSettings.IPv4Settings = NEIPv4Settings(addresses: [conf["ip"] as! String], subnetMasks: [conf["subnet"] as! String]) routeManager = RouteManager(route: conf["route"] as? String, IPv4Settings: newSettings.IPv4Settings!) if conf["mtu"] != nil { newSettings.MTU = Int(conf["mtu"] as! String) } else { newSettings.MTU = 1432 } if "chnroutes" == (conf["route"] as? String) { NSLog("using ChinaDNS") newSettings.DNSSettings = NEDNSSettings(servers: ["127.0.0.1"]) } else { NSLog("using DNS") newSettings.DNSSettings = NEDNSSettings(servers: (conf["dns"] as! String).componentsSeparatedByString(",")) } NSLog("setTunnelNetworkSettings") self.setTunnelNetworkSettings(newSettings) { (error: NSError?) -> Void in self.readPacketsFromUDP() NSLog("readPacketsFromUDP") if let completionHandler = self.pendingStartCompletion { // send an packet // self.log("completion") NSLog("%@", String(error)) NSLog("VPN started") completionHandler(error) if error != nil { // simply kill the extension process since it does no harm and ShadowVPN is expected to be always on exit(1) } } } } func readPacketsFromTUN() { self.packetFlow.readPacketsWithCompletionHandler { packets, protocols in for packet in packets { // NSLog("TUN: %d", packet.length) self.session?.writeDatagram(SVCrypto.encryptWithData(packet, userToken: self.userToken), completionHandler: { (error: NSError?) -> Void in if let error = error { NSLog("%@", error) // self.recreateUDP() // return } }) } self.readPacketsFromTUN() } } func readPacketsFromUDP() { session?.setReadHandler({ (newPackets: [NSData]?, error: NSError?) -> Void in // self.log("readPacketsFromUDP") guard let packets = newPackets else { return } var protocols = [NSNumber]() var decryptedPackets = [NSData]() for packet in packets { // NSLog("UDP: %d", packet.length) // currently IPv4 only let decrypted = SVCrypto.decryptWithData(packet, userToken: self.userToken) // NSLog("write to TUN: %d", decrypted.length) decryptedPackets.append(decrypted) protocols.append(2) } self.packetFlow.writePackets(decryptedPackets, withProtocols: protocols) }, maxDatagrams: NSIntegerMax) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let object = object { if object as! NSObject == self { if let keyPath = keyPath { if keyPath == "defaultPath" { // commented out since when switching from 4G to Wi-Fi, this will be called multiple times, only the last time works // let wifi = ChinaDNSRunner.checkWiFiNetwork() // if wifi != self.wifi { NSLog("Wi-Fi status changed") // self.wifi = wifi self.recreateUDP() // return // } } } } } } override func stopTunnelWithReason(reason: NEProviderStopReason, completionHandler: () -> Void) { // Add code here to start the process of stopping the tunnel NSLog("stopTunnelWithReason") session?.cancel() completionHandler() super.stopTunnelWithReason(reason, completionHandler: completionHandler) // simply kill the extension process since it does no harm and ShadowVPN is expected to be always on exit(0) } override func handleAppMessage(messageData: NSData, completionHandler: ((NSData?) -> Void)?) { // Add code here to handle the message if let handler = completionHandler { handler(messageData) } } override func sleepWithCompletionHandler(completionHandler: () -> Void) { // Add code here to get ready to sleep completionHandler() } override func wake() { // Add code here to wake up } }
gpl-3.0
70005c4048d0d58289692c810342e437
40.710383
157
0.556793
4.982376
false
false
false
false
dabing1022/AlgorithmRocks
DataStructureAlgorithm/Playground/DataStructureAlgorithm.playground/Pages/ShellSort.xcplaygroundpage/Contents.swift
1
1065
//: [Previous](@previous) /*: # **ShellSort** 希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。希尔排序是非稳定排序算法。该方法因DL.Shell于1959年提出而得名。 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。 */ var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5] func swapTwoValues<T>(inout a: T, inout _ b: T) { (a, b) = (b, a) } func shellSort(inout a: [Int]) { let N = a.count var h = 1 while (h < N / 3) { h = 3 * h + 1 } while (h >= 1) { for i in h..<N { for (var j = i; j >= h && a[j] < a[j - h]; j -= h) { swap(&a[j], &a[j - h]) } } h /= 3 } } shellSort(&randomNumbers) //: [Next](@next)
mit
08a9baa9958e61e9e792e81d48c3b4f3
20.857143
175
0.515033
2.130919
false
false
false
false
DanielAsher/Madness
Documentation/Colours.playground/section-2.swift
1
853
func toComponent(string: String) -> CGFloat { return CGFloat(strtol(string, nil, 16)) / 255 } let digit = %("0"..."9") let lower = %("a"..."f") let upper = %("A"..."F") let hex = digit | lower | upper let hex2 = (hex ++ hex |> map { $0 + $1 }) let component1: Parser<String, CGFloat>.Function = hex |> map { toComponent($0 + $0) } let component2: Parser<String, CGFloat>.Function = toComponent <^> hex2 let three: Parser<String, [CGFloat]>.Function = component1 * 3 let six: Parser<String, [CGFloat]>.Function = component2 * 3 let colour: Parser<String, NSColor>.Function = ignore("#") ++ (six | three) |> map { NSColor(calibratedRed: $0[0], green: $0[1], blue: $0[2], alpha: 1) } if let reddish = parse(colour, "#d52a41") { reddish } if let greenish = parse(colour, "#5a2") { greenish } if let blueish = parse(colour, "#5e8ca1") { blueish }
mit
315d89d7d5bc337d19ba1f0bbe73d8e6
28.413793
86
0.634232
2.921233
false
false
false
false
proversity-org/edx-app-ios
Source/CourseCardView.swift
1
8739
// // CourseCardView.swift // edX // // Created by Jianfeng Qiu on 13/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit private let defaultCoverImageAspectRatio:CGFloat = 0.533 @IBDesignable class CourseCardView: UIView, UIGestureRecognizerDelegate { private let arrowHeight = 15.0 private let verticalMargin = 10 private let coverImageView = UIImageView() private let container = UIView() private let titleLabel = UILabel() private let dateLabel = UILabel() private let bottomLine = UIView() private let overlayContainer = UIView() var course: OEXCourse? var tapAction : ((CourseCardView) -> ())? private var titleTextStyle : OEXTextStyle { return OEXTextStyle(weight : .semiBold, size: .xLarge, color: OEXStyles.shared().neutralXDark()) } private var dateTextStyle : OEXTextStyle { return OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().neutralDark()) } private var coverImageAspectRatio : CGFloat { // Let the placeholder image aspect ratio determine the course card image aspect ratio. guard let placeholder = UIImage(named:"placeholderCourseCardImage") else { return defaultCoverImageAspectRatio } return placeholder.size.height / placeholder.size.width } private func setupView() { configureViews() accessibilityTraits = UIAccessibilityTraits.staticText accessibilityHint = Strings.accessibilityShowsCourseContent } override init(frame : CGRect) { super.init(frame : frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() let bundle = Bundle(for: type(of: self)) coverImageView.image = UIImage(named:"placeholderCourseCardImage", in: bundle, compatibleWith: traitCollection) titleLabel.attributedText = titleTextStyle.attributedString(withText: "Demo Course") dateLabel.attributedText = dateTextStyle.attributedString(withText: "edx | DemoX") } func configureViews() { backgroundColor = OEXStyles.shared().neutralXLight() clipsToBounds = true bottomLine.backgroundColor = OEXStyles.shared().neutralXLight() container.backgroundColor = OEXStyles.shared().neutralWhite().withAlphaComponent(0.85) coverImageView.backgroundColor = OEXStyles.shared().neutralWhiteT() coverImageView.contentMode = UIView.ContentMode.scaleAspectFill coverImageView.clipsToBounds = true coverImageView.hidesLoadingSpinner = true container.accessibilityIdentifier = "Title Bar" container.addSubview(titleLabel) container.addSubview(dateLabel) addSubview(coverImageView) addSubview(container) insertSubview(bottomLine, aboveSubview: coverImageView) addSubview(overlayContainer) coverImageView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) coverImageView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .vertical) dateLabel.setContentHuggingPriority(UILayoutPriority.defaultLow, for: NSLayoutConstraint.Axis.horizontal) dateLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.horizontal) dateLabel.adjustsFontSizeToFitWidth = true container.snp.makeConstraints { make in make.leading.equalTo(self) make.trailing.equalTo(self).priority(.required) make.bottom.equalTo(self).offset(-OEXStyles.dividerSize()) } coverImageView.snp.makeConstraints { make in make.top.equalTo(self) make.leading.equalTo(self) make.trailing.equalTo(self) make.height.equalTo(coverImageView.snp.width).multipliedBy(coverImageAspectRatio).priority(.low) make.bottom.equalTo(self) } dateLabel.snp.makeConstraints { make in make.leading.equalTo(container).offset(StandardHorizontalMargin) make.top.equalTo(titleLabel.snp.bottom).offset(StandardVerticalMargin) make.bottom.equalTo(container).offset(-verticalMargin) make.trailing.equalTo(titleLabel) } bottomLine.snp.makeConstraints { make in make.leading.equalTo(self) make.trailing.equalTo(self) make.bottom.equalTo(self) make.top.equalTo(container.snp.bottom) } overlayContainer.snp.makeConstraints { make in make.leading.equalTo(self) make.trailing.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(container.snp.top) } let tapGesture = UITapGestureRecognizer {[weak self] _ in self?.cardTapped() } tapGesture.delegate = self addGestureRecognizer(tapGesture) } override func updateConstraints() { if let accessory = titleAccessoryView { accessory.snp.remakeConstraints { make in make.trailing.equalTo(container).offset(-StandardHorizontalMargin) make.centerY.equalTo(container) } } titleLabel.snp.remakeConstraints { make in make.leading.equalTo(container).offset(StandardHorizontalMargin) if let accessory = titleAccessoryView { make.trailing.lessThanOrEqualTo(accessory).offset(-StandardHorizontalMargin) } else { make.trailing.equalTo(container).offset(-StandardHorizontalMargin) } make.top.equalTo(container).offset(verticalMargin) } super.updateConstraints() } var titleAccessoryView : UIView? = nil { willSet { titleAccessoryView?.removeFromSuperview() } didSet { if let accessory = titleAccessoryView { container.addSubview(accessory) } updateConstraints() } } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return tapAction != nil } var titleText : String? { get { return titleLabel.text } set { titleLabel.attributedText = titleTextStyle.attributedString(withText: newValue) updateAcessibilityLabel() } } var dateText : String? { get { return dateLabel.text } set { dateLabel.attributedText = dateTextStyle.attributedString(withText: newValue) updateAcessibilityLabel() } } var coverImage : RemoteImage? { get { return coverImageView.remoteImage } set { coverImageView.remoteImage = newValue } } private func cardTapped() { tapAction?(self) } func wrapTitleLabel() { titleLabel.numberOfLines = 3 titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping titleLabel.minimumScaleFactor = 0.5 titleLabel.adjustsFontSizeToFitWidth = true layoutIfNeeded() } @discardableResult func updateAcessibilityLabel()-> String { var accessibilityString = "" if let title = titleText { accessibilityString = title } if let text = dateText { let formateddateText = text.replacingOccurrences(of: "|", with: "") accessibilityString = "\(accessibilityString),\(Strings.accessibilityBy) \(formateddateText)" } accessibilityLabel = accessibilityString return accessibilityString } func addCenteredOverlay(view : UIView) { addSubview(view) view.snp.makeConstraints { make in make.center.equalTo(overlayContainer) } } } extension CourseCardView { static func cardHeight(leftMargin: CGFloat = 0, rightMargin: CGFloat = 0) -> CGFloat { let screenWidth = UIScreen.main.bounds.size.width var height: CGFloat = 0 let screenHeight = UIScreen.main.bounds.size.height let halfScreenHeight = (screenHeight / 2.0) - (leftMargin + rightMargin) let ratioedHeight = screenWidth * defaultCoverImageAspectRatio height = CGFloat(Int(halfScreenHeight > ratioedHeight ? ratioedHeight : halfScreenHeight)) return height } }
apache-2.0
18f6e9dc23633b45bf42daf45ec61563
34.815574
128
0.645383
5.656311
false
false
false
false
EslamHanafy/ESUtilities
ESUtilities/Views.swift
1
2020
// // Views.swift // ESUtilities // // Created by Eslam on 9/8/17. // Copyright © 2017 eslam. All rights reserved. // import UIKit extension UIView { /// change the view layer to be a circle @IBInspectable var ESCircle:Bool{ get { if self.ESCircle == nil { return false } return self.ESCircle } set { if newValue { self.superview?.layoutIfNeeded() self.layer.cornerRadius = self.frame.size.height / 2 } } } /// change the view layer to be a circle @IBInspectable var ESShadow:Bool{ get { if self.ESShadow == nil { return false } return self.ESShadow } set { if newValue { if self is UIImageView { makeShadow(forLayer: makeLayer()) }else{ makeShadow(forLayer: self.layer) } } } } /// create new layer and add it to super view /// /// - Returns: the created layer fileprivate func makeLayer()-> CALayer { let layer = CALayer() layer.bounds = self.bounds.insetBy(dx: 20, dy: 20) layer.position = self.center layer.backgroundColor = self.layer.backgroundColor layer.zPosition = -5 self.superview!.layer.addSublayer(layer) return layer } /// make shadow for layer /// /// - Parameter lyr: the layer that you want to add the shadow for it fileprivate func makeShadow(forLayer lyr:CALayer) { self.superview?.layoutIfNeeded() lyr.shadowColor = UIColor.black.cgColor lyr.shadowOffset = CGSize.zero lyr.shadowOpacity = 0.5 lyr.masksToBounds = false lyr.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath lyr.shadowRadius = 3 } }
gpl-3.0
f0041ebd0223e14a4bd86c83ee282e93
25.565789
109
0.537395
4.630734
false
false
false
false
MilitiaSoftworks/MSAlertController
MSAlertController/Components/MSAlertControllerComponent.swift
1
1745
// // MSAlertControllerComponent.swift // MSAlertController // // Created by Jacob King on 13/01/2017. // Copyright © 2017 Militia Softworks Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit // This is the base component, all others will inheirit from this including custom user classes if they so wish. open class MSAlertControllerComponent: UIView { @IBOutlet internal var topConstraint: NSLayoutConstraint? @IBOutlet internal var bottomConstraint: NSLayoutConstraint? @IBOutlet internal var leftConstraint: NSLayoutConstraint? @IBOutlet internal var rightConstraint: NSLayoutConstraint? @IBOutlet internal var heightConstraint: NSLayoutConstraint? open override func layoutSubviews() { super.layoutSubviews() self.translatesAutoresizingMaskIntoConstraints = false } open func applyConstraintMap(_ map: MSAlertControllerConstraintMap) { self.leftConstraint?.constant = map.leftInset self.rightConstraint?.constant = map.rightInset self.topConstraint?.constant = map.topInset self.bottomConstraint?.constant = map.bottomInset self.heightConstraint?.constant = map.height } }
apache-2.0
daeb14df4d7d1bc2b8feed7ee2229474
38.636364
112
0.740826
4.73913
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Shared Views/Date Chooser/SiteStatsTableHeaderView.swift
1
10702
import UIKit protocol SiteStatsTableHeaderDelegate: AnyObject { func dateChangedTo(_ newDate: Date?) } protocol SiteStatsTableHeaderDateButtonDelegate: SiteStatsTableHeaderDelegate { func didTouchHeaderButton(forward: Bool) } class SiteStatsTableHeaderView: UIView, NibLoadable, Accessible { // MARK: - Properties static let estimatedHeight: CGFloat = 60 @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timezoneLabel: UILabel! @IBOutlet weak var backArrow: UIImageView! @IBOutlet weak var forwardArrow: UIImageView! @IBOutlet weak var bottomSeparatorLine: UIView! { didSet { bottomSeparatorLine.isGhostableDisabled = true } } @IBOutlet weak var backButton: UIButton! { didSet { backButton.isGhostableDisabled = true } } @IBOutlet weak var forwardButton: UIButton! { didSet { forwardButton.isGhostableDisabled = true } } @IBOutlet private var containerView: UIView! { didSet { containerView.isGhostableDisabled = true } } private typealias Style = WPStyleGuide.Stats private weak var delegate: SiteStatsTableHeaderDelegate? private var date: Date? private var period: StatsPeriodUnit? // Allow the date bar to only go up to the most recent date available. // Used by Insights 'This Year' details view and Post Stats. private var mostRecentDate: Date? // Limits how far back the date chooser can go. // Corresponds to the number of bars shown on the Overview chart. static let defaultPeriodCount = 14 private var expectedPeriodCount = SiteStatsTableHeaderView.defaultPeriodCount private var backLimit: Int { return -(expectedPeriodCount - 1) } private var isRunningGhostAnimation: Bool = false // MARK: - View override func awakeFromNib() { super.awakeFromNib() applyStyles() } override func tintColorDidChange() { super.tintColorDidChange() // Restart animation when toggling light/dark mode so colors are updated. restartGhostAnimation(style: GhostCellStyle.muriel) } func configure(date: Date?, period: StatsPeriodUnit?, delegate: SiteStatsTableHeaderDelegate, expectedPeriodCount: Int = SiteStatsTableHeaderView.defaultPeriodCount, mostRecentDate: Date? = nil) { self.date = { if let date = date, let mostRecentDate = mostRecentDate, mostRecentDate < date { return mostRecentDate } return date }() self.period = period self.delegate = delegate self.expectedPeriodCount = expectedPeriodCount self.mostRecentDate = mostRecentDate dateLabel.text = displayDate() displayTimezone() updateButtonStates() prepareForVoiceOver() } func prepareForVoiceOver() { dateLabel.accessibilityLabel = displayDateAccessibilityLabel() backButton.accessibilityLabel = NSLocalizedString("Previous period", comment: "Accessibility label") backButton.accessibilityHint = NSLocalizedString("Tap to select the previous period", comment: "Accessibility hint") backButton.accessibilityTraits = backButton.isEnabled ? [.button] : [.button, .notEnabled] forwardButton.accessibilityLabel = NSLocalizedString("Next period", comment: "Accessibility label") forwardButton.accessibilityHint = NSLocalizedString("Tap to select the next period", comment: "Accessibility hint") forwardButton.accessibilityTraits = forwardButton.isEnabled ? [.button] : [.button, .notEnabled] accessibilityElements = [ dateLabel, timezoneLabel, backButton, forwardButton ].compactMap { $0 } } func updateDate(with intervalDate: Date) { guard let period = period else { return } self.date = StatsPeriodHelper().endDate(from: intervalDate, period: period) delegate?.dateChangedTo(self.date) reloadView() } func animateGhostLayers(_ animate: Bool) { if animate { isRunningGhostAnimation = true startGhostAnimation(style: GhostCellStyle.muriel) } else { isRunningGhostAnimation = false stopGhostAnimation() } updateButtonStates() } } private extension SiteStatsTableHeaderView { func applyStyles() { backgroundColor = .listForeground Style.configureLabelAsCellRowTitle(dateLabel) Style.configureLabelAsChildRowTitle(timezoneLabel) Style.configureViewAsSeparator(bottomSeparatorLine) // Required as the Style separator configure method clears all // separators for the Stats Revamp in Insights. bottomSeparatorLine.backgroundColor = .separator } func displayDate() -> String? { guard let components = displayDateComponents() else { return nil } let (fromDate, toDate) = components if let toDate = toDate { return "\(fromDate) - \(toDate)" } else { return "\(fromDate)" } } func displayDateAccessibilityLabel() -> String? { guard let components = displayDateComponents() else { return nil } let (fromDate, toDate) = components if let toDate = toDate { let format = NSLocalizedString("Current period: %@ to %@", comment: "Week Period Accessibility label. Prefix the current selected period. Ex. Current period: Jan 6 to Jan 12.") return .localizedStringWithFormat(format, fromDate, toDate) } else { let format = NSLocalizedString("Current period: %@", comment: "Period Accessibility label. Prefix the current selected period. Ex. Current period: 2019") return .localizedStringWithFormat(format, fromDate) } } /// Returns the formatted dates for the current period. func displayDateComponents() -> (fromDate: String, toDate: String?)? { guard let date = date, let period = period else { return nil } let dateFormatter = DateFormatter() dateFormatter.setLocalizedDateFormatFromTemplate(period.dateFormatTemplate) switch period { case .day, .month, .year: return (dateFormatter.string(from: date), nil) case .week: let week = StatsPeriodHelper().weekIncludingDate(date) guard let weekStart = week?.weekStart, let weekEnd = week?.weekEnd else { return nil } return (dateFormatter.string(from: weekStart), dateFormatter.string(from: weekEnd)) } } func displayTimezone() { guard !SiteStatsInformation.sharedInstance.timeZoneMatchesDevice(), let siteTimeZone = SiteStatsInformation.sharedInstance.siteTimeZone else { timezoneLabel.isHidden = true timezoneLabel.accessibilityLabel = nil return } timezoneLabel.text = siteTimeZone.displayForStats() timezoneLabel.accessibilityLabel = siteTimeZone.displayForStats() timezoneLabel.isHidden = false } func reloadView() { dateLabel.text = displayDate() updateButtonStates() prepareForVoiceOver() postAccessibilityPeriodLabel() } @IBAction func didTapBackButton(_ sender: UIButton) { captureAnalyticsEvent(.statsDateTappedBackward) updateDate(forward: false) } @IBAction func didTapForwardButton(_ sender: UIButton) { captureAnalyticsEvent(.statsDateTappedForward) updateDate(forward: true) } func updateDate(forward: Bool) { if let delegate = delegate as? SiteStatsTableHeaderDateButtonDelegate { delegate.didTouchHeaderButton(forward: forward) return } guard let date = date, let period = period else { return } let value = forward ? 1 : -1 self.date = StatsPeriodHelper().calculateEndDate(from: date, offsetBy: value, unit: period) delegate?.dateChangedTo(self.date) reloadView() } func updateButtonStates() { guard !isRunningGhostAnimation else { forwardButton.isEnabled = false backButton.isEnabled = false return } guard let date = date, let period = period else { forwardButton.isEnabled = false backButton.isEnabled = false updateArrowStates() return } let helper = StatsPeriodHelper() forwardButton.isEnabled = helper.dateAvailableAfterDate(date, period: period, mostRecentDate: mostRecentDate) backButton.isEnabled = helper.dateAvailableBeforeDate(date, period: period, backLimit: backLimit, mostRecentDate: mostRecentDate) updateArrowStates() prepareForVoiceOver() } func updateArrowStates() { forwardArrow.image = Style.imageForGridiconType(.chevronRight, withTint: (forwardButton.isEnabled ? .darkGrey : .grey)) backArrow.image = Style.imageForGridiconType(.chevronLeft, withTint: (backButton.isEnabled ? .darkGrey : .grey)) } func postAccessibilityPeriodLabel() { UIAccessibility.post(notification: .screenChanged, argument: dateLabel) } // MARK: - Analytics support func captureAnalyticsEvent(_ event: WPAnalyticsStat) { let properties: [AnyHashable: Any] = [StatsPeriodUnit.analyticsPeriodKey: period?.description as Any] if let blogIdentifier = SiteStatsInformation.sharedInstance.siteID { WPAppAnalytics.track(event, withProperties: properties, withBlogID: blogIdentifier) } else { WPAppAnalytics.track(event, withProperties: properties) } } } extension SiteStatsTableHeaderView: StatsBarChartViewDelegate { func statsBarChartValueSelected(_ statsBarChartView: StatsBarChartView, entryIndex: Int, entryCount: Int) { guard let period = period, entryCount > 0, entryCount <= SiteStatsTableHeaderView.defaultPeriodCount else { return } let periodShift = -((entryCount - 1) - entryIndex) let fromDate = mostRecentDate?.normalizedDate() ?? StatsDataHelper.currentDateForSite().normalizedDate() self.date = StatsPeriodHelper().calculateEndDate(from: fromDate, offsetBy: periodShift, unit: period) delegate?.dateChangedTo(self.date) reloadView() } }
gpl-2.0
b82c2f772bdd4d438e2f6b1a6043c1a0
33.191693
188
0.654083
5.287549
false
false
false
false
teklabs/MyTabBarApp
MyTabBarApp/DetailViewController.swift
1
1935
// // DetailItemViewController.swift // MyTabBarApp // // Created by teklabsco on 11/20/15. // Copyright © 2015 Teklabs, LLC. All rights reserved. // import UIKit class DetailViewController: UIViewController,UITextViewDelegate { @IBOutlet weak var detailDescriptionLabel: UITextView! var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if itemObjects.count == 0 { return } if let label = self.detailDescriptionLabel { label.text = itemObjects[currentIndex] if label.text == BLANK_NOTE_TITLE { label.text = "" } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. detailViewController = self detailDescriptionLabel.becomeFirstResponder() detailDescriptionLabel.delegate = self self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if itemObjects.count == 0 { return } itemObjects[currentIndex] = detailDescriptionLabel.text if detailDescriptionLabel.text == "" { itemObjects[currentIndex] = BLANK_NOTE_TITLE } saveAndUpdate() } func saveAndUpdate() { masterView?.save() masterView?.tableView.reloadData() } func textViewDidChange(textView: UITextView) { itemObjects[currentIndex] = detailDescriptionLabel.text saveAndUpdate() } }
gpl-3.0
9048b33d37e24a0efb0d4332d24e5c6b
25.135135
80
0.60031
5.342541
false
false
false
false
davidozhang/spycodes
Spycodes/ViewControllers/Main/SCMainViewController.swift
1
4935
import UIKit class SCMainViewController: SCViewController { @IBOutlet weak var logoLabel: SCLogoLabel! @IBOutlet weak var createGameButton: SCButton! @IBOutlet weak var joinGameButton: SCButton! @IBOutlet weak var swipeUpButton: SCImageButton! // MARK: Actions @IBAction func unwindToMainMenu(_ sender: UIStoryboardSegue) { super.unwindedToSelf(sender) } @IBAction func onCreateGame(_ sender: AnyObject) { Player.instance.setIsHost(true) self.performSegue( withIdentifier: SCConstants.segues.playerNameViewControllerSegue.rawValue, sender: self ) } @IBAction func onJoinGame(_ sender: AnyObject) { self.performSegue( withIdentifier: SCConstants.segues.playerNameViewControllerSegue.rawValue, sender: self ) } @IBAction func onSwipeUpButtonTapped(_ sender: Any) { self.swipeUp() } // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.uniqueIdentifier = SCConstants.viewControllers.mainViewController.rawValue // Currently this view is the root view controller for unwinding logic self.unwindSegueIdentifier = SCConstants.segues.mainViewControllerUnwindSegue.rawValue self.isRootViewController = true SCLogger.log( identifier: SCConstants.loggingIdentifier.deviceType.rawValue, SCDeviceTypeManager.getDeviceType().rawValue ) SCAppInfoManager.checkLatestAppVersion { // If not on latest app version DispatchQueue.main.async { self.showUpdateAppAlert() } } SCStoreKitManager.requestReviewIfAllowed() SCUsageStatisticsManager.instance.recordDiscreteUsageStatistics(.appOpens) self.logoLabel.text = SCStrings.appName.localized self.createGameButton.setTitle( SCStrings.button.createGame.rawLocalized, for: .normal ) self.joinGameButton.setTitle( SCStrings.button.joinGame.rawLocalized, for: .normal ) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) ConsolidatedCategories.instance.reset() Player.instance.reset() SCGameSettingsManager.instance.reset() Statistics.instance.reset() Room.instance.reset() Timer.instance.reset() SCStates.resetAll() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super._prepareForSegue(segue, sender: sender) // All segues identified here should be forward direction only if let vc = segue.destination as? SCMainSettingsViewController { vc.delegate = self } } override func swipeUp() { self.performSegue( withIdentifier: SCConstants.segues.mainSettingsViewControllerSegue.rawValue, sender: self ) } override func setCustomLayoutForDeviceType(deviceType: SCDeviceType) { if deviceType == SCDeviceType.iPhone_X { self.swipeUpButton.isHidden = false self.swipeUpButton.setImage(UIImage(named: "Chevron-Up"), for: UIControlState()) } else { self.swipeUpButton.isHidden = true } } // MARK: Private fileprivate func showUpdateAppAlert() { let alertController = UIAlertController( title: SCStrings.header.updateApp.rawLocalized, message: SCStrings.message.updatePrompt.rawLocalized, preferredStyle: .alert ) let confirmAction = UIAlertAction( title: SCStrings.button.download.rawLocalized, style: .default, handler: { (action: UIAlertAction) in if let appStoreURL = URL(string: SCConstants.url.appStore.rawValue) { UIApplication.shared.openURL(appStoreURL) } } ) alertController.addAction(confirmAction) self.present( alertController, animated: true, completion: nil ) } } // _____ _ _ // | ____|_ _| |_ ___ _ __ ___(_) ___ _ __ ___ // | _| \ \/ / __/ _ \ '_ \/ __| |/ _ \| '_ \/ __| // | |___ > <| || __/ | | \__ \ | (_) | | | \__ \ // |_____/_/\_\\__\___|_| |_|___/_|\___/|_| |_|___/ // MARK: SCMainSettingsViewControllerDelegate extension SCMainViewController: SCMainSettingsViewControllerDelegate { func mainSettings(onToggleViewCellChanged toggleViewCell: SCToggleViewCell, settingType: SCLocalSettingType) { if settingType == .nightMode { DispatchQueue.main.async { super.updateAppearance() } } } }
mit
cfbcffa7bbef4eac0c77b611aad9e07e
31.254902
94
0.608511
4.964789
false
false
false
false
cpageler93/RAML-Swift
Sources/Annotation.swift
1
3161
// // Annotation.swift // RAML // // Created by Christoph on 30.06.17. // import Foundation import Yaml public class Annotation { public var name: String public var singleValue: String? public var parameters: [Yaml: Yaml]? public init(name: String) { self.name = name } internal init() { self.name = "" } } // MARK: Annotation Parsing extension RAML { internal func parseAnnotations(_ input: ParseInput) throws -> [Annotation]? { guard let yaml = input.yaml else { return nil } switch yaml { case .dictionary(let yamlDict): return try parseAnnotations(dict: yamlDict) default: return nil } } internal func parseAnnotations(dict: [Yaml: Yaml]) throws -> [Annotation]? { var annotations: [Annotation] = [] for (key, value) in dict { guard let keyString = key.string else { throw RAMLError.ramlParsingError(.invalidDataType(for: "Annotation Key", mustBeKindOf: "String")) } if keyString.isAnnotationKey() { let annotation = try parseAnnotation(name: keyString.annotationKeyName(), yaml: value) annotations.append(annotation) } } if annotations.count > 0 { return annotations } else { return nil } } internal func parseAnnotation(name: String, yaml: Yaml) throws -> Annotation{ let annotation = Annotation(name: name) switch yaml { case .string(let yamlString): annotation.singleValue = yamlString case .dictionary(let yamlDict): annotation.parameters = yamlDict default: break } return annotation } } internal extension String { internal func isAnnotationKey() -> Bool { return self.hasPrefix("(") && self.hasSuffix(")") } internal func annotationKeyName() -> String { return String(self.dropFirst().dropLast()) } } public protocol HasAnnotations { var annotations: [Annotation]? { get set } } public extension HasAnnotations { public func annotationWith(name: String) -> Annotation? { for annotation in annotations ?? [] { if annotation.name == name { return annotation } } return nil } public func hasAnnotationWith(name: String) -> Bool { return annotationWith(name: name) != nil } } // MARK: Default Values public extension Annotation { public convenience init(initWithDefaultsBasedOn annotation: Annotation) { self.init() self.name = annotation.name self.singleValue = annotation.singleValue self.parameters = annotation.parameters } public func applyDefaults() -> Annotation { return Annotation(initWithDefaultsBasedOn: self) } }
mit
9994e9c69dc7473efa26ee99e663da52
22.414815
102
0.55552
5.065705
false
false
false
false
donpark/clipboard-mac
clipboard/main.swift
1
1787
// // main.swift // clipboard // // Created by Don Park on 3/10/17. // Copyright © 2017 Docuverse. All rights reserved. // import Foundation import AppKit //enum Command: String { // case list = "list" // case ls = "ls" // case get = "get" // case set = "set" // case add = "add" // case remove = "remove" // case rm = "rm" // case clear = "clear" // case copy = "copy" // case paste = "paste" //} let cli = CommandLine() // MARK: Options let help = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Prints a help message.") cli.addOptions(help) func usageExit(_ error: Error? = nil) { if error != nil { cli.printUsage(error!) } else { cli.printUsage() } exit(EX_USAGE) } extension FileHandle : TextOutputStream { public func write(_ string: String) { guard let data = string.data(using: .utf8) else { return } self.write(data) } } func listClipboard(_ args: Arguments) { let pb = NSPasteboard.general() guard let types = pb.types else { return } var stdout = FileHandle.standardOutput print(types, to: &stdout) } func getClipboard(_ args: Arguments) { guard let dataType = args.next() else { usageExit() return } let pb = NSPasteboard.general() if let data = pb.data(forType: dataType) { let stdout = FileHandle.standardOutput stdout.write(data) } } do { try cli.parse() } catch { usageExit(error) } let args = Arguments(cli.unparsedArguments) let cmd = args.next("list") if cmd == nil { usageExit() } switch cmd!.lowercased() { case "list", "ls": listClipboard(args) case "get": getClipboard(args) default: usageExit() } exit(EXIT_SUCCESS)
mit
950503b9c7d70fa53816d565e5c0c701
18.204301
66
0.594625
3.414914
false
false
false
false
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Utils/ChartTransformer.swift
26
10120
// // ChartTransformer.swift // Charts // // Created by Daniel Cohen Gindi on 6/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 /// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards. public class ChartTransformer: NSObject { /// matrix to map the values to the screen pixels internal var _matrixValueToPx = CGAffineTransformIdentity /// matrix for handling the different offsets of the chart internal var _matrixOffset = CGAffineTransformIdentity internal var _viewPortHandler: ChartViewPortHandler public init(viewPortHandler: ChartViewPortHandler) { _viewPortHandler = viewPortHandler } /// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets. public func prepareMatrixValuePx(#chartXMin: Double, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Double) { var scaleX = (_viewPortHandler.contentWidth / deltaX) var scaleY = (_viewPortHandler.contentHeight / deltaY) // setup all matrices _matrixValueToPx = CGAffineTransformIdentity _matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY) _matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin)) } /// Prepares the matrix that contains all offsets. public func prepareMatrixOffset(inverted: Bool) { if (!inverted) { _matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom) } else { _matrixOffset = CGAffineTransformMakeScale(1.0, -1.0) _matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop) } } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the SCATTERCHART. public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) for (var j = 0; j < entries.count; j++) { var e = entries[j] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BUBBLECHART. public func generateTransformedValuesBubble(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint] { let count = to - from var valuePoints = [CGPoint]() valuePoints.reserveCapacity(count) for (var j = 0; j < count; j++) { var e = entries[j + from] valuePoints.append(CGPoint(x: CGFloat(e.xIndex - from) * phaseX + CGFloat(from), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the LINECHART. public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint] { let count = Int(ceil(CGFloat(to - from) * phaseX)) var valuePoints = [CGPoint]() valuePoints.reserveCapacity(count) for (var j = 0; j < count; j++) { var e = entries[j + from] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the CANDLESTICKCHART. public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) for (var j = 0; j < entries.count; j++) { var e = entries[j] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) var setCount = barData.dataSetCount var space = barData.groupSpace for (var j = 0; j < entries.count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0 var y = e.value valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) var setCount = barData.dataSetCount var space = barData.groupSpace for (var j = 0; j < entries.count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0 var y = e.value valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transform an array of points with all matrices. // VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming. public func pointValuesToPixel(inout pts: [CGPoint]) { var trans = valueToPixelMatrix for (var i = 0, count = pts.count; i < count; i++) { pts[i] = CGPointApplyAffineTransform(pts[i], trans) } } public func pointValueToPixel(inout point: CGPoint) { point = CGPointApplyAffineTransform(point, valueToPixelMatrix) } /// Transform a rectangle with all matrices. public func rectValueToPixel(inout r: CGRect) { r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.y > 0.0) { r.origin.y *= phaseY } else { var bottom = r.origin.y + r.size.height bottom *= phaseY r.size.height = bottom - r.origin.y } r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.x > 0.0) { r.origin.x *= phaseY } else { var right = r.origin.x + r.size.width right *= phaseY r.size.width = right - r.origin.x } r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// transforms multiple rects with all matrices public func rectValuesToPixel(inout rects: [CGRect]) { var trans = valueToPixelMatrix for (var i = 0; i < rects.count; i++) { rects[i] = CGRectApplyAffineTransform(rects[i], trans) } } /// Transforms the given array of touch points (pixels) into values on the chart. public func pixelsToValue(inout pixels: [CGPoint]) { var trans = pixelToValueMatrix for (var i = 0; i < pixels.count; i++) { pixels[i] = CGPointApplyAffineTransform(pixels[i], trans) } } /// Transforms the given touch point (pixels) into a value on the chart. public func pixelToValue(inout pixel: CGPoint) { pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix) } /// Returns the x and y values in the chart at the given touch point /// (encapsulated in a PointD). This method transforms pixel coordinates to /// coordinates / values in the chart. public func getValueByTouchPoint(point: CGPoint) -> CGPoint { return CGPointApplyAffineTransform(point, pixelToValueMatrix) } public var valueToPixelMatrix: CGAffineTransform { return CGAffineTransformConcat( CGAffineTransformConcat( _matrixValueToPx, _viewPortHandler.touchMatrix ), _matrixOffset ) } public var pixelToValueMatrix: CGAffineTransform { return CGAffineTransformInvert(valueToPixelMatrix) } }
mit
0cf30ce86fa9658004b85bcad3a0bd53
33.780069
153
0.627964
5.039841
false
false
false
false
pkx0128/UIKit
MUISegmentedControl/MUISegmentedControl/ViewController.swift
1
1201
// // ViewController.swift // MUISegmentedControl // // Created by pankx on 2017/9/23. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //创建mySegment实例 let mysegment = UISegmentedControl(items: ["上午","中午","下午"]) //设置尺寸 mysegment.frame = CGRect(x: 0, y: 16, width: view.bounds.width, height: 40) //设置背景颜色 mysegment.backgroundColor = UIColor.cyan //设置选中颜色 mysegment.tintColor = UIColor.blue //设置开始选中的选项 mysegment.selectedSegmentIndex = 0 //添加事件 mysegment.addTarget(self, action: #selector(vchange), for: .valueChanged) view.addSubview(mysegment) } //选中相关事件方法 func vchange(g:UISegmentedControl) { print(g.selectedSegmentIndex) print(g.titleForSegment(at: g.selectedSegmentIndex) ?? "") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7f601117cda8335c40cf18157d9c42b2
25.285714
83
0.636775
4.181818
false
false
false
false
larryhou/swift
NavigationTransition/NavigationTransition/Transitions/SwipeVerticalTransitionController.swift
1
2540
// // SwipeVerticalTransitionController.swift // NavigationTransition // // Created by larryhou on 24/08/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import UIKit //NOTE: duration = 0.8 class SwipeVerticalTransitionController: NavigationTransitionController { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let allowed = super.gestureRecognizerShouldBegin(gestureRecognizer) if !interactive { let translation = gesture.translation(in: gesture.view) return translation.y > 0 && allowed } return allowed } override func createTransitionAnimator(transitionContext: UIViewControllerContextTransitioning) -> UIViewPropertyAnimator { let fromController = transitionContext.viewController(forKey: .from)! let toController = transitionContext.viewController(forKey: .to)! let fromView = fromController.view! let toView = toController.view! toView.frame = transitionContext.finalFrame(for: toController) if operation == .push { transitionContext.containerView.insertSubview(toView, aboveSubview: fromView) var frame = toView.frame frame.origin.y = frame.height toView.frame = frame toView.layer.cornerRadius = 20 toView.backgroundColor = .red return UIViewPropertyAnimator(duration: duration, curve: .easeInOut) { toView.frame.origin.y = 0 toView.layer.cornerRadius = 0 toView.backgroundColor = .white } } else { transitionContext.containerView.insertSubview(toView, belowSubview: fromView) var frame = fromView.frame frame.origin.y = frame.height return UIViewPropertyAnimator(duration: duration, curve: .easeInOut) { fromView.frame = frame fromView.layer.cornerRadius = 20 fromView.backgroundColor = .red } } } override func fraction(of translation: CGPoint) -> CGFloat { return super.fraction(of: translation) / 4 } override func interactionUpdate(with translation: CGPoint) { super.interactionUpdate(with: translation) } override func updateInteractiveTransition(_ percentComplete: CGFloat, with translation: CGPoint) { } override func createRecoverAnimator() -> UIViewPropertyAnimator? { return nil } }
mit
95eaecb217ab4eec7aaea4e1d3dab7d1
34.760563
127
0.66089
5.543668
false
false
false
false
natestedman/LayoutModules
LayoutModules/Geometry.swift
1
5046
// LayoutModules // Written in 2016 by Nate Stedman <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import CoreGraphics // MARK: - Axes /// The possible major (scrolling) and minor (non-scrolling) axes for a collection view. public enum Axis { /// The horizontal axis. case Horizontal /// The vertical axis. case Vertical } // MARK: - Points /// An axis-agnostic point structure. public struct Point { // MARK: - Initialization /** Initializes a point structure. - parameter major: The major coordinate of the point. - parameter minor: The minor coordinate of the point. */ public init(major: CGFloat, minor: CGFloat) { self.major = major self.minor = minor } /** Initializes a point structure from a Core Graphics point. - parameter CGPoint: A Core Graphics point. - parameter majorAxis: The major axis to use. */ public init(CGPoint: CoreGraphics.CGPoint, majorAxis: Axis) { switch majorAxis { case .Horizontal: self = Point(major: CGPoint.x, minor: CGPoint.y) case .Vertical: self = Point(major: CGPoint.y, minor: CGPoint.x) } } // MARK: - Coordinates /// The major coordinate of the point. var major: CGFloat /// The minor coordinate of the point. var minor: CGFloat } extension Point { // MARK: - Core Graphics Integration /** Converts the axis-agnostic point to a Core Graphics point. - parameter majorAxis: The major axis to use. */ public func CGPointWithMajorAxis(majorAxis: Axis) -> CGPoint { switch majorAxis { case .Horizontal: return CGPoint(x: major, y: minor) case .Vertical: return CGPoint(x: minor, y: major) } } } // MARK: - Sizes /// An axis-agnostic size structure. public struct Size { // MARK: - Initialization /** Initializes a size structure. - parameter major: The major dimension of the size. - parameter minor: The minor dimension of the size. */ public init(major: CGFloat, minor: CGFloat) { self.major = major self.minor = minor } /** Initializes a size structure from a Core Graphics size. - parameter CGSize: A Core Graphics size. - parameter majorAxis: The major axis to use. */ public init(CGSize: CoreGraphics.CGSize, majorAxis: Axis) { switch majorAxis { case .Horizontal: self = Size(major: CGSize.width, minor: CGSize.height) case .Vertical: self = Size(major: CGSize.height, minor: CGSize.width) } } // MARK: - Coordinates /// The major dimension of the size. var major: CGFloat /// The minor dimension of the size. var minor: CGFloat } extension Size { // MARK: - Core Graphics Integration /** Converts the axis-agnostic size to a Core Graphics size. - parameter majorAxis: The major axis to use. */ public func CGSizeWithMajorAxis(majorAxis: Axis) -> CGSize { switch majorAxis { case .Horizontal: return CGSize(width: major, height: minor) case .Vertical: return CGSize(width: minor, height: major) } } } // MARK: - Rects /// An axis-agnostic rect structure. public struct Rect { // MARK: - Initialization /** Initializes a rect structure. - parameter origin: The origin of the rect. - parameter size: The size of the rect. */ public init(origin: Point, size: Size) { self.origin = origin self.size = size } /** Initializes a rect structure from a Core Graphics rect. - parameter CGRect: A Core Graphics rect. - parameter majorAxis: The major axis to use. */ public init(CGRect: CoreGraphics.CGRect, majorAxis: Axis) { self.init( origin: Point(CGPoint: CGRect.origin, majorAxis: majorAxis), size: Size(CGSize: CGRect.size, majorAxis: majorAxis) ) } // MARK: - Components /// The origin of the rect. var origin: Point /// The size of the rect. var size: Size } extension Rect { // MARK: - Core Graphics Integration /** Converts the axis-agnostic rect to a Core Graphics rect. - parameter majorAxis: The major axis to use. */ public func CGRectWithMajorAxis(majorAxis: Axis) -> CGRect { return CGRect( origin: origin.CGPointWithMajorAxis(majorAxis), size: size.CGSizeWithMajorAxis(majorAxis) ) } }
cc0-1.0
ef81625acb5eb3d5f00b13ccdb229a3c
22.469767
88
0.615537
4.290816
false
false
false
false
mminami/MMMoviePlayer
MMMoviePlayer/MovieItem.swift
1
1124
// // Created by mminami on 2017/10/27. // Copyright (c) 2017 mminami. All rights reserved. // import Foundation public struct MovieItem { public let title: String public let videoURL: URL public let presenterName: String public let description: String public let thumbnailURL: URL public let videoDuration: Int public var videoDurationText: String { var components = DateComponents() components.second = videoDuration/1000 let formatter = DateComponentsFormatter() formatter.zeroFormattingBehavior = .pad formatter.allowedUnits = [.minute, .second] return formatter.string(for: components)! } public init(title: String, videoURL: URL, presenterName: String, description: String, thumbnailURL: URL, videoDuration: Int) { self.title = title self.videoURL = videoURL self.presenterName = presenterName self.description = description self.thumbnailURL = thumbnailURL self.videoDuration = videoDuration } }
mit
673ac6369d8112ac774242192beb9793
27.820513
51
0.63968
5.203704
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/People/PeopleViewController.swift
2
15777
import UIKit import CocoaLumberjack import WordPressShared open class PeopleViewController: UITableViewController, NSFetchedResultsControllerDelegate, UIViewControllerRestoration { // MARK: - Properties /// Team's Blog /// open var blog: Blog? /// Mode: Users / Followers /// fileprivate var filter = Filter.Users { didSet { refreshInterface() refreshResultsController() refreshPeople() refreshNoResultsView() } } /// NoResults Helper /// fileprivate let noResultsView = WPNoResultsView() /// Indicates whether there are more results that can be retrieved, or not. /// fileprivate var shouldLoadMore = false { didSet { if shouldLoadMore { footerActivityIndicator.startAnimating() } else { footerActivityIndicator.stopAnimating() } } } /// Indicates whether there is a loadMore call in progress, or not. /// fileprivate var isLoadingMore = false /// Number of records to skip in the next request /// fileprivate var nextRequestOffset = 0 /// Filter Predicate /// fileprivate var predicate: NSPredicate { let predicate = NSPredicate(format: "siteID = %@ AND kind = %@", blog!.dotComID!, NSNumber(value: filter.personKind.rawValue as Int)) return predicate } /// Sort Descriptor /// fileprivate var sortDescriptors: [NSSortDescriptor] { // Note: // Followers must be sorted out by creationDate! // switch filter { case .Followers: return [NSSortDescriptor(key: "creationDate", ascending: true, selector: #selector(NSDate.compare(_:)))] default: return [NSSortDescriptor(key: "displayName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))] } } /// Core Data Context /// fileprivate lazy var context: NSManagedObjectContext = { return ContextManager.sharedInstance().newMainContextChildContext() }() /// Core Data FRC /// fileprivate lazy var resultsController: NSFetchedResultsController<NSFetchRequestResult> = { // FIXME(@koke, 2015-11-02): my user should be first let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") request.predicate = self.predicate request.sortDescriptors = self.sortDescriptors let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc }() /// Navigation Bar Custom Title /// @IBOutlet fileprivate var titleButton: NavBarTitleDropdownButton! /// TableView Footer /// @IBOutlet fileprivate var footerView: UIView! /// TableView Footer Activity Indicator /// @IBOutlet fileprivate var footerActivityIndicator: UIActivityIndicatorView! // MARK: - UITableView Methods open override func numberOfSections(in tableView: UITableView) -> Int { return resultsController.sections?.count ?? 0 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return resultsController.sections?[section].numberOfObjects ?? 0 } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "PeopleCell") as? PeopleCell else { fatalError() } let person = personAtIndexPath(indexPath) let role = self.role(person: person) let viewModel = PeopleCellViewModel(person: person, role: role) cell.bindViewModel(viewModel) return cell } open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return hasHorizontallyCompactView() ? CGFloat.leastNormalMagnitude : 0 } open override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // Refresh only when we reach the last 3 rows in the last section! let numberOfRowsInSection = self.tableView(tableView, numberOfRowsInSection: indexPath.section) guard (indexPath.row + refreshRowPadding) >= numberOfRowsInSection else { return } loadMorePeopleIfNeeded() } // MARK: - NSFetchedResultsController Methods open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { refreshNoResultsView() tableView.reloadData() } // MARK: - View Lifecycle Methods open override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = titleButton navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(invitePersonWasPressed)) WPStyleGuide.configureColors(for: view, andTableView: tableView) // By default, let's display the Blog's Users filter = .Users } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRowWithAnimation(true) refreshNoResultsView() WPAnalytics.track(.openedPeople) } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) tableView.reloadData() } open override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let personViewController = segue.destination as? PersonViewController, let selectedIndexPath = tableView.indexPathForSelectedRow { personViewController.context = context personViewController.blog = blog personViewController.person = personAtIndexPath(selectedIndexPath) switch filter { case .Followers: personViewController.screenMode = .Follower case .Users: personViewController.screenMode = .User case .Viewers: personViewController.screenMode = .Viewer } } else if let navController = segue.destination as? UINavigationController, let inviteViewController = navController.topViewController as? InvitePersonViewController { inviteViewController.blog = blog } } // MARK: - Action Handlers @IBAction open func refresh() { refreshPeople() } @IBAction open func titleWasPressed() { displayModePicker() } @IBAction open func invitePersonWasPressed() { performSegue(withIdentifier: Storyboard.inviteSegueIdentifier, sender: self) } // MARK: - Interface Helpers fileprivate func refreshInterface() { // Note: // We also set the title on purpose, so that whatever VC we push, the back button spells the right title. // title = filter.title titleButton.setAttributedTitleForTitle(filter.title) shouldLoadMore = false } fileprivate func refreshResultsController() { resultsController.fetchRequest.predicate = predicate resultsController.fetchRequest.sortDescriptors = sortDescriptors do { try resultsController.performFetch() // Failsafe: // This was causing a glitch after State Restoration. Top Section padding was being initially // set with an incorrect value, and subsequent reloads weren't picking up the right value. // if isHorizontalSizeClassUnspecified() { return } tableView.reloadData() } catch { DDLogError("Error fetching People: \(error)") } } // MARK: - Sync Helpers fileprivate func refreshPeople() { loadPeoplePage() { [weak self] (retrieved, shouldLoadMore) in self?.tableView.reloadData() self?.nextRequestOffset = retrieved self?.shouldLoadMore = shouldLoadMore self?.refreshControl?.endRefreshing() } } fileprivate func loadMorePeopleIfNeeded() { guard shouldLoadMore == true && isLoadingMore == false else { return } isLoadingMore = true loadPeoplePage(nextRequestOffset) { [weak self] (retrieved, shouldLoadMore) in self?.nextRequestOffset += retrieved self?.shouldLoadMore = shouldLoadMore self?.isLoadingMore = false } } fileprivate func loadPeoplePage(_ offset: Int = 0, success: @escaping ((_ retrieved: Int, _ shouldLoadMore: Bool) -> Void)) { guard let blog = blog, let service = PeopleService(blog: blog, context: context) else { return } switch filter { case .Followers: service.loadFollowersPage(offset, success: success) case .Users: loadUsersPage(offset, success: success) case .Viewers: service.loadViewersPage(offset, success: success) } } fileprivate func loadUsersPage(_ offset: Int = 0, success: @escaping ((_ retrieved: Int, _ shouldLoadMore: Bool) -> Void)) { guard let blog = blogInContext, let peopleService = PeopleService(blog: blog, context: context), let roleService = RoleService(blog: blog, context: context) else { return } var result: (retrieved: Int, shouldLoadMore: Bool)? let group = DispatchGroup() group.enter() peopleService.loadUsersPage(offset, success: { (retrieved, shouldLoadMore) in result = (retrieved, shouldLoadMore) group.leave() }, failure: { (error) in group.leave() }) group.enter() roleService.fetchRoles(success: {_ in group.leave() }, failure: { _ in group.leave() }) group.notify(queue: DispatchQueue.main) { if let result = result { success(result.retrieved, result.shouldLoadMore) } } } fileprivate var blogInContext: Blog? { guard let objectID = blog?.objectID, let object = try? context.existingObject(with: objectID) else { return nil } return object as? Blog } // MARK: - No Results Helpers fileprivate func refreshNoResultsView() { guard resultsController.fetchedObjects?.count == 0 else { noResultsView.removeFromSuperview() return } noResultsView.titleText = NSLocalizedString("No \(filter.title) Yet", comment: "Empty state message (People Management). Please, do not translate the \\(filter.title) part!") if noResultsView.superview == nil { tableView.addSubview(withFadeAnimation: noResultsView) } } // MARK: - Private Helpers fileprivate func personAtIndexPath(_ indexPath: IndexPath) -> Person { let managedPerson = resultsController.object(at: indexPath) as! ManagedPerson return managedPerson.toUnmanaged() } fileprivate func role(person: Person) -> Role? { guard let blog = blog, let service = RoleService(blog: blog, context: context) else { return nil } return service.getRole(slug: person.role) } fileprivate func displayModePicker() { guard let blog = blog else { fatalError() } let filters = filtersAvailableForBlog(blog) let controller = SettingsSelectionViewController(style: .plain) controller.title = NSLocalizedString("Filters", comment: "Title of the list of People Filters") controller.titles = filters.map { $0.title } controller.values = filters.map { $0.rawValue } controller.currentValue = filter.rawValue as NSObject! controller.onItemSelected = { [weak self] selectedValue in guard let rawFilter = selectedValue as? String, let filter = Filter(rawValue: rawFilter) else { fatalError() } self?.filter = filter self?.dismiss(animated: true, completion: nil) } controller.tableView.isScrollEnabled = false ForcePopoverPresenter.configurePresentationControllerForViewController(controller, presentingFromView: titleButton) present(controller, animated: true, completion: nil) } fileprivate func filtersAvailableForBlog(_ blog: Blog) -> [Filter] { var available: [Filter] = [.Users, .Followers] if blog.siteVisibility == .private { available.append(.Viewers) } return available } // MARK: - UIViewControllerRestoration open override func encodeRestorableState(with coder: NSCoder) { let objectString = blog?.objectID.uriRepresentation().absoluteString coder.encode(objectString, forKey: RestorationKeys.blog) super.encodeRestorableState(with: coder) } open class func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { let context = ContextManager.sharedInstance().mainContext guard let blogID = coder.decodeObject(forKey: RestorationKeys.blog) as? String, let objectURL = URL(string: blogID), let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: objectURL), let restoredBlog = try? context.existingObject(with: objectID), let blog = restoredBlog as? Blog else { return nil } return controllerWithBlog(blog) } // MARK: - Static Helpers open class func controllerWithBlog(_ blog: Blog) -> PeopleViewController? { let storyboard = UIStoryboard(name: "People", bundle: nil) guard let viewController = storyboard.instantiateInitialViewController() as? PeopleViewController else { return nil } viewController.blog = blog viewController.restorationClass = self return viewController } // MARK: - Private Enums fileprivate enum Filter: String { case Users = "users" case Followers = "followers" case Viewers = "viewers" var title: String { switch self { case .Users: return NSLocalizedString("Users", comment: "Blog Users") case .Followers: return NSLocalizedString("Followers", comment: "Blog Followers") case .Viewers: return NSLocalizedString("Viewers", comment: "Blog Viewers") } } var personKind: PersonKind { switch self { case .Users: return .user case .Followers: return .follower case .Viewers: return .viewer } } } fileprivate enum RestorationKeys { static let blog = "peopleBlogRestorationKey" } fileprivate enum Storyboard { static let inviteSegueIdentifier = "invite" } fileprivate let refreshRowPadding = 4 }
gpl-2.0
46911f092ce6acfac49a60bb151518c3
32.006276
144
0.622995
5.574912
false
false
false
false
eytanbiala/On-The-Map
On The Map/ListViewController.swift
1
1973
// // ListViewController.swift // On The Map // // Created by Eytan Biala on 4/26/16. // Copyright © 2016 Udacity. All rights reserved. // import Foundation import UIKit class ListViewController : UITableViewController { let reuseId = "cell" convenience init() { self.init(nibName:nil, bundle:nil) tabBarItem.title = "List" tabBarItem.image = UIImage(named: "list") tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: reuseId) tableView.rowHeight = 56 clearsSelectionOnViewWillAppear = true } override func viewDidLoad() { super.viewDidLoad() title = "List" } func reload() { tableView.reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let locations = Model.sharedInstance.studentLocations { return locations.count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(reuseId, forIndexPath: indexPath) if let user = Model.sharedInstance.studentLocations?[indexPath.row] { cell.textLabel?.text = user.full() cell.detailTextLabel?.text = user.url cell.imageView?.image = UIImage(named: "pin") } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let user = Model.sharedInstance.studentLocations?[indexPath.row] { var urlStr = user.url if !urlStr.lowercaseString.hasPrefix("http") { urlStr = "http://" + urlStr } UIApplication.sharedApplication().openURL(NSURL(string: urlStr)!) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
a56b90530e55cb437cbcffbe55dd129b
27.185714
118
0.641988
5.135417
false
false
false
false
tzef/BmoImageLoader
BmoImageLoader/Classes/ProgressAnimation/ColorBarProgressAnimation.swift
1
4573
// // ColorBarProgressAnimation.swift // CrazyMikeSwift // // Created by LEE ZHE YU on 2016/8/8. // Copyright © 2016年 B1-Media. All rights reserved. // import UIKit class ColorBarProgressAnimation: BaseProgressAnimation { var darkerView = BmoProgressHelpView() var containerView = BmoProgressHelpView() var containerViewMaskLayer = CAShapeLayer() var newImageView = BmoProgressImageView() let fillBarView = BmoProgressHelpView() let fillBarMaskLayer = CAShapeLayer() var position = BmoProgressPosition.positionCenter let barHeight = 3 convenience init(imageView: UIImageView, newImage: UIImage?, position: BmoProgressPosition) { self.init() self.imageView = imageView self.newImage = newImage self.position = position progressColor = UIColor(red: 6.0/255.0, green: 125.0/255.0, blue: 255.0/255.0, alpha: 1.0) self.resetAnimation().closure() } // MARK : - Override override func displayLinkAction(_ dis: CADisplayLink) { if let helpPoint = helpPointView.layer.presentation()?.bounds.origin { if helpPoint.x == CGFloat(self.progress.fractionCompleted) { self.displayLink?.invalidate() self.displayLink = nil } let width = fillBarView.bounds.width * helpPoint.x fillBarMaskLayer.path = CGPath(rect: CGRect(x: 0, y: 0, width: width, height: fillBarView.bounds.height), transform: nil) } } override func successAnimation(_ imageView: UIImageView) { self.fillBarView.removeFromSuperview() UIView.transition( with: imageView, duration: self.transitionDuration, options: .transitionCrossDissolve, animations: { self.newImageView.image = self.newImage }, completion: { (finished) in imageView.image = self.newImage UIView.animate(withDuration: self.transitionDuration, animations: { self.darkerView.alpha = 0.0 self.newImageView.alpha = 0.0 }, completion: { (finished) in self.imageView?.image = self.newImageView.image self.completionBlock?(.success(self.newImage)) imageView.bmo_removeProgressAnimation() }) } ) } override func failureAnimation(_ imageView: UIImageView, error: NSError?) { self.fillBarView.removeFromSuperview() UIView.animate(withDuration: self.transitionDuration, animations: { self.darkerView.alpha = 0.0 self.newImageView.alpha = 0.0 }, completion: { (finished) in if finished { self.completionBlock?(.failure(error)) imageView.bmo_removeProgressAnimation() } }) } //MARK: - ProgressAnimator Protocol override func resetAnimation() -> BmoProgressAnimator { guard let strongImageView = self.imageView else { return self } strongImageView.layoutIfNeeded() strongImageView.bmo_removeProgressAnimation() helpPointView.frame = CGRect.zero strongImageView.addSubview(helpPointView) strongImageView.addSubview(darkerView) darkerView.autoFit(strongImageView) strongImageView.addSubview(containerView) containerView.autoFit(strongImageView) newImageView.contentMode = strongImageView.contentMode newImageView.layer.masksToBounds = strongImageView.layer.masksToBounds containerView.addSubview(newImageView) newImageView.autoFit(containerView) fillBarView.backgroundColor = progressColor fillBarView.layer.mask = fillBarMaskLayer containerView.addSubview(fillBarView) switch position { case .positionTop: fillBarView.autoFitTop(containerView, height: CGFloat(barHeight)) case .positionCenter: fillBarView.autoFitCenterVertical(containerView, height: CGFloat(barHeight)) case .positionBottom: fillBarView.autoFitBottom(containerView, height: CGFloat(barHeight)) } fillBarMaskLayer.path = CGMutablePath() if let image = newImage { newImageView.image = image darkerView.backgroundColor = UIColor.black darkerView.alpha = 0.4 } return self } }
mit
42ef53657aacb3d8bd4b87f64d397ff4
36.768595
133
0.62407
5.283237
false
false
false
false
sschiau/SSSolutions.swift
SSSolutions-Swift-Anagram.playground/section-1.swift
1
2117
/** * Copyright 2014 Silviu Schiau. * * * Anagram * * Author: Silviu Schiau <[email protected]> * Version: 1.0.0 * License Apache License Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt * * This copyright 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 let word = "kjf" let string = "djfiakdef" /* * * Method n^2 * */ func isAnagram(word: String, string: String) -> Bool { // Count the word chars matches var count = 0 // Iterate all word's chars for charWord in word { var isFound = false // Iterate all string's chars for charString in string { if charWord == charString { // flag true if char is found isFound = true } } if isFound { ++count if count == countElements(word) { return true } } else { return false } } return false } /* * * Method ((n log n ) * 2) + (2 * n) * */ func isAnagramWithSort(word: String, string: String) -> Bool { let sortedWord = sorted(word) let sortedString = sorted(string) // Count matches var count = 0 for charWord in sortedWord { if var index = find(sortedString, charWord) { ++count if count == countElements(word) { return true } } } return false } isAnagram(word, string) isAnagramWithSort(word, string)
apache-2.0
2d8b3bd9384ff528df15302113bd15e3
20.17
83
0.572036
4.126706
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Settings/ViewControllers/WellDoneViewController.swift
1
2537
// Copyright DApps Platform Inc. All rights reserved. import UIKit enum WellDoneAction { case other } protocol WellDoneViewControllerDelegate: class { func didPress(action: WellDoneAction, sender: UIView, in viewController: WellDoneViewController) } final class WellDoneViewController: UIViewController { weak var delegate: WellDoneViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(image: R.image.mascot_happy()) imageView.translatesAutoresizingMaskIntoConstraints = false let descriptionLabel = UILabel() descriptionLabel.translatesAutoresizingMaskIntoConstraints = false descriptionLabel.text = NSLocalizedString("welldone.description.label.text", value: "Help us grow by sharing this app with your friends!", comment: "") descriptionLabel.font = UIFont.systemFont(ofSize: 16, weight: .regular) descriptionLabel.textColor = Colors.darkBlue descriptionLabel.numberOfLines = 0 descriptionLabel.textAlignment = .center let otherButton = Button(size: .normal, style: .solid) otherButton.translatesAutoresizingMaskIntoConstraints = false otherButton.setTitle(R.string.localizable.share(), for: .normal) otherButton.addTarget(self, action: #selector(other(_:)), for: .touchUpInside) let stackView = UIStackView(arrangedSubviews: [ imageView, //titleLabel, descriptionLabel, .spacer(height: 10), .spacer(), otherButton, ]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.alignment = .center stackView.axis = .vertical stackView.spacing = 10 view.backgroundColor = .white view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor), stackView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor), stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), stackView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor), otherButton.widthAnchor.constraint(equalToConstant: 240), ]) } @objc private func other(_ sender: UIView) { delegate?.didPress(action: .other, sender: sender, in: self) } }
gpl-3.0
ded493fd0fd59f9b1727dc30399d18d5
38.030769
159
0.69728
5.491342
false
false
false
false
Acidburn0zzz/firefox-ios
Storage/SQL/SQLiteHistory.swift
9
45395
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let log = Logger.syncLogger public let TopSiteCacheSize: Int32 = 16 class NoSuchRecordError: MaybeErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } private var ignoredSchemes = ["about"] public func isIgnoredURL(_ url: URL) -> Bool { guard let scheme = url.scheme else { return false } if let _ = ignoredSchemes.firstIndex(of: scheme) { return true } if url.host == "localhost" { return true } return false } public func isIgnoredURL(_ url: String) -> Bool { if let url = URL(string: url) { return isIgnoredURL(url) } return false } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ // The constants in these functions were arrived at by utterly unscientific experimentation. func getRemoteFrecencySQL() -> String { let visitCountExpression = "remoteVisitCount" let now = Date.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))" } func getLocalFrecencySQL() -> String { let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))" let now = Date.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } fileprivate func escapeFTSSearchString(_ search: String) -> String { // Remove double-quotes, split search string on whitespace // and remove any empty strings let words = search.replacingOccurrences(of: "\"", with: "").components(separatedBy: .whitespaces).filter({ !$0.isEmpty }) // If there's only one word, ensure it is longer than 2 // characters. Otherwise, form a different type of search // string to attempt to match the start of URLs. guard words.count > 1 else { guard let word = words.first else { return "" } let charThresholdForSearchAll = 2 if word.count > charThresholdForSearchAll { return "\"\(word)*\"" } else { let titlePrefix = "title: \"^" let httpPrefix = "url: \"^http://" let httpsPrefix = "url: \"^https://" return [titlePrefix, httpPrefix, httpsPrefix, httpPrefix + "www.", httpsPrefix + "www.", httpPrefix + "m.", httpsPrefix + "m."] .map({ "\($0)\(word)*\"" }) .joined(separator: " OR ") } } // Remove empty strings, wrap each word in double-quotes, append // "*", then join it all back together. For words with fewer than // three characters, anchor the search to the beginning of word // bounds by prepending "^". // Example: "foo bar a b" -> "\"foo*\"\"bar*\"\"^a*\"\"^b*\"" return words.map({ "\"\($0)*\"" }).joined() } extension SDRow { func getTimestamp(_ column: String) -> Timestamp? { return (self[column] as? NSNumber)?.uint64Value } func getBoolean(_ column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ open class SQLiteHistory { let db: BrowserDB let favicons: SQLiteFavicons let prefs: Prefs let clearTopSitesQuery: (String, Args?) = ("DELETE FROM cached_top_sites", nil) required public init(db: BrowserDB, prefs: Prefs) { self.db = db self.favicons = SQLiteFavicons(db: self.db) self.prefs = prefs } public func getSites(forURLs urls: [String]) -> Deferred<Maybe<Cursor<Site?>>> { let inExpression = urls.joined(separator: "\",\"") let sql = """ SELECT history.id AS historyID, history.url AS url, title, guid, iconID, iconURL, iconDate, iconType, iconWidth FROM view_favicons_widest, history WHERE history.id = siteID AND history.url IN (\"\(inExpression)\") """ let args: Args = [] return db.runQueryConcurrently(sql, args: args, factory: SQLiteHistory.iconHistoryColumnFactory) } } private let topSitesQuery = "SELECT cached_top_sites.*, page_metadata.provider_name FROM cached_top_sites LEFT OUTER JOIN page_metadata ON cached_top_sites.url = page_metadata.site_url ORDER BY frecencies DESC LIMIT (?)" /** * The init for this will perform the heaviest part of the frecency query * and create a temporary table that can be queried quickly. Currently this accounts for * >75% of the query time. * The scope/lifetime of this object is important as the data is 'frozen' until a new instance is created. */ fileprivate struct SQLiteFrecentHistory: FrecentHistory { private let db: BrowserDB private let prefs: Prefs init(db: BrowserDB, prefs: Prefs) { self.db = db self.prefs = prefs let empty = "DELETE FROM \(MatViewAwesomebarBookmarksWithFavicons)" let insert = """ INSERT INTO \(MatViewAwesomebarBookmarksWithFavicons) SELECT guid, url, title, description, visitDate, iconID, iconURL, iconDate, iconType, iconWidth FROM \(ViewAwesomebarBookmarksWithFavicons) """ _ = db.transaction { connection in try connection.executeChange(empty) try connection.executeChange(insert) } } func getSites(matchingSearchQuery filter: String?, limit: Int) -> Deferred<Maybe<Cursor<Site>>> { let factory = SQLiteHistory.iconHistoryColumnFactory let params = FrecencyQueryParams.urlCompletion(whereURLContains: filter ?? "", groupClause: "GROUP BY historyID ") let (query, args) = getFrecencyQuery(limit: limit, params: params) return db.runQueryConcurrently(query, args: args, factory: factory) } fileprivate func updateTopSitesCacheQuery() -> (String, Args?) { let limit = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? TopSiteCacheSize) let (topSitesQuery, args) = getTopSitesQuery(historyLimit: limit) let insertQuery = """ WITH siteFrecency AS (\(topSitesQuery)) INSERT INTO cached_top_sites SELECT historyID, url, title, guid, domain_id, domain, localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount, iconID, iconURL, iconDate, iconType, iconWidth, frecencies FROM siteFrecency LEFT JOIN view_favicons_widest ON siteFrecency.historyID = view_favicons_widest.siteID """ return (insertQuery, args) } private func topSiteClauses() -> (String, String) { let whereData = "(domains.showOnTopSites IS 1) AND (domains.domain NOT LIKE 'r.%') AND (domains.domain NOT LIKE 'google.%') " let groupBy = "GROUP BY domain_id " return (whereData, groupBy) } enum FrecencyQueryParams { case urlCompletion(whereURLContains: String, groupClause: String) case topSites(groupClause: String, whereData: String) } private func getFrecencyQuery(limit: Int, params: FrecencyQueryParams) -> (String, Args?) { let groupClause: String let whereData: String? let urlFilter: String? switch params { case let .urlCompletion(filter, group): urlFilter = filter groupClause = group whereData = nil case let .topSites(group, whereArg): urlFilter = nil whereData = whereArg groupClause = group } let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24 let sixMonthsAgo = Date.nowMicroseconds() - sixMonthsInMicroseconds let args: Args let ftsWhereClause: String let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))" if let urlFilter = urlFilter?.trimmingCharacters(in: .whitespaces), !urlFilter.isEmpty { // No deleted item has a URL, so there is no need to explicitly add that here. ftsWhereClause = " WHERE (history_fts MATCH ?)\(whereFragment)" args = [escapeFTSSearchString(urlFilter)] } else { ftsWhereClause = " WHERE (history.is_deleted = 0)\(whereFragment)" args = [] } // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = """ SELECT history.id AS historyID, history.url AS url, history.title AS title, history.guid AS guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(sum(visits.is_local), 0) AS localVisitCount, coalesce(sum(CASE visits.is_local WHEN 1 THEN 0 ELSE 1 END), 0) AS remoteVisitCount FROM history INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id INNER JOIN history_fts ON history_fts.rowid = history.rowid \(ftsWhereClause) GROUP BY historyID """ // Next: limit to only those that have been visited at all within the last six months. // (Don't do that in the innermost: we want to get the full count, even if some visits are older.) // Discard all but the 1000 most frecent. // Compute and return the frecency for all 1000 URLs. let frecenciedSQL = """ SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency FROM (\(ungroupedSQL)) WHERE ( -- Eliminate dead rows from coalescing. ((localVisitCount > 0) OR (remoteVisitCount > 0)) AND -- Exclude really old items. ((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo))) ) ORDER BY frecency DESC -- Don't even look at a huge set. This avoids work. LIMIT 1000 """ // Next: merge by domain and select the URL with the max frecency of a domain, ordering by that sum frecency and reducing to a (typically much lower) limit. // NOTE: When using GROUP BY we need to be explicit about which URL to use when grouping. By using "max(frecency)" the result row // for that domain will contain the projected URL corresponding to the history item with the max frecency, https://sqlite.org/lang_select.html#resultset // This is the behavior we want in order to ensure that the most popular URL for a domain is used for the top sites tile. // TODO: make is_bookmarked here accurate by joining against ViewAllBookmarks. // TODO: ensure that the same URL doesn't appear twice in the list, either from duplicate // bookmarks or from being in both bookmarks and history. let historySQL = """ SELECT historyID, url, title, guid, domain_id, domain, max(localVisitDate) AS localVisitDate, max(remoteVisitDate) AS remoteVisitDate, sum(localVisitCount) AS localVisitCount, sum(remoteVisitCount) AS remoteVisitCount, max(frecency) AS maxFrecency, sum(frecency) AS frecencies, 0 AS is_bookmarked FROM (\(frecenciedSQL)) \(groupClause) ORDER BY frecencies DESC LIMIT \(limit) """ let allSQL = """ SELECT * FROM (\(historySQL)) AS hb LEFT OUTER JOIN view_favicons_widest ON view_favicons_widest.siteID = hb.historyID ORDER BY is_bookmarked DESC, frecencies DESC """ return (allSQL, args) } private func getTopSitesQuery(historyLimit: Int) -> (String, Args?) { let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = """ SELECT history.id AS historyID, history.url AS url, history.title AS title, history.guid AS guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(sum(visits.is_local), 0) AS localVisitCount, coalesce(sum(CASE visits.is_local WHEN 1 THEN 0 ELSE 1 END), 0) AS remoteVisitCount FROM history INNER JOIN ( SELECT siteID FROM ( SELECT COUNT(rowid) AS visitCount, siteID FROM visits GROUP BY siteID ORDER BY visitCount DESC LIMIT 5000 ) UNION ALL SELECT siteID FROM ( SELECT siteID FROM visits GROUP BY siteID ORDER BY max(date) DESC LIMIT 1000 ) ) AS groupedVisits ON groupedVisits.siteID = history.id INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id WHERE (history.is_deleted = 0) AND ((domains.showOnTopSites IS 1) AND (domains.domain NOT LIKE 'r.%') AND (domains.domain NOT LIKE 'google.%')) AND (history.url LIKE 'http%') GROUP BY historyID """ let frecenciedSQL = """ SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency FROM (\(ungroupedSQL)) """ let historySQL = """ SELECT historyID, url, title, guid, domain_id, domain, max(localVisitDate) AS localVisitDate, max(remoteVisitDate) AS remoteVisitDate, sum(localVisitCount) AS localVisitCount, sum(remoteVisitCount) AS remoteVisitCount, max(frecency) AS maxFrecency, sum(frecency) AS frecencies, 0 AS is_bookmarked FROM (\(frecenciedSQL)) GROUP BY domain_id ORDER BY frecencies DESC LIMIT \(historyLimit) """ return (historySQL, nil) } } extension SQLiteHistory: BrowserHistory { public func removeSiteFromTopSites(_ site: Site) -> Success { if let host = (site.url as String).asURL?.normalizedHost { return self.removeHostFromTopSites(host) } return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } public func removeFromPinnedTopSites(_ site: Site) -> Success { guard let host = (site.url as String).asURL?.normalizedHost else { return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } //do a fuzzy delete so dupes can be removed let query: (String, Args?) = ("DELETE FROM pinned_top_sites where domain = ?", [host]) return db.run([query]) >>== { return self.db.run([("UPDATE domains SET showOnTopSites = 1 WHERE domain = ?", [host])]) } } public func isPinnedTopSite(_ url: String) -> Deferred<Maybe<Bool>> { let sql = """ SELECT * FROM pinned_top_sites WHERE url = ? LIMIT 1 """ let args: Args = [url] return self.db.queryReturnsResults(sql, args: args) } public func getPinnedTopSites() -> Deferred<Maybe<Cursor<Site>>> { let sql = """ SELECT * FROM pinned_top_sites LEFT OUTER JOIN view_favicons_widest ON historyID = view_favicons_widest.siteID ORDER BY pinDate DESC """ return db.runQueryConcurrently(sql, args: [], factory: SQLiteHistory.iconHistoryMetadataColumnFactory) } public func addPinnedTopSite(_ site: Site) -> Success { // needs test let now = Date.now() guard let guid = site.guid, let host = (site.url as String).asURL?.normalizedHost else { return deferMaybe(DatabaseError(description: "Invalid site \(site.url)")) } let args: Args = [site.url, now, site.title, site.id, guid, host] let arglist = BrowserDB.varlist(args.count) // Prevent the pinned site from being used in topsite calculations // We dont have to worry about this when removing a pin because the assumption is that a user probably doesnt want it being recommended as a topsite either return self.removeHostFromTopSites(host) >>== { return self.db.run([("INSERT OR REPLACE INTO pinned_top_sites (url, pinDate, title, historyID, guid, domain) VALUES \(arglist)", args)]) } } public func removeHostFromTopSites(_ host: String) -> Success { return db.run([("UPDATE domains SET showOnTopSites = 0 WHERE domain = ?", [host])]) } public func removeHistoryForURL(_ url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM visits WHERE siteID = (SELECT id FROM history WHERE url = ?)" let markArgs: Args = [Date.nowNumber(), url] let markDeleted = "UPDATE history SET url = NULL, is_deleted = 1, title = '', should_upload = 1, local_modified = ? WHERE url = ?" return db.run([ (sql: deleteVisits, args: visitArgs), (sql: markDeleted, args: markArgs), favicons.getCleanupFaviconsQuery(), favicons.getCleanupFaviconSiteURLsQuery() ]) } public func removeHistoryFromDate(_ date: Date) -> Success { let visitTimestamp = date.toMicrosecondTimestamp() let historyRemoval = """ WITH deletionIds as (SELECT history.id from history INNER JOIN visits on history.id = visits.siteID WHERE visits.date > ?) UPDATE history SET url = NULL, is_deleted=1, title = '', should_upload = 1, local_modified = ? WHERE history.id in deletionIds """ let historyRemovalArgs: Args = [visitTimestamp, Date.nowNumber()] let visitRemoval = "DELETE FROM visits WHERE visits.date > ?" let visitRemovalArgs: Args = [visitTimestamp] return db.run([ (sql: historyRemoval, args: historyRemovalArgs), (sql: visitRemoval, args: visitRemovalArgs), favicons.getCleanupFaviconsQuery(), favicons.getCleanupFaviconSiteURLsQuery() ]) } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. // Bug 1162778. public func clearHistory() -> Success { return self.db.run([ ("DELETE FROM visits", nil), ("DELETE FROM history", nil), ("DELETE FROM domains", nil), ("DELETE FROM page_metadata", nil), ("DELETE FROM favicon_site_urls", nil), ("DELETE FROM favicons", nil), ]) // We've probably deleted a lot of stuff. Vacuum now to recover the space. >>> effect({ self.db.vacuum() }) } func recordVisitedSite(_ site: Site) -> Success { // Don't store visits to sites with about: protocols if isIgnoredURL(site.url as String) { return deferMaybe(IgnoredSiteError()) } return db.withConnection { conn -> Void in let now = Date.now() if self.updateSite(site, atTime: now, withConnection: conn) > 0 { return } // Insert instead. if self.insertSite(site, atTime: now, withConnection: conn) > 0 { return } let err = DatabaseError(description: "Unable to update or insert site; Invalid key returned") log.error("recordVisitedSite encountered an error: \(err.localizedDescription)") throw err } } func updateSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int { // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. guard let host = (site.url as String).asURL?.normalizedHost else { return 0 } let update = "UPDATE history SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM domains where domain = ?) WHERE url = ?" let updateArgs: Args? = [site.title, time, host, site.url] if Logger.logPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } do { try conn.executeChange(update, withArgs: updateArgs) return conn.numberOfRowsModified } catch let error as NSError { log.warning("Update failed with error: \(error.localizedDescription)") return 0 } } fileprivate func insertSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int { if let host = (site.url as String).asURL?.normalizedHost { do { try conn.executeChange("INSERT OR IGNORE INTO domains (domain) VALUES (?)", withArgs: [host]) } catch let error as NSError { log.warning("Domain insertion failed with \(error.localizedDescription)") return 0 } let insert = """ INSERT INTO history ( guid, url, title, local_modified, is_deleted, should_upload, domain_id ) SELECT ?, ?, ?, ?, 0, 1, id FROM domains WHERE domain = ? """ let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host] do { try conn.executeChange(insert, withArgs: insertArgs) } catch let error as NSError { log.warning("Site insertion failed with \(error.localizedDescription)") return 0 } return 1 } if Logger.logPII { log.warning("Invalid URL \(site.url). Not stored in history.") } return 0 } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(_ visit: SiteVisit) -> Success { return db.withConnection { conn -> Void in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = """ INSERT OR IGNORE INTO visits ( siteID, date, type, is_local ) VALUES ( (SELECT id FROM history WHERE url = ?), ?, ?, 1 ) """ let realDate = visit.date let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] try conn.executeChange(insert, withArgs: insertArgs) } } public func addLocalVisit(_ visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getFrecentHistory() -> FrecentHistory { return SQLiteFrecentHistory(db: db, prefs: prefs) } public func getTopSitesWithLimit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.db.runQueryConcurrently(topSitesQuery, args: [limit], factory: SQLiteHistory.iconHistoryMetadataColumnFactory) } public func setTopSitesNeedsInvalidation() { prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } public func setTopSitesCacheSize(_ size: Int32) { let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0 if oldValue != size { prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize) setTopSitesNeedsInvalidation() } } public func refreshTopSitesQuery() -> [(String, Args?)] { return [clearTopSitesQuery, getFrecentHistory().updateTopSitesCacheQuery()] } public func clearTopSitesCache() -> Success { return self.db.run([clearTopSitesQuery]) >>> { self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func getSitesByLastVisit(limit: Int, offset: Int) -> Deferred<Maybe<Cursor<Site>>> { let sql = """ SELECT history.id AS historyID, history.url, title, guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(count(visits.is_local), 0) AS visitCount , iconID, iconURL, iconDate, iconType, iconWidth FROM history INNER JOIN ( SELECT siteID, max(date) AS latestVisitDate FROM visits GROUP BY siteID ORDER BY latestVisitDate DESC LIMIT \(limit) OFFSET \(offset) ) AS latestVisits ON latestVisits.siteID = history.id INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id LEFT OUTER JOIN view_favicons_widest ON view_favicons_widest.siteID = history.id WHERE (history.is_deleted = 0) GROUP BY history.id ORDER BY latestVisits.latestVisitDate DESC """ return db.runQueryConcurrently(sql, args: nil, factory: SQLiteHistory.iconHistoryColumnFactory) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return db.run("UPDATE history SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return db.run("DELETE FROM history WHERE guid = ?", withArgs: args) } // Fails on non-existence. fileprivate func getSiteIDForGUID(_ guid: GUID) -> Deferred<Maybe<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: (SDRow) -> Int = { return $0["id"] as! Int } return db.runQueryConcurrently(query, args: args, factory: factory) >>== { cursor in if cursor.count == 0 { return deferMaybe(NoSuchRecordError(guid: guid)) } return deferMaybe(cursor[0]!) } } public func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = visit.date let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } fileprivate struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } fileprivate func metadataForGUID(_ guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM history WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return db.runQueryConcurrently(select, args: args, factory: factory) >>== { cursor in return deferMaybe(cursor[0]) } } public func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = modified // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferMaybe(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if let localModified = metadata.localModified, localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE history SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } log.verbose("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.verbose("Updating local history item for guid \(place.guid).") let update = "UPDATE history SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.verbose("Inserting remote history item for guid \(place.guid).") if let host = place.url.asURL?.normalizedHost { if Logger.logPII { log.debug("Inserting: \(place.url).") } let insertDomain = "INSERT OR IGNORE INTO domains (domain) VALUES (?)" let insertHistory = """ INSERT INTO history ( guid, url, title, server_modified, is_deleted, should_upload, domain_id ) SELECT ?, ?, ?, ?, 0, 0, id FROM domains WHERE domain = ? """ return self.db.run([ (insertDomain, [host]), (insertHistory, [place.guid, place.url, place.title, serverModified, host]) ]) >>> always(place.guid) } else { // This is a URL with no domain. Insert it directly. if Logger.logPII { log.debug("Inserting: \(place.url) with no domain.") } let insertHistory = """ INSERT INTO history ( guid, url, title, server_modified, is_deleted, should_upload, domain_id ) VALUES (?, ?, ?, ?, 0, 0, NULL) """ return self.db.run([ (insertHistory, [place.guid, place.url, place.title, serverModified]) ]) >>> always(place.guid) } } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM history WHERE history.should_upload = 1 AND history.is_deleted = 1" let f: (SDRow) -> String = { $0["guid"] as! String } return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // What we want to do: find all history items that are flagged for upload, then find a number of recent visits for each item. // This was originally all in a single SQL query but was seperated into two to save some memory when returning back the cursor. return getModifiedHistory(limit: 1000) >>== { self.attachVisitsTo(places: $0, visitLimit: 20) } } private func getModifiedHistory(limit: Int) -> Deferred<Maybe<[Int: Place]>> { let sql = """ SELECT id, guid, url, title FROM history WHERE should_upload = 1 AND NOT is_deleted = 1 ORDER BY id LIMIT ? """ var places = [Int: Place]() let placeFactory: (SDRow) -> Void = { row in let id = row["id"] as! Int let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) } let args: Args = [limit] return db.runQueryConcurrently(sql, args: args, factory: placeFactory) >>> { deferMaybe(places) } } private func attachVisitsTo(places: [Int: Place], visitLimit: Int) -> Deferred<Maybe<[(Place, [Visit])]>> { // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem. We used to do this in SQL, joining // the visits table to a subselect of visits table, however, ran into OOM issues (Bug 1417034) // // Now, we want a more dumb approach with no joins in SQL and doing group-by-site and limit-to-N in swift. // // We do this in a single query, rather than the N+1 that desktop takes. // // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. // Turn our lazy collection of integers into a comma-seperated string for the IN clause. let historyIDs = Array(places.keys) let sql = """ SELECT siteID, date AS visitDate, type AS visitType FROM visits WHERE siteID IN (\(historyIDs.map(String.init).joined(separator: ","))) ORDER BY siteID DESC, date DESC """ // We want to get a tuple Visit and Place here. We can either have an explicit tuple factory // or we use an identity function, and make do without creating extra data structures. // Since we have a known Out Of Memory issue here, let's avoid extra data structures. let rowIdentity: (SDRow) -> SDRow = { $0 } // We'll need to runQueryUnsafe so we get a LiveSQLiteCursor, i.e. we don't get the cursor // contents into memory all at once. return db.runQueryUnsafe(sql, args: nil, factory: rowIdentity) { (cursor: Cursor<SDRow>) -> [Int: [Visit]] in // Accumulate a mapping of site IDs to list of visits. Each list should be shorter than visitLimit. // Seed our accumulator with empty lists since we already know which IDs we will be fetching. var visits = [Int: [Visit]]() historyIDs.forEach { visits[$0] = [] } // We need to iterate through these explicitly, without relying on the // factory. for row in cursor.makeIterator() { guard let row = row, cursor.status == .success else { throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: cursor.statusMessage]) } guard let id = row["siteID"] as? Int, let existingCount = visits[id]?.count, existingCount < visitLimit else { continue } guard let date = row.getTimestamp("visitDate"), let visitType = row["visitType"] as? Int, let type = VisitType(rawValue: visitType) else { continue } let visit = Visit(date: date, type: type) // Append the visits in descending date order, so we only get the // most recent top N. visits[id]?.append(visit) } return visits } >>== { visits in // Join up the places map we received as input with our visits map. let placesAndVisits: [(Place, [Visit])] = places.compactMap { id, place in guard let visitsList = visits[id], !visitsList.isEmpty else { return nil } return (place, visitsList) } let recentVisitCount = placesAndVisits.reduce(0) { $0 + $1.1.count } log.info("Attaching \(placesAndVisits.count) places to \(recentVisitCount) most recent visits") return deferMaybe(placesAndVisits) } } public func markAsDeleted(_ guids: [GUID]) -> Success { if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") return self.db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).compactMap(markAsDeletedStatementForGUIDs)) } fileprivate func markAsDeletedStatementForGUIDs(_ guids: ArraySlice<String>) -> (String, Args?) { // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM history WHERE is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 } return (sql, args) } public func markAsSynchronized(_ guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { if guids.isEmpty { return deferMaybe(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") return self.db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).compactMap { chunk in return markAsSynchronizedStatementForGUIDs(chunk, modified: modified) }) >>> always(modified) } fileprivate func markAsSynchronizedStatementForGUIDs(_ guids: ArraySlice<String>, modified: Timestamp) -> (String, Args?) { let inClause = BrowserDB.varlist(guids.count) let sql = """ UPDATE history SET should_upload = 0, server_modified = \(modified) WHERE guid IN \(inClause) """ let args: Args = guids.map { $0 } return (sql, args) } public func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } public func doneUpdatingMetadataAfterUpload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteHistory { // Returns a deferred `true` if there are rows in the DB that have a server_modified time. // Because we clear this when we reset or remove the account, and never set server_modified // without syncing, the presence of matching rows directly indicates that a deletion // would be synced to the server. public func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsResults("SELECT 1 FROM history WHERE server_modified IS NOT NULL LIMIT 1") } } extension SQLiteHistory: ResettableSyncStorage { // We don't drop deletions when we reset -- we might need to upload a deleted item // that never made it to the server. public func resetClient() -> Success { let flag = "UPDATE history SET should_upload = 1, server_modified = NULL" return self.db.run(flag) } } extension SQLiteHistory: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing history metadata and deleted items after account removal.") let discard = "DELETE FROM history WHERE is_deleted = 1" return self.db.run(discard) >>> self.resetClient } }
mpl-2.0
d0a86e2061f20d597f90f030fbcfb8bf
42.52349
220
0.594537
4.758885
false
false
false
false
FuckBoilerplate/RxCache
Tests/internal/ProvidersTest.swift
1
12363
// ProvidersMappableTest.swift // RxCache // // Copyright (c) 2016 Victor Albertos https://github.com/VictorAlbertos // // 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 XCTest import RxSwift import Nimble @testable import RxCache class ProvidersTest: XCTestCase { fileprivate var providers : RxCache! fileprivate var persistence : Disk! override func setUp() { super.setUp() persistence = Disk() providers = RxCache.Providers providers.useExpiredDataIfLoaderNotAvailable = false providers.twoLayersCache.evictAll() } func testWhenFirstRetrieveThenSourceRetrievedIsCloud() { let mock = [Mock(aString: "1")] var success = false let provider = MockProvider.mock(evict: nil, lifeCache: nil) providers.cacheArray(Observable.just(mock), provider: provider).subscribe(onNext: { record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }).addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) } func testWhenNoInvalidateCacheThenSourceRetrievedIsNotCloud() { let mock = [Mock(aString: "1")] var success = false let provider = MockProvider.mock(evict: nil, lifeCache: nil) providers.cacheArray(Observable.just(mock), provider: provider).subscribe(onNext: { record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }).addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) success = false providers.cacheArray(Observable.just(mock), provider: provider).subscribe(onNext: { record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).toNot(equal(Source.Cloud.rawValue)) }).addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) } func testWhenInvalidateCacheThenSourceRetrievedIsCloud() { let mock = [Mock(aString: "1")] var success = false providers.cacheArray(Observable.just(mock), provider: MockProvider.mock(evict: nil, lifeCache: nil)).subscribeNext {record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }.addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) let provider = MockProvider.mock(evict: EvictProvider(evict: true), lifeCache: nil) success = false providers.cacheArray(Observable.just(mock), provider: provider).subscribeNext {record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }.addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) } func testWhenLoaderThrowsExceptionAndThereIsNoCacheThenGetThrowException() { let loader : Observable<[Mock]> = Observable.error(NSError(domain: Locale.NotDataReturnWhenCallingObservableLoader, code: 0, userInfo: nil)) let provider = MockProvider.mock(evict: nil, lifeCache: nil) var errorThrown = false providers.cacheArray(loader, provider: provider) .subscribeError { (error) -> Void in errorThrown = true }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(true)) } func tetsWhenUselessLoaderAndCacheNoExpiredByLifeCache0ThenGetMock() { let lifeCache : LifeCache = LifeCache(duration: 0, timeUnit: LifeCache.TimeUnit.seconds) whenUselessLoaderAndCacheNoExpiredThenGetMock(lifeCache) } func testWhenUselessLoaderAndCacheNoExpiredByLifeCacheNilThenGetMock() { whenUselessLoaderAndCacheNoExpiredThenGetMock(nil) } fileprivate func whenUselessLoaderAndCacheNoExpiredThenGetMock(_ lifeCache : LifeCache?) { let mock = [Mock(aString: "1")] var success = false providers.cacheArray(Observable.just(mock), provider: MockProvider.mock(evict: nil, lifeCache: nil)).subscribeNext {record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }.addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) var errorThrown = true let provider = MockProvider.mock(evict: nil, lifeCache: lifeCache) providers.cacheArray(RxCache.errorObservable([Mock].self), provider: provider).subscribeNext {record in expect(record.cacheables[0]).toNot(beNil()) errorThrown = false }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(false)) } func testWhenUselessLoaderAndCacheInvalidateAndUseExpiredDataIfLoaderNotAvailableThenGetMock() { providers.useExpiredDataIfLoaderNotAvailable = true let mock = [Mock(aString: "1")] var success = false providers.cacheArray(Observable.just(mock), provider: MockProvider.mock(evict: nil, lifeCache: nil)).subscribeNext {record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }.addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) var errorThrown = true let provider = MockProvider.mock(evict: EvictProvider(evict: true), lifeCache: nil) providers.cacheArray(RxCache.errorObservable([Mock].self), provider: provider).subscribeNext {record in expect(record.cacheables[0]).toNot(beNil()) errorThrown = false }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(false)) } func testWhenUselessLoaderAndCacheInvalidateButNoUseExpiredDataIfLoaderNotAvailableThenGetException() { providers.useExpiredDataIfLoaderNotAvailable = false let mock = [Mock(aString: "1")] var success = false providers.cacheArray(Observable.just(mock), provider: MockProvider.mock(evict: nil, lifeCache: nil)).subscribeNext {record in success = true expect(record.cacheables[0]).toNot(beNil()) expect(record.source.rawValue).to(equal(Source.Cloud.rawValue)) }.addDisposableTo(DisposeBag()) expect(success).toEventually(equal(true)) let provider = MockProvider.mock(evict: EvictProvider(evict: true), lifeCache: nil) var errorThrown = false providers.cacheArray(RxCache.errorObservable([Mock].self), provider: provider).subscribeError { (error) -> Void in errorThrown = true }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(true)) } func testWhenCacheIsCalledObservableIsDeferredUntilSubscription() { self.providers.twoLayersCache.retrieveHasBeenCalled = false let provider = MockProvider.mock(evict: nil, lifeCache: nil) let mock = [Mock(aString: "1")] let oMock = providers.cacheArray(Observable.just(mock), provider: provider) expect(self.providers.twoLayersCache.retrieveHasBeenCalled).to(equal(false)) oMock.subscribeNext{_ in}.addDisposableTo(DisposeBag()) expect(self.providers.twoLayersCache.retrieveHasBeenCalled).toEventually(equal(true)) } func testWhenUseEvictDynamicKeyWithoutProvidingDynamicKeyGetException() { let mock = [Mock(aString: "1")] var errorThrown = false providers.cacheArray(Observable.just(mock), provider: MockProviderEvictDynamicKey.error()).subscribeError { (error) -> Void in errorThrown = true }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(true)) providers.cacheArray(Observable.just(mock), provider: MockProviderEvictDynamicKey.success()) .subscribeNext {record in errorThrown = false expect(record.cacheables[0]).toNot(beNil()) }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(false)) } func testWhenUseEvictDynamicKeyGroupWithoutProvidingDynamicKeyGroupGetException() { let mock = [Mock(aString: "1")] var errorThrown = false providers.cacheArray(Observable.just(mock), provider: MockProviderEvictDynamicKeyGroup.error()) .subscribeError { (error) -> Void in errorThrown = true }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(true)) providers.cacheArray(Observable.just(mock), provider: MockProviderEvictDynamicKeyGroup.success()) .subscribeNext {record in errorThrown = false expect(record.cacheables[0]).toNot(beNil()) }.addDisposableTo(DisposeBag()) expect(errorThrown).toEventually(equal(false)) } enum MockProvider : Provider { case mock(evict: EvictProvider?, lifeCache : LifeCache? ) var lifeCache: LifeCache? { switch self { case let .mock(_, lifeCache): return lifeCache } } var dynamicKey: DynamicKey? { return nil } var dynamicKeyGroup: DynamicKeyGroup? { return nil } var evict: EvictProvider? { switch self { case let .mock(evict, _): return evict } } } enum MockProviderEvictDynamicKey : Provider { case error() case success() var lifeCache: LifeCache? { return nil } var dynamicKey: DynamicKey? { switch self { case .error(): return nil case .success(): return DynamicKey(dynamicKey: "1") } } var dynamicKeyGroup: DynamicKeyGroup? { return nil } var evict: EvictProvider? { return EvictDynamicKey(evict: true) } } enum MockProviderEvictDynamicKeyGroup : Provider { case error() case success() var lifeCache: LifeCache? { return nil } var dynamicKey: DynamicKey? { return nil } var dynamicKeyGroup: DynamicKeyGroup? { switch self { case .error(): return nil case .success(): return DynamicKeyGroup(dynamicKey: "1", group: "1") } } var evict: EvictProvider? { return EvictDynamicKeyGroup(evict: true) } } }
mit
09f5f5a8c122b3a14d6857ef039def37
38.498403
148
0.63504
4.852041
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/ViewControllers/Stickers/StickerKeyboard.swift
1
16877
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc public protocol StickerKeyboardDelegate { func didSelectSticker(stickerInfo: StickerInfo) func presentManageStickersView() } // MARK: - @objc public class StickerKeyboard: CustomKeyboard { // MARK: - Dependencies private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: - @objc public weak var delegate: StickerKeyboardDelegate? private let mainStackView = UIStackView() private let headerView = UIStackView() private var stickerPacks = [StickerPack]() private var selectedStickerPack: StickerPack? { didSet { selectedPackChanged(oldSelectedPack: oldValue) } } @objc public override init() { super.init() createSubviews() reloadStickers() // By default, show the "recent" stickers. assert(nil == selectedStickerPack) NotificationCenter.default.addObserver(self, selector: #selector(stickersOrPacksDidChange), name: StickerManager.stickersOrPacksDidChange, object: nil) } required public init(coder: NSCoder) { notImplemented() } private func createSubviews() { contentView.addSubview(mainStackView) mainStackView.axis = .vertical mainStackView.alignment = .fill mainStackView.autoPinEdgesToSuperviewEdges() mainStackView.addBackgroundView(withBackgroundColor: Theme.keyboardBackgroundColor) mainStackView.addArrangedSubview(headerView) populateHeaderView() setupPaging() } public override func wasPresented() { super.wasPresented() // If there are no recents, default to showing the first sticker pack. if currentPageCollectionView.stickerCount < 1 { selectedStickerPack = stickerPacks.first } updatePageConstraints() } private func reloadStickers() { databaseStorage.read { (transaction) in self.stickerPacks = StickerManager.installedStickerPacks(transaction: transaction).sorted { $0.dateCreated > $1.dateCreated } } var items = [StickerHorizontalListViewItem]() items.append(StickerHorizontalListViewItemRecents(didSelectBlock: { [weak self] in self?.recentsButtonWasTapped() }, isSelectedBlock: { [weak self] in self?.selectedStickerPack == nil })) items += stickerPacks.map { (stickerPack) in StickerHorizontalListViewItemSticker(stickerInfo: stickerPack.coverInfo, didSelectBlock: { [weak self] in self?.selectedStickerPack = stickerPack }, isSelectedBlock: { [weak self] in self?.selectedStickerPack?.info == stickerPack.info }) } packsCollectionView.items = items guard stickerPacks.count > 0 else { selectedStickerPack = nil return } // Update paging to reflect any potentially new ordering of sticker packs selectedPackChanged(oldSelectedPack: nil) } private static let packCoverSize: CGFloat = 32 private static let packCoverInset: CGFloat = 4 private static let packCoverSpacing: CGFloat = 4 private let packsCollectionView = StickerHorizontalListView(cellSize: StickerKeyboard.packCoverSize, cellInset: StickerKeyboard.packCoverInset, spacing: StickerKeyboard.packCoverSpacing) private func populateHeaderView() { headerView.spacing = StickerKeyboard.packCoverSpacing headerView.axis = .horizontal headerView.alignment = .center headerView.backgroundColor = Theme.keyboardBackgroundColor headerView.layoutMargins = UIEdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6) headerView.isLayoutMarginsRelativeArrangement = true if FeatureFlags.stickerSearch { let searchButton = buildHeaderButton("search-24") { [weak self] in self?.searchButtonWasTapped() } headerView.addArrangedSubview(searchButton) searchButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "searchButton") } packsCollectionView.backgroundColor = Theme.keyboardBackgroundColor headerView.addArrangedSubview(packsCollectionView) let manageButton = buildHeaderButton("plus-24") { [weak self] in self?.manageButtonWasTapped() } headerView.addArrangedSubview(manageButton) manageButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "manageButton") updateHeaderView() } private func buildHeaderButton(_ imageName: String, block: @escaping () -> Void) -> UIView { let button = OWSButton(imageName: imageName, tintColor: Theme.secondaryColor, block: block) button.setContentHuggingHigh() button.setCompressionResistanceHigh() return button } private func updateHeaderView() { } // MARK: Events @objc func stickersOrPacksDidChange() { AssertIsOnMainThread() Logger.verbose("") reloadStickers() updateHeaderView() } public override func orientationDidChange() { super.orientationDidChange() Logger.verbose("") updatePageConstraints(ignoreScrollingState: true) } private func searchButtonWasTapped() { AssertIsOnMainThread() Logger.verbose("") // TODO: } private func recentsButtonWasTapped() { AssertIsOnMainThread() Logger.verbose("") // nil is used for the recents special-case. selectedStickerPack = nil } private func manageButtonWasTapped() { AssertIsOnMainThread() Logger.verbose("") delegate?.presentManageStickersView() } // MARK: - Paging /// This array always includes three collection views, where the indeces represent: /// 0 - Previous Page /// 1 - Current Page /// 2 - Next Page private var stickerPackCollectionViews = [ StickerPackCollectionView(), StickerPackCollectionView(), StickerPackCollectionView() ] private var stickerPackCollectionViewConstraints = [NSLayoutConstraint]() private var currentPageCollectionView: StickerPackCollectionView { return stickerPackCollectionViews[1] } private var nextPageCollectionView: StickerPackCollectionView { return stickerPackCollectionViews[2] } private var previousPageCollectionView: StickerPackCollectionView { return stickerPackCollectionViews[0] } private let stickerPagingScrollView = UIScrollView() private var nextPageStickerPack: StickerPack? { // If we don't have a pack defined, the first pack is always up next guard let stickerPack = selectedStickerPack else { return stickerPacks.first } // If we don't have an index, or we're at the end of the array, recents is up next guard let index = stickerPacks.firstIndex(of: stickerPack), index < (stickerPacks.count - 1) else { return nil } // Otherwise, use the next pack in the array return stickerPacks[index + 1] } private var previousPageStickerPack: StickerPack? { // If we don't have a pack defined, the last pack is always previous guard let stickerPack = selectedStickerPack else { return stickerPacks.last } // If we don't have an index, or we're at the start of the array, recents is previous guard let index = stickerPacks.firstIndex(of: stickerPack), index > 0 else { return nil } // Otherwise, use the previous pack in the array return stickerPacks[index - 1] } private var pageWidth: CGFloat { return stickerPagingScrollView.frame.width } private var numberOfPages: CGFloat { return CGFloat(stickerPackCollectionViews.count) } // These thresholds indicate the offset at which we update the next / previous page. // They're not exactly half way through the transition, to avoid us continously // bouncing back and forth between pages. private var previousPageThreshold: CGFloat { return pageWidth * 0.45 } private var nextPageThreshold: CGFloat { return pageWidth + previousPageThreshold } private func setupPaging() { stickerPagingScrollView.isPagingEnabled = true stickerPagingScrollView.showsHorizontalScrollIndicator = false stickerPagingScrollView.isDirectionalLockEnabled = true stickerPagingScrollView.delegate = self mainStackView.addArrangedSubview(stickerPagingScrollView) stickerPagingScrollView.autoPinEdge(toSuperviewSafeArea: .left) stickerPagingScrollView.autoPinEdge(toSuperviewSafeArea: .right) let stickerPagesContainer = UIView() stickerPagingScrollView.addSubview(stickerPagesContainer) stickerPagesContainer.autoPinEdgesToSuperviewEdges() stickerPagesContainer.autoMatch(.height, to: .height, of: stickerPagingScrollView) stickerPagesContainer.autoMatch(.width, to: .width, of: stickerPagingScrollView, withMultiplier: numberOfPages) for (index, collectionView) in stickerPackCollectionViews.enumerated() { collectionView.backgroundColor = Theme.keyboardBackgroundColor collectionView.isDirectionalLockEnabled = true collectionView.stickerDelegate = self // We want the current page on top, to prevent weird // animations when we initially calculate our frame. if collectionView == currentPageCollectionView { stickerPagesContainer.addSubview(collectionView) } else { stickerPagesContainer.insertSubview(collectionView, at: 0) } collectionView.autoMatch(.width, to: .width, of: stickerPagingScrollView) collectionView.autoMatch(.height, to: .height, of: stickerPagingScrollView) collectionView.autoPinEdge(toSuperviewEdge: .top) collectionView.autoPinEdge(toSuperviewEdge: .bottom) stickerPackCollectionViewConstraints.append( collectionView.autoPinEdge(toSuperviewEdge: .left, withInset: CGFloat(index) * pageWidth) ) } } private var pendingPageChangeUpdates: (() -> Void)? private func applyPendingPageChangeUpdates() { pendingPageChangeUpdates?() pendingPageChangeUpdates = nil } private func selectedPackChanged(oldSelectedPack: StickerPack?) { AssertIsOnMainThread() // We're paging backwards! if oldSelectedPack == nextPageStickerPack { // The previous page becomes the current page and the current page becomes // the next page. We have to load the new previous. stickerPackCollectionViews.insert(stickerPackCollectionViews.removeLast(), at: 0) stickerPackCollectionViewConstraints.insert(stickerPackCollectionViewConstraints.removeLast(), at: 0) pendingPageChangeUpdates = { self.previousPageCollectionView.showInstalledPackOrRecents(stickerPack: self.previousPageStickerPack) } // We're paging forwards! } else if oldSelectedPack == previousPageStickerPack { // The next page becomes the current page and the current page becomes // the previous page. We have to load the new next. stickerPackCollectionViews.append(stickerPackCollectionViews.removeFirst()) stickerPackCollectionViewConstraints.append(stickerPackCollectionViewConstraints.removeFirst()) pendingPageChangeUpdates = { self.nextPageCollectionView.showInstalledPackOrRecents(stickerPack: self.nextPageStickerPack) } // We didn't get here through paging, stuff probably changed. Reload all the things. } else { currentPageCollectionView.showInstalledPackOrRecents(stickerPack: selectedStickerPack) previousPageCollectionView.showInstalledPackOrRecents(stickerPack: previousPageStickerPack) nextPageCollectionView.showInstalledPackOrRecents(stickerPack: nextPageStickerPack) pendingPageChangeUpdates = nil } // If we're not currently scrolling, apply the page change updates immediately. if !isScrollingChange { applyPendingPageChangeUpdates() } updatePageConstraints() // Update the selected pack in the top bar. packsCollectionView.updateSelections() } private func updatePageConstraints(ignoreScrollingState: Bool = false) { // Setup the collection views in their page positions for (index, constraint) in stickerPackCollectionViewConstraints.enumerated() { constraint.constant = CGFloat(index) * pageWidth } // Scrolling backwards if !ignoreScrollingState && stickerPagingScrollView.contentOffset.x <= previousPageThreshold { stickerPagingScrollView.contentOffset.x += pageWidth // Scrolling forward } else if !ignoreScrollingState && stickerPagingScrollView.contentOffset.x >= nextPageThreshold { stickerPagingScrollView.contentOffset.x -= pageWidth // Not moving forward or back, just scroll back to center so we can go forward and back again } else { stickerPagingScrollView.contentOffset.x = pageWidth } } // MARK: - Scroll state management /// Indicates that the user stopped actively scrolling, but /// we still haven't reached their final destination. private var isWaitingForDeceleration = false /// Indicates that the user started scrolling and we've yet /// to reach their final destination. private var isUserScrolling = false /// Indicates that we're currently changing pages due to a /// user initiated scroll action. private var isScrollingChange = false private func userStartedScrolling() { isWaitingForDeceleration = false isUserScrolling = true } private func userStoppedScrolling(waitingForDeceleration: Bool = false) { guard isUserScrolling else { return } if waitingForDeceleration { isWaitingForDeceleration = true } else { isWaitingForDeceleration = false isUserScrolling = false } } private func checkForPageChange() { // Ignore any page changes unless the user is triggering them. guard isUserScrolling else { return } isScrollingChange = true let offsetX = stickerPagingScrollView.contentOffset.x // Scrolled left a page if offsetX <= previousPageThreshold { selectedStickerPack = previousPageStickerPack // Scrolled right a page } else if offsetX >= nextPageThreshold { selectedStickerPack = nextPageStickerPack // We're about to cross the threshold into a new page, execute any pending updates. // We wait to execute these until we're sure we're going to cross over as it // can cause some UI jitter that interupts scrolling. } else if offsetX >= pageWidth * 0.95 && offsetX <= pageWidth * 1.05 { applyPendingPageChangeUpdates() } isScrollingChange = false } } // MARK: - extension StickerKeyboard: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { checkForPageChange() } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { userStartedScrolling() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { userStoppedScrolling(waitingForDeceleration: decelerate) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { userStoppedScrolling() } } extension StickerKeyboard: StickerPackCollectionViewDelegate { public func didTapSticker(stickerInfo: StickerInfo) { AssertIsOnMainThread() Logger.verbose("") delegate?.didSelectSticker(stickerInfo: stickerInfo) } public func stickerPreviewHostView() -> UIView? { AssertIsOnMainThread() return window } public func stickerPreviewHasOverlay() -> Bool { return true } }
gpl-3.0
f8aa7f3e295966d35196693028604822
34.605485
120
0.669017
5.777816
false
false
false
false
bkmunar/firefox-ios
Client/Frontend/Browser/SearchEngines.swift
1
8997
/* 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 private let OrderedEngineNames = "search.orderedEngineNames" private let DisabledEngineNames = "search.disabledEngineNames" private let ShowSearchSuggestionsOptIn = "search.suggestions.showOptIn" private let ShowSearchSuggestions = "search.suggestions.show" /** * Manage a set of Open Search engines. * * The search engines are ordered. Individual search engines can be enabled and disabled. The * first search engine is distinguished and labeled the "default" search engine; it can never be * disabled. Search suggestions should always be sourced from the default search engine. * * Two additional bits of information are maintained: whether the user should be shown "opt-in to * search suggestions" UI, and whether search suggestions are enabled. * * Consumers will almost always use `defaultEngine` if they want a single search engine, and * `quickSearchEngines()` if they want a list of enabled quick search engines (possibly empty, * since the default engine is never included in the list of enabled quick search engines, and * it is possible to disable every non-default quick search engine). * * The search engines are backed by a write-through cache into a ProfilePrefs instance. This class * is not thread-safe -- you should only access it on a single thread (usually, the main thread)! */ class SearchEngines { let prefs: Prefs init(prefs: Prefs) { self.prefs = prefs // By default, show search suggestions opt-in and don't show search suggestions automatically. self.shouldShowSearchSuggestionsOptIn = prefs.boolForKey(ShowSearchSuggestionsOptIn) ?? true self.shouldShowSearchSuggestions = prefs.boolForKey(ShowSearchSuggestions) ?? false self.disabledEngineNames = getDisabledEngineNames() self.orderedEngines = getOrderedEngines() } var defaultEngine: OpenSearchEngine { get { return self.orderedEngines[0] } set(defaultEngine) { // The default engine is always enabled. self.enableEngine(defaultEngine) // The default engine is always first in the list. var orderedEngines = self.orderedEngines.filter({ engine in engine.shortName != defaultEngine.shortName }) orderedEngines.insert(defaultEngine, atIndex: 0) self.orderedEngines = orderedEngines } } func isEngineDefault(engine: OpenSearchEngine) -> Bool { return defaultEngine.shortName == engine.shortName } // The keys of this dictionary are used as a set. private var disabledEngineNames: [String: Bool]! { didSet { self.prefs.setObject(self.disabledEngineNames.keys.array, forKey: DisabledEngineNames) } } var orderedEngines: [OpenSearchEngine]! { didSet { self.prefs.setObject(self.orderedEngines.map({ (engine) in engine.shortName }), forKey: OrderedEngineNames) } } var quickSearchEngines: [OpenSearchEngine]! { get { return self.orderedEngines.filter({ (engine) in !self.isEngineDefault(engine) && self.isEngineEnabled(engine) }) } } var shouldShowSearchSuggestionsOptIn: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestionsOptIn, forKey: ShowSearchSuggestionsOptIn) } } var shouldShowSearchSuggestions: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestions, forKey: ShowSearchSuggestions) } } func isEngineEnabled(engine: OpenSearchEngine) -> Bool { return disabledEngineNames.indexForKey(engine.shortName) == nil } func enableEngine(engine: OpenSearchEngine) { disabledEngineNames.removeValueForKey(engine.shortName) } func disableEngine(engine: OpenSearchEngine) { if isEngineDefault(engine) { // Can't disable default engine. return } disabledEngineNames[engine.shortName] = true } private func getDisabledEngineNames() -> [String: Bool] { if let disabledEngineNames = self.prefs.stringArrayForKey(DisabledEngineNames) { var disabledEngineDict = [String: Bool]() for engineName in disabledEngineNames { disabledEngineDict[engineName] = true } return disabledEngineDict } else { return [String: Bool]() } } // Get all known search engines, with the default search engine first, but the others in no // particular order. class func getUnorderedEngines() -> [OpenSearchEngine] { var error: NSError? let pluginBasePath = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("SearchPlugins") let language = NSLocale.preferredLanguages().first as! String let fallbackDirectory = pluginBasePath.stringByAppendingPathComponent("en") // Look for search plugins in the following order: // 1) the full language ID // 2) the language ID without the dialect // 3) the fallback language (English) // For example, "fr-CA" would look for plugins in this order: 1) fr-CA, 2) fr, 3) en. var searchDirectory = pluginBasePath.stringByAppendingPathComponent(language) if !NSFileManager.defaultManager().fileExistsAtPath(searchDirectory) { let languageWithoutDialect = language.componentsSeparatedByString("-").first! searchDirectory = pluginBasePath.stringByAppendingPathComponent(languageWithoutDialect) if language == languageWithoutDialect || !NSFileManager.defaultManager().fileExistsAtPath(searchDirectory) { searchDirectory = fallbackDirectory } } let index = searchDirectory.stringByAppendingPathComponent("list.txt") let listFile = String(contentsOfFile: index, encoding: NSUTF8StringEncoding, error: &error) let engineNames = listFile! .stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) .componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) assert(error == nil, "Read the list of search engines") var engines = [OpenSearchEngine]() let parser = OpenSearchParser(pluginMode: true) for engineName in engineNames { // Search the current localized search plugins directory for the search engine. // If it doesn't exist, fall back to English. var fullPath = searchDirectory.stringByAppendingPathComponent("\(engineName).xml") if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) { fullPath = fallbackDirectory.stringByAppendingPathComponent("\(engineName).xml") } assert(NSFileManager.defaultManager().fileExistsAtPath(fullPath), "\(fullPath) exists") let engine = parser.parse(fullPath) assert(engine != nil, "Engine at \(fullPath) successfully parsed") engines.append(engine!) } let defaultEngineFile = searchDirectory.stringByAppendingPathComponent("default.txt") let defaultEngineName = String(contentsOfFile: defaultEngineFile, encoding: NSUTF8StringEncoding, error: nil)?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return engines.sorted({ e, _ in e.shortName == defaultEngineName }) } // Get all known search engines, possibly as ordered by the user. private func getOrderedEngines() -> [OpenSearchEngine] { let unorderedEngines = SearchEngines.getUnorderedEngines() if let orderedEngineNames = prefs.stringArrayForKey(OrderedEngineNames) { // We have a persisted order of engines, so try to use that order. // We may have found engines that weren't persisted in the ordered list // (if the user changed locales or added a new engine); these engines // will be appended to the end of the list. return unorderedEngines.sorted { engine1, engine2 in let index1 = find(orderedEngineNames, engine1.shortName) let index2 = find(orderedEngineNames, engine2.shortName) if index1 == nil && index2 == nil { return engine1.shortName < engine2.shortName } // nil < N for all non-nil values of N. if index1 == nil || index2 == nil { return index1 > index2 } return index1 < index2 } } else { // We haven't persisted the engine order, so return whatever order we got from disk. return unorderedEngines } } }
mpl-2.0
a6c3adc302f64b6ea5a0c339d5eab796
43.539604
201
0.673669
5.126496
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/ViewControllers/Misc/Info-About-Settings/SupportViewController.swift
1
9630
// // SupportViewController.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 9/9/17. // import UIKit import EggRating import StoreKit final class SupportViewController: UITableViewController { // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() title = Localizable.support.localized setupTableView() IAPHandler.shared.fetchAvailableProducts(delegate: self) } private func setupTableView() { tableView.backgroundColor = .groupTableViewBackground tableView.contentInset.bottom = 60 tableView.contentInset.top = 20 tableView.separatorStyle = .none tableView.estimatedRowHeight = 60 } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 1 { if IAPHandler.shared.iapProducts.count > 0 { IAPHandler.shared.purchase(atIndex: indexPath.row - 1) } } else if indexPath.section == 2 { if indexPath.row == 1 { // let appId = "1212141622" // guard let url = URL(string : "itms-apps:itunes.apple.com/us/app/apple-store/id\(appId)?mt=8&action=write-review") else { // return // } // UIApplication.shared.open(url, options: [:], completionHandler: nil) EggRating.promptRateUs(in: self) } else { guard let url = URL(string: "https://github.com/nathantannar4/Parse-Dashboard-for-iOS") else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } // MARK: - UITableViewDatasource override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath.section >= 1 ) && indexPath.row == 0 { return 60 } return UITableViewAutomaticDimension } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else if section == 1 { return IAPHandler.shared.iapProducts.count > 0 ? IAPHandler.shared.iapProducts.count + 1 : 2 } else if section == 2 { return 3 } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil) cell.backgroundColor = .groupTableViewBackground cell.textLabel?.numberOfLines = 0 switch indexPath.section { case 0: cell.textLabel?.text = Localizable.supportInfo.localized cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.textLabel?.textColor = .darkGray cell.selectionStyle = .none case 1: if indexPath.row == 0 { cell.textLabel?.text = Localizable.makeDonation.localized cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 24) cell.selectionStyle = .none cell.imageView?.image = UIImage(named: "Money")?.scale(to: 30) let separatorView = UIView() separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) separatorView.anchor(cell.textLabel?.bottomAnchor, left: cell.contentView.leftAnchor, right: cell.contentView.rightAnchor, heightConstant: 0.5) } else if IAPHandler.shared.iapProducts.count > 0 { switch indexPath.row { case 1: cell.imageView?.image = UIImage(named: "Coffee") cell.textLabel?.text = IAPHandler.shared.iapProducts[indexPath.row-1].localizedTitle cell.detailTextLabel?.text = IAPHandler.shared.iapPrices[0] cell.imageView?.tintColor = .logoTint cell.textLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) cell.detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.accessoryType = .disclosureIndicator case 2: cell.imageView?.image = UIImage(named: "Beer") cell.textLabel?.text = IAPHandler.shared.iapProducts[indexPath.row-1].localizedTitle cell.detailTextLabel?.text = IAPHandler.shared.iapPrices[1] cell.imageView?.tintColor = .darkPurpleAccent cell.textLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) cell.detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.accessoryType = .disclosureIndicator case 3: cell.imageView?.image = UIImage(named: "Meal") cell.textLabel?.text = IAPHandler.shared.iapProducts[indexPath.row-1].localizedTitle cell.detailTextLabel?.text = IAPHandler.shared.iapPrices[2] cell.imageView?.tintColor = .darkPurpleBackground cell.textLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) cell.detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.accessoryType = .disclosureIndicator default: break } } else { cell.textLabel?.text = "Fetching Donation Options..." cell.textLabel?.font = UIFont.italicSystemFont(ofSize: 18) } case 2: switch indexPath.row { case 0: cell.textLabel?.text = Localizable.fanPrompt.localized cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 24) cell.selectionStyle = .none cell.imageView?.image = UIImage(named: "Heart")?.scale(to: 30) let separatorView = UIView() separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) separatorView.anchor(cell.textLabel?.bottomAnchor, left: cell.contentView.leftAnchor, right: cell.contentView.rightAnchor, heightConstant: 0.5) case 1: cell.textLabel?.text = Localizable.ratePrompt.localized cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.imageView?.image = UIImage(named: "Rating") cell.accessoryType = .disclosureIndicator case 2: cell.textLabel?.text = Localizable.starRepoPrompt.localized cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.imageView?.image = UIImage(named: "Star") cell.accessoryType = .disclosureIndicator default: break } default: break } return cell } } extension SupportViewController: SKProductsRequestDelegate { // MARK: - SKProductsRequestDelegate func productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse) { IAPHandler.shared.iapProducts.removeAll() IAPHandler.shared.iapPrices.removeAll() let products = response.products.sorted { (a, b) -> Bool in return a.price.decimalValue < b.price.decimalValue } for product in products { let numberFormatter = NumberFormatter() numberFormatter.formatterBehavior = .behavior10_4 numberFormatter.numberStyle = .currency numberFormatter.locale = product.priceLocale if let price1Str = numberFormatter.string(from: product.price) { IAPHandler.shared.iapProducts.append(product) IAPHandler.shared.iapPrices.append(price1Str) print(product.localizedDescription + "\nfor just \(price1Str)") } } tableView.reloadSections([1], with: .none) } }
mit
e6ff4d4c86fd37d0a8b7b3ffee76546a
43.995327
159
0.612525
5.113648
false
false
false
false
cwwise/Keyboard-swift
Pods/Hue/Source/iOS/UIImage+Hue.swift
3
5974
import UIKit class CountedColor { let color: UIColor let count: Int init(color: UIColor, count: Int) { self.color = color self.count = count } } extension UIImage { fileprivate func resize(to newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 2) draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } public func colors(scaleDownSize: CGSize? = nil) -> (background: UIColor, primary: UIColor, secondary: UIColor, detail: UIColor) { let cgImage: CGImage if let scaleDownSize = scaleDownSize { cgImage = resize(to: scaleDownSize).cgImage! } else { let ratio = size.width / size.height let r_width: CGFloat = 250 cgImage = resize(to: CGSize(width: r_width, height: r_width / ratio)).cgImage! } let width = cgImage.width let height = cgImage.height let bytesPerPixel = 4 let bytesPerRow = width * bytesPerPixel let bitsPerComponent = 8 let randomColorsThreshold = Int(CGFloat(height) * 0.01) let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let colorSpace = CGColorSpaceCreateDeviceRGB() let raw = malloc(bytesPerRow * height) let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue let context = CGContext(data: raw, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let data = UnsafePointer<UInt8>(context?.data?.assumingMemoryBound(to: UInt8.self)) let imageBackgroundColors = NSCountedSet(capacity: height) let imageColors = NSCountedSet(capacity: width * height) let sortComparator: (CountedColor, CountedColor) -> Bool = { (a, b) -> Bool in return a.count <= b.count } for x in 0..<width { for y in 0..<height { let pixel = ((width * y) + x) * bytesPerPixel let color = UIColor( red: CGFloat((data?[pixel+1])!) / 255, green: CGFloat((data?[pixel+2])!) / 255, blue: CGFloat((data?[pixel+3])!) / 255, alpha: 1 ) if x >= 5 && x <= 10 { imageBackgroundColors.add(color) } imageColors.add(color) } } var sortedColors = [CountedColor]() for color in imageBackgroundColors { guard let color = color as? UIColor else { continue } let colorCount = imageBackgroundColors.count(for: color) if randomColorsThreshold <= colorCount { sortedColors.append(CountedColor(color: color, count: colorCount)) } } sortedColors.sort(by: sortComparator) var proposedEdgeColor = CountedColor(color: blackColor, count: 1) if let first = sortedColors.first { proposedEdgeColor = first } if proposedEdgeColor.color.isBlackOrWhite && !sortedColors.isEmpty { for countedColor in sortedColors where CGFloat(countedColor.count / proposedEdgeColor.count) > 0.3 { if !countedColor.color.isBlackOrWhite { proposedEdgeColor = countedColor break } } } let imageBackgroundColor = proposedEdgeColor.color let isDarkBackgound = imageBackgroundColor.isDark sortedColors.removeAll() for imageColor in imageColors { guard let imageColor = imageColor as? UIColor else { continue } let color = imageColor.color(minSaturation: 0.15) if color.isDark == !isDarkBackgound { let colorCount = imageColors.count(for: color) sortedColors.append(CountedColor(color: color, count: colorCount)) } } sortedColors.sort(by: sortComparator) var primaryColor, secondaryColor, detailColor: UIColor? for countedColor in sortedColors { let color = countedColor.color if primaryColor == nil && color.isContrasting(with: imageBackgroundColor) { primaryColor = color } else if secondaryColor == nil && primaryColor != nil && primaryColor!.isDistinct(from: color) && color.isContrasting(with: imageBackgroundColor) { secondaryColor = color } else if secondaryColor != nil && (secondaryColor!.isDistinct(from: color) && primaryColor!.isDistinct(from: color) && color.isContrasting(with: imageBackgroundColor)) { detailColor = color break } } free(raw) return ( imageBackgroundColor, primaryColor ?? (isDarkBackgound ? whiteColor : blackColor), secondaryColor ?? (isDarkBackgound ? whiteColor : blackColor), detailColor ?? (isDarkBackgound ? whiteColor : blackColor)) } public func color(at point: CGPoint, completion: @escaping (UIColor?) -> Void) { let size = self.size let cgImage = self.cgImage DispatchQueue.global(qos: .userInteractive).async { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) guard let imgRef = cgImage, let dataProvider = imgRef.dataProvider, let dataCopy = dataProvider.data, let data = CFDataGetBytePtr(dataCopy), rect.contains(point) else { completion(nil) return } let pixelInfo = (Int(size.width) * Int(point.y) + Int(point.x)) * 4 let red = CGFloat(data[pixelInfo]) / 255.0 let green = CGFloat(data[pixelInfo + 1]) / 255.0 let blue = CGFloat(data[pixelInfo + 2]) / 255.0 let alpha = CGFloat(data[pixelInfo + 3]) / 255.0 DispatchQueue.main.async { completion(UIColor(red: red, green: green, blue: blue, alpha: alpha)) } } } }
mit
f7d611e788d594a8a9a055ab0640875e
33.137143
173
0.635588
4.522332
false
false
false
false
Zodiac-Innovations/SlamCocoaTouch
SlamCocoaTouch/SlamButton.swift
1
2305
// // SlamButton.swift // SlamCocoaTouch // Closure based Button view // // Created by Steve Sheets on 10/12/17. // Copyright © 2017 Zodiac Innovations. All rights reserved. // import UIKit import UIKit /// Closure based Button view public class SlamButton: UIButton, SlamViewProtocol { /// Optional action closure invoked when view is pressed public var actionClosure: SlamActionClosure? /// Optional closure invoked by UI to fill view's title public var contentClosure: SlamStringClosure? /// Optional closure invoked by UI to display/hide view public var visibleClosure: SlamFlagClosure? /// Optional closure invoked by UI to enable/disable view public var activeClosure: SlamFlagClosure? public override init(frame: CGRect) { super.init(frame: frame) self.addTarget(self, action: #selector(press(sender:)), for: .touchUpInside) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addTarget(self, action: #selector(press(sender:)), for: .touchUpInside) } /// Action method invoked when view is pressed. It invokes the closure. @objc func press(sender: UIView) { if let actionClosure = actionClosure { actionClosure() } } public func slamUI() { // Hide the view if needed, set text if neeed, enable/disable if needed, then show if needed. let currentlyVisible = !self.isHidden var wantVisible = currentlyVisible if let visibleClosure = visibleClosure { wantVisible = visibleClosure() } if !wantVisible, currentlyVisible { self.isHidden = true } if let contentClosure = contentClosure { let string = contentClosure() if string != self.title(for: .normal) { self.setTitle(string, for: .normal) } } if let activeClosure = activeClosure { let isActive = activeClosure() if self.isEnabled != isActive { self.isEnabled = isActive } } if wantVisible, !currentlyVisible { self.isHidden = false } } }
mit
e49401ec97263687da3db4bd9886919c
27.097561
101
0.605903
4.740741
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/CoreData/GMSInboxAlphaName+Extension.swift
1
1673
// // GMSInboxAlphaName+Extension.swift // GlobalMessageService // // Created by Vitalii Budnik on 2/25/16. // Copyright © 2016 Global Message Services Worldwide. All rights reserved. // import Foundation import CoreData extension GMSInboxAlphaName: NSManagedObjectSearchable { // swiftlint:disable line_length /** Search and creates (if needed) `GMSInboxFetchedDate` object for passed date - parameter alphaName: `String` with Alpha name - parameter managedObjectContext: `NSManagedObjectContext` in what to search. (optional. Default value: `GlobalMessageServiceCoreDataHelper.managedObjectContext`) - returns: `self` if found, or successfully created, `nil` otherwise */ internal static func getInboxAlphaName( alphaName name: String?, inManagedObjectContext managedObjectContext: NSManagedObjectContext? = GlobalMessageServiceCoreDataHelper.managedObjectContext) -> GMSInboxAlphaName? // swiftlint:disable:this opnening_brace { // swiftlint:enable line_length let aplhaNameString = name ?? unknownAlphaNameString let predicate = NSPredicate(format: "title == %@", aplhaNameString) guard let aplhaName = GMSInboxAlphaName.findObject( withPredicate: predicate, inManagedObjectContext: managedObjectContext) as? GMSInboxAlphaName else // swiftlint:disable:this opnening_brace { return .None } aplhaName.title = aplhaNameString return aplhaName } /** Unlocalized default string for unknown alpha-name in remote push-notification */ internal static var unknownAlphaNameString: String { return "_UNKNOWN_ALPHA_NAME_" } }
apache-2.0
bec1d82212dfd4b1ac332e19d9d9fc20
30.54717
131
0.73445
4.763533
false
false
false
false
ymedialabs/Swift-Notes
Swift-Notes.playground/Pages/13. Inheritance.xcplaygroundpage/Contents.swift
2
4081
//: # Swift Foundation //: ---- //: ## Inheritance //: A class can inherit methods, properties, and other characteristics from another class. /*: When one class inherits from another class, * the inheriting class is called as the ***subclass*** * and the class it inherits from is the ***superclass*** Subclass can * call and access methods, properties, subscripts belonging to its superclass. * override methods, properties, subscripts. * add property observers to inherited properties. */ //: ### Base Class //Any class that doesn't inherit from another class is a ***base class*** class BaseClass { var someProperty = 1 func someMethod() -> String { return "Hi" } } //: ### Subclassing class SubClassA: BaseClass { var anotherProperty = 2 } class SubClassB: SubClassA { } let temp = SubClassA() temp.anotherProperty temp.someProperty temp.someMethod() let temp2 = SubClassB() temp2.anotherProperty temp2.someProperty temp2.someMethod() //: ### Overriding //: A subclass can provide its own custom implementation of an instance method, type method, instance property, type property, or subscript that it would otherwise inherit from a superclass. This is known as overriding. /*: * Prefix the overriding definition with an `override` keyword. * Adding `override` keyword clarifies that you have not provided matching definition by mistake. * Any overrides without `override` keyword is a compiler error. * Allows Swift to check if the *superclass* has the same matching declaration. */ class ClassA { var storedProperty: Int = 10 var computedProperty: Int { get{ return storedProperty + 2 } set { storedProperty = newValue - 2 } } var anotherComputedProperty: Int { return storedProperty + 5 } func someMethod() { print("Hello") } } class ClassB: ClassA { var normalProperty: Int = 20 override var computedProperty: Int { get{ return normalProperty + 3 } set { normalProperty = newValue - 3 } } override var anotherComputedProperty: Int { get { return normalProperty + 5 } set { normalProperty = newValue - 5 } } } var foo = ClassA() foo.storedProperty foo.computedProperty foo.computedProperty = 20 foo.storedProperty var bar = ClassB() bar.storedProperty bar.computedProperty bar.anotherComputedProperty bar.anotherComputedProperty = 15 bar.normalProperty //: ### Overriding Property observers //: You can use property overriding to add property observers to an inherited property. class ClassC: ClassA { override var storedProperty: Int { willSet { print("normalProperty is about to change") } didSet { print("normalProperty changed") } } //Can't override read-only computed property // override var anotherComputedProperty: Int { // willSet { // print("normalProperty is about to change") // } // didSet { // print("normalProperty changed") // } // } } var fooBar = ClassC() //fooBar.storedProperty = 30 //: ## 📖 //: You cannot add property observers to inherited constant stored properties and inherited read only computed properties. The values of these properties cannot change, hence not appropriate to have `willSet` and `didSet`. //: ### Preventing Overrides & Subclass /*: * You can prevent a method, property, or subscript from being overridden by marking it as final. * You can also prevent a class from being subclassed by marking it as final. * Do this by prefixing with `final` keyword before the definition */ final class ClassD: ClassC { final var someProperty = 10 final func description() { } } //Can't create a subclass of ClassD, since it is marked sa final. //class ClassE: ClassD { // override func description() { // // } //} //: ---- //: [Next](@next)
mit
36ea9fd62f3f2450fcbc9f7955e888c6
22.436782
222
0.653997
4.531111
false
false
false
false
manavgabhawala/swift
test/IRGen/enum_resilience.swift
1
12452
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s import resilient_enum import resilient_struct // CHECK: %swift.type = type { [[INT:i32|i64]] } // CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }> // CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }> // Public fixed layout struct contains a public resilient struct, // cannot use spare bits // CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }> // Public resilient struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }> // Internal fixed layout struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }> // Public fixed layout struct contains a fixed layout struct, // can use spare bits // CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }> public class Class {} public struct Reference { public var n: Class } @_fixed_layout public enum Either { case Left(Reference) case Right(Reference) } public enum ResilientEither { case Left(Reference) case Right(Reference) } enum InternalEither { case Left(Reference) case Right(Reference) } @_fixed_layout public struct ReferenceFast { public var n: Class } @_fixed_layout public enum EitherFast { case Left(ReferenceFast) case Right(ReferenceFast) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_TF15enum_resilience25functionWithResilientEnumFO14resilient_enum6MediumS1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithResilientEnum(_ m: Medium) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return m } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_TF15enum_resilience33functionWithIndirectResilientEnumFO14resilient_enum16IndirectApproachS1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach { // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum16IndirectApproach() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return ia } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_TF15enum_resilience31constructResilientEnumNoPayloadFT_O14resilient_enum6Medium public func constructResilientEnumNoPayload() -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 0, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Paper } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_TF15enum_resilience29constructResilientEnumPayloadFV16resilient_struct4SizeO14resilient_enum6Medium public func constructResilientEnumPayload(_ s: Size) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium() // CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8*** // CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 -2, %swift.type* [[METADATA2]]) // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Postcard(s) } // CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_TF15enum_resilience19resilientSwitchTestFO14resilient_enum6MediumSi(%swift.opaque* noalias nocapture) // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium() // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* [[ENUM_STORAGE]], %swift.opaque* %0, %swift.type* [[METADATA]]) // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 23 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* [[ENUM_STORAGE]], %swift.type* [[METADATA]]) // CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [ // CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]] // CHECK: i32 0, label %[[PAPER_CASE:.*]] // CHECK: i32 1, label %[[CANVAS_CASE:.*]] // CHECK: ] // CHECK: ; <label>:[[PAPER_CASE]] // CHECK: br label %[[END:.*]] // CHECK: ; <label>:[[CANVAS_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[PAMPHLET_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[DEFAULT_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[END]] // CHECK: ret public func resilientSwitchTest(_ m: Medium) -> Int { switch m { case .Paper: return 1 case .Canvas: return 2 case .Pamphlet(let m): return resilientSwitchTest(m) default: return 3 } } public func reabstraction<T>(_ f: (Medium) -> T) {} // CHECK-LABEL: define{{( protected)?}} swiftcc void @_TF15enum_resilience25resilientEnumPartialApplyFFO14resilient_enum6MediumSiT_(i8*, %swift.refcounted*) public func resilientEnumPartialApply(_ f: (Medium) -> Int) { // CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject // CHECK: call swiftcc void @_TF15enum_resilience13reabstractionurFFO14resilient_enum6MediumxT_(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_TPA__TTRXFo_iO14resilient_enum6Medium_dSi_XFo_iS0__iSi_ to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_TMSi) reabstraction(f) // CHECK: ret void } // CHECK-LABEL: define internal swiftcc void @_TPA__TTRXFo_iO14resilient_enum6Medium_dSi_XFo_iS0__iSi_(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself) // Enums with resilient payloads from a different resilience domain // require runtime metadata instantiation, just like generics. public enum EnumWithResilientPayload { case OneSize(Size) case TwoSizes(Size, Size) } // Make sure we call a function to access metadata of enums with // resilient layout. // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_TF15enum_resilience20getResilientEnumTypeFT_PMP_() // CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO15enum_resilience24EnumWithResilientPayload() // CHECK-NEXT: ret %swift.type* [[METADATA]] public func getResilientEnumType() -> Any.Type { return EnumWithResilientPayload.self } // Public metadata accessor for our resilient enum // CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaO15enum_resilience24EnumWithResilientPayload() // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_TMLO15enum_resilience24EnumWithResilientPayload // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @_TMaO15enum_resilience24EnumWithResilientPayload.once_token, i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*)) // CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @_TMLO15enum_resilience24EnumWithResilientPayload // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ] // CHECK-NEXT: ret %swift.type* [[RESULT]] // Methods inside extensions of resilient enums fish out type parameters // from metadata -- make sure we can do that extension ResilientMultiPayloadGenericEnum { // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_TFE15enum_resilienceO14resilient_enum32ResilientMultiPayloadGenericEnum16getTypeParameterfT_Mx(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself) // CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type** // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 3 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] public func getTypeParameter() -> T.Type { return T.self } } // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
apache-2.0
bff96ba541043486f9662c4e7e9c3edb
46.166667
286
0.663668
3.42747
false
false
false
false
maple1994/RxZhiHuDaily
RxZhiHuDaily/View/MPCircleRefreshView.swift
1
2230
// // MPCircleRefreshView.swift // RxZhiHuDaily // // Created by Maple on 2017/10/14. // Copyright © 2017年 Maple. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif /// 下拉刷新圆圈View class MPCircleRefreshView: UIView { fileprivate let circleLayer = CAShapeLayer() fileprivate let indicatorView = UIActivityIndicatorView() fileprivate let disposeBag = DisposeBag() fileprivate var isRefreshing: Bool = false init() { super.init(frame: CGRect.zero) addSubview(indicatorView) layer.addSublayer(circleLayer) } override func layoutSubviews() { super.layoutSubviews() indicatorView.center = CGPoint(x: frame.width/2, y: frame.height/2) setupLayer() } required init?(coder aDecoder: NSCoder) { fatalError("") } fileprivate func setupLayer() { circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: 8, y: 8), radius: 8, startAngle: CGFloat(Double.pi * 0.5), endAngle: CGFloat(Double.pi * 0.5 + 2 * Double.pi), clockwise: true).cgPath circleLayer.strokeColor = UIColor.white.cgColor circleLayer.fillColor = UIColor.clear.cgColor circleLayer.strokeStart = 0.0 circleLayer.strokeEnd = 0.0 circleLayer.lineWidth = 1.0 circleLayer.lineCap = kCALineCapRound let xy = (frame.width - 16) * 0.5 circleLayer.frame = CGRect(x: xy, y: xy, width: 16, height: 16) } } extension MPCircleRefreshView { /// 设置圆圈的绘制百分比 func pullToRefresh(progress: CGFloat) { circleLayer.isHidden = progress == 0 circleLayer.strokeEnd = progress } /// 开始刷新 func beginRefresh(begin: @escaping () -> Void) { if isRefreshing { //防止刷新未结束又开始请求刷新 return } circleLayer.removeFromSuperlayer() circleLayer.strokeEnd = 0 indicatorView.startAnimating() begin() } /// 结束刷新 func endRefresh() { layer.addSublayer(circleLayer) setupLayer() isRefreshing = false indicatorView.stopAnimating() } }
mit
e0a1b240ea43fe5f80add4e31d4c2710
26.935065
196
0.62901
4.490605
false
false
false
false
acastano/tabs-scrolling-controller
Tabs/Tabs/Extensions/UIViewController+Helpers.swift
1
1718
import UIKit extension UIViewController { func add(_ viewController: UIViewController, to contentView: UIView) { viewController.willMove(toParent: self) addChild(viewController) contentView.addSubview(viewController.view) viewController.view.frame = contentView.bounds viewController.view.translatesAutoresizingMaskIntoConstraints = false viewController.view.pinToSuperviewEdges() viewController.didMove(toParent: self) UIView.performWithoutAnimation { viewController.view.layoutIfNeeded() } } func remove(_ viewController: UIViewController) { viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() } func fadeFromColor(_ fromColor: UIColor, toColor: UIColor, withPercentage: CGFloat) -> UIColor { var fromRed: CGFloat = 0.0 var fromGreen: CGFloat = 0.0 var fromBlue: CGFloat = 0.0 var fromAlpha: CGFloat = 0.0 fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha) var toRed: CGFloat = 0.0 var toGreen: CGFloat = 0.0 var toBlue: CGFloat = 0.0 var toAlpha: CGFloat = 0.0 toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha) let red = (toRed - fromRed) * withPercentage + fromRed let green = (toGreen - fromGreen) * withPercentage + fromGreen let blue = (toBlue - fromBlue) * withPercentage + fromBlue let alpha = (toAlpha - fromAlpha) * withPercentage + fromAlpha return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
apache-2.0
2a9016fad9ae6c21d91312e89390e1c0
29.678571
100
0.656577
4.605898
false
false
false
false
thehung111/ViSearchSwiftSDK
Example/Example/Lib/KRProgressHUD/KRProgressHUD.swift
3
18188
// // KRProgressHUD.swift // KRProgressHUD // // Copyright © 2016年 Krimpedance. All rights reserved. // import UIKit /** Type of KRProgressHUD's background view. - **Clear:** `UIColor.clearColor`. - **White:** `UIColor(white: 1, alpho: 0.2)`. - **Black:** `UIColor(white: 0, alpho: 0.2)`. Default type. */ public enum KRProgressHUDMaskType { case clear, white, black } /** Style of KRProgressHUD. - **Black:** HUD's backgroundColor is `.blackColor()`. HUD's text color is `.whiteColor()`. - **White:** HUD's backgroundColor is `.whiteColor()`. HUD's text color is `.blackColor()`. Default style. - **BlackColor:** same `.Black` and confirmation glyphs become original color. - **WhiteColor:** same `.Black` and confirmation glyphs become original color. */ public enum KRProgressHUDStyle { case black, white, blackColor, whiteColor } /** KRActivityIndicatorView style. (KRProgressHUD uses only large style.) - **Black:** the color is `.blackColor()`. Default style. - **White:** the color is `.blackColor()`. - **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`. */ public enum KRProgressHUDActivityIndicatorStyle { case black, white, color(UIColor, UIColor) } /** * KRProgressHUD is a beautiful and easy-to-use progress HUD. */ public final class KRProgressHUD { fileprivate static let view = KRProgressHUD() class func sharedView() -> KRProgressHUD { return view } fileprivate let window = UIWindow(frame: UIScreen.main.bounds) fileprivate let progressHUDView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) fileprivate let iconView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) fileprivate let activityIndicatorView = KRActivityIndicatorView(position: CGPoint.zero, activityIndicatorStyle: .largeBlack) fileprivate let drawView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) fileprivate let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 20)) fileprivate var tmpWindow: UIWindow? fileprivate var maskType: KRProgressHUDMaskType { willSet { switch newValue { case .clear: window.rootViewController?.view.backgroundColor = UIColor.clear case .white: window.rootViewController?.view.backgroundColor = UIColor(white: 1, alpha: 0.2) case .black: window.rootViewController?.view.backgroundColor = UIColor(white: 0, alpha: 0.2) } } } fileprivate var progressHUDStyle: KRProgressHUDStyle { willSet { switch newValue { case .black, .blackColor: progressHUDView.backgroundColor = UIColor.black messageLabel.textColor = UIColor.white case .white, .whiteColor: progressHUDView.backgroundColor = UIColor.white messageLabel.textColor = UIColor.black } } } fileprivate var activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle { willSet { switch newValue { case .black: activityIndicatorView.activityIndicatorViewStyle = .largeBlack case .white: activityIndicatorView.activityIndicatorViewStyle = .largeWhite case let .color(sc, ec): activityIndicatorView.activityIndicatorViewStyle = .largeColor(sc, ec) } } } fileprivate var defaultStyle: KRProgressHUDStyle = .white { willSet { progressHUDStyle = newValue } } fileprivate var defaultMaskType: KRProgressHUDMaskType = .black { willSet { maskType = newValue } } fileprivate var defaultActivityIndicatorStyle: KRProgressHUDActivityIndicatorStyle = .black { willSet { activityIndicatorStyle = newValue } } fileprivate var defaultMessageFont = UIFont(name: "HiraginoSans-W3", size: 13) ?? UIFont.systemFont(ofSize: 13) { willSet { messageLabel.font = newValue } } fileprivate var defaultPosition: CGPoint = { let screenFrame = UIScreen.main.bounds return CGPoint(x: screenFrame.width/2, y: screenFrame.height/2) }() { willSet { progressHUDView.center = newValue } } public static var isVisible: Bool { return sharedView().window.alpha == 0 ? false : true } fileprivate init() { maskType = .black progressHUDStyle = .white activityIndicatorStyle = .black configureProgressHUDView() } fileprivate func configureProgressHUDView() { let rootViewController = KRProgressHUDViewController() window.rootViewController = rootViewController window.windowLevel = UIWindowLevelNormal window.alpha = 0 progressHUDView.center = defaultPosition progressHUDView.backgroundColor = UIColor.white progressHUDView.layer.cornerRadius = 10 progressHUDView.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] window.rootViewController?.view.addSubview(progressHUDView) iconView.backgroundColor = UIColor.clear iconView.center = CGPoint(x: 50, y: 50) progressHUDView.addSubview(iconView) activityIndicatorView.isHidden = false iconView.addSubview(activityIndicatorView) drawView.backgroundColor = UIColor.clear drawView.isHidden = true iconView.addSubview(drawView) messageLabel.center = CGPoint(x: 150/2, y: 90) messageLabel.backgroundColor = UIColor.clear messageLabel.font = defaultMessageFont messageLabel.textAlignment = .center messageLabel.adjustsFontSizeToFitWidth = true messageLabel.minimumScaleFactor = 0.5 messageLabel.text = nil messageLabel.isHidden = true progressHUDView.addSubview(messageLabel) } } /** * KRProgressHUD Setter -------------------------- */ extension KRProgressHUD { /// Set default mask type. /// - parameter type: `KRProgressHUDMaskType` public class func set(maskType type: KRProgressHUDMaskType) { KRProgressHUD.sharedView().defaultMaskType = type } /// Set default HUD style /// - parameter style: `KRProgressHUDStyle` public class func set(style: KRProgressHUDStyle) { KRProgressHUD.sharedView().defaultStyle = style } /// Set default KRActivityIndicatorView style. /// - parameter style: `KRProgresHUDActivityIndicatorStyle` public class func set(activityIndicatorStyle style: KRProgressHUDActivityIndicatorStyle) { KRProgressHUD.sharedView().defaultActivityIndicatorStyle = style } /// Set default HUD text font. /// - parameter font: text font public class func set(font: UIFont) { KRProgressHUD.sharedView().defaultMessageFont = font } /// Set default HUD center's position. /// - parameter position: center position public class func set(centerPosition position: CGPoint) { KRProgressHUD.sharedView().defaultPosition = position } } /** * KRProgressHUD Show & Dismiss -------------------------- */ extension KRProgressHUD { /** Showing HUD with some args. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message - parameter image: image that Alternative to confirmation glyph. - parameter completion: completion handler. - returns: No return value. */ public class func show( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil, image: UIImage? = nil, completion: (()->())? = nil ) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(image: image) KRProgressHUD.sharedView().show() { completion?() } } /** Showing HUD with success glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showSuccess( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .success) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with information glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showInfo( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .info) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with warning glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showWarning( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .warning) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with error glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showError( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .error) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Dismissing HUD. - parameter completion: handler when dismissed. - returns: No return value */ public class func dismiss(_ completion: (()->())? = nil) { DispatchQueue.main.async { () -> Void in UIView.animate(withDuration: 0.5, animations: { KRProgressHUD.sharedView().window.alpha = 0 }, completion: { _ in KRProgressHUD.sharedView().window.isHidden = true KRProgressHUD.sharedView().tmpWindow?.makeKey() KRProgressHUD.sharedView().activityIndicatorView.stopAnimating() KRProgressHUD.sharedView().progressHUDStyle = KRProgressHUD.sharedView().defaultStyle KRProgressHUD.sharedView().maskType = KRProgressHUD.sharedView().defaultMaskType KRProgressHUD.sharedView().activityIndicatorStyle = KRProgressHUD.sharedView().defaultActivityIndicatorStyle KRProgressHUD.sharedView().messageLabel.font = KRProgressHUD.sharedView().defaultMessageFont completion?() }) } } } /** * KRProgressHUD update during show -------------------------- */ extension KRProgressHUD { public class func update(text: String) { sharedView().messageLabel.text = text } } /** * KRProgressHUD update style method -------------------------- */ private extension KRProgressHUD { func show(_ completion: (()->())? = nil) { DispatchQueue.main.async { () -> Void in self.tmpWindow = UIApplication.shared.keyWindow self.window.alpha = 0 self.window.makeKeyAndVisible() UIView.animate(withDuration: 0.5, animations: { KRProgressHUD.sharedView().window.alpha = 1 }, completion: { _ in completion?() }) } } func updateStyles(progressHUDStyle progressStyle: KRProgressHUDStyle?, maskType type: KRProgressHUDMaskType?, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle?) { if let style = progressStyle { KRProgressHUD.sharedView().progressHUDStyle = style } if let type = type { KRProgressHUD.sharedView().maskType = type } if let style = indicatorStyle { KRProgressHUD.sharedView().activityIndicatorStyle = style } } func updateProgressHUDViewText(font: UIFont?, message: String?) { if let text = message { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 150, height: 110) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 150/2, y: 40) messageLabel.isHidden = false messageLabel.text = text messageLabel.font = font ?? defaultMessageFont } else { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 100, height: 100) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 50, y: 50) messageLabel.isHidden = true } } func updateProgressHUDViewIcon(iconType: KRProgressHUDIconType? = nil, image: UIImage? = nil) { drawView.subviews.forEach { $0.removeFromSuperview() } drawView.layer.sublayers?.forEach { $0.removeFromSuperlayer() } switch (iconType, image) { case (nil, nil): drawView.isHidden = true activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() case let (nil, image): activityIndicatorView.isHidden = true activityIndicatorView.stopAnimating() drawView.isHidden = false let imageView = UIImageView(image: image) imageView.frame = KRProgressHUD.sharedView().drawView.bounds imageView.contentMode = .scaleAspectFit drawView.addSubview(imageView) case let (type, _): drawView.isHidden = false activityIndicatorView.isHidden = true activityIndicatorView.stopAnimating() let pathLayer = CAShapeLayer() pathLayer.frame = drawView.layer.bounds pathLayer.lineWidth = 0 pathLayer.path = type!.getPath() switch progressHUDStyle { case .black: pathLayer.fillColor = UIColor.white.cgColor case .white: pathLayer.fillColor = UIColor.black.cgColor default: pathLayer.fillColor = type!.getColor() } drawView.layer.addSublayer(pathLayer) } } }
mit
9e0dfa8e22f07908d06fe48367870fd0
38.967033
192
0.660929
5.591943
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Main/View/MNDiscoverCell.swift
1
1236
// // MNDiscoverCell.swift // Moon // // Created by YKing on 16/6/11. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNDiscoverCell: UITableViewCell { lazy var squareView: MNDiscoverSquareView = { let sqView = MNDiscoverSquareView.viewFromXib() as! MNDiscoverSquareView self.contentView.addSubview(sqView) return sqView }() lazy var barView: MNDiscoverBarView = { let baView = MNDiscoverBarView.viewFromXib() as! MNDiscoverBarView self.contentView.addSubview(baView) return baView }() var mod: MNModEntity? { didSet { self.squareView.isHidden = true self.barView.isHidden = true if mod?.type == "mashup_square" { self.squareView.mod = mod self.squareView.isHidden = false } else if mod?.type == "mashup_bar" { self.barView.mod = mod self.barView.isHidden = false } } } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = commonBgColor } override func layoutSubviews() { super.layoutSubviews() self.barView.frame = self.bounds self.squareView.frame = CGRect(x: 0, y: 0, width: self.width, height: 455) } }
mit
6b8bcb5210f98ba24ba8bc1218f5e262
22.264151
78
0.64558
3.990291
false
false
false
false
subangstrom/Ronchi
Ronchi/AppDelegate.swift
1
6721
// // AppDelegate.swift // Ronchi // // Created by James LeBeau on 6/12/17. // Copyright © 2017 The Handsome Microscopist. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Ronchi") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error)") } }) return container }() // MARK: - Core Data Saving and Undo support @IBAction func saveAction(_ sender: AnyObject?) { // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. let context = persistentContainer.viewContext if !context.commitEditing() { NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving") } if context.hasChanges { do { try context.save() } catch { // Customize this code block to include application-specific recovery steps. let nserror = error as NSError NSApplication.shared().presentError(nserror) } } } func windowWillReturnUndoManager(window: NSWindow) -> UndoManager? { // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application. return persistentContainer.viewContext.undoManager } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply { // Save changes in the application's managed object context before the application terminates. let context = persistentContainer.viewContext if !context.commitEditing() { NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing to terminate") return .terminateCancel } if !context.hasChanges { return .terminateNow } do { try context.save() } catch { let nserror = error as NSError // Customize this code block to include application-specific recovery steps. let result = sender.presentError(nserror) if (result) { return .terminateCancel } let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") let alert = NSAlert() alert.messageText = question alert.informativeText = info alert.addButton(withTitle: quitButton) alert.addButton(withTitle: cancelButton) let answer = alert.runModal() if answer == NSAlertSecondButtonReturn { return .terminateCancel } } // If we got here, it is time to quit. return .terminateNow } } func defaultsObjectContext()->NSManagedObjectContext{ // First load the Data Model // `momd` is important //This resource is the same name as your xcdatamodeld contained in your project guard let modelURL = Bundle.main.url(forResource: "Document", withExtension:"momd") else { fatalError("Error loading model from bundle") } // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) let moc = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType) moc.persistentStoreCoordinator = psc moc.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy let docURL = NSPersistentContainer.defaultDirectoryURL() let storeURL = docURL.appendingPathComponent( "UserDefaults.sqlite") let options = [NSSQLitePragmasOption:["journal_mode":"DELETE"]]; do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) //The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from. } catch { fatalError("Error migrating store: \(error)") } return moc }
gpl-3.0
4c28311b9807904f55bec97ef7f9761c
39.97561
228
0.650446
5.763293
false
false
false
false
brentdax/swift
stdlib/public/core/StringComparable.swift
4
5289
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims extension _StringGuts { @inline(__always) @inlinable public func _bitwiseEqualTo(_ other: _StringGuts) -> Bool { return self.rawBits == other.rawBits } @inlinable internal static func isEqual( _ left: _StringGuts, to right: _StringGuts ) -> Bool { // Bitwise equality implies string equality if left._bitwiseEqualTo(right) { return true } if left._isSmall && right._isSmall { // TODO: Ensure normality when adding UTF-8 support _sanityCheck(left._isASCIIOrSmallASCII && right._isASCIIOrSmallASCII, "Need to ensure normality") // Equal small strings should be bitwise equal if ASCII return false } return compare(left, to: right) == 0 } @inlinable internal static func isEqual( _ left: _StringGuts, _ leftRange: Range<Int>, to right: _StringGuts, _ rightRange: Range<Int> ) -> Bool { // Bitwise equality implies string equality if left._bitwiseEqualTo(right) && leftRange == rightRange { return true } return compare(left, leftRange, to: right, rightRange) == 0 } @inlinable internal static func isLess( _ left: _StringGuts, than right: _StringGuts ) -> Bool { // Bitwise equality implies string equality if left._bitwiseEqualTo(right) { return false } if left._isSmall && right._isSmall { // Small strings compare lexicographically if ASCII return left._smallUTF8String._compare(right._smallUTF8String) == .less } return compare(left, to: right) == -1 } @inlinable internal static func isLess( _ left: _StringGuts, _ leftRange: Range<Int>, than right: _StringGuts, _ rightRange: Range<Int> ) -> Bool { // Bitwise equality implies string equality if left._bitwiseEqualTo(right) && leftRange == rightRange { return false } return compare(left, leftRange, to: right, rightRange) == -1 } @inlinable internal static func compare( _ left: _StringGuts, _ leftRange: Range<Int>, to right: _StringGuts, _ rightRange: Range<Int> ) -> Int { defer { _fixLifetime(left) } defer { _fixLifetime(right) } if left.isASCII && right.isASCII { let leftASCII = left._unmanagedASCIIView[leftRange] let rightASCII = right._unmanagedASCIIView[rightRange] let result = leftASCII.compareASCII(to: rightASCII) return result } let leftBits = left.rawBits let rightBits = right.rawBits return _compareUnicode(leftBits, leftRange, rightBits, rightRange) } @inlinable internal static func compare( _ left: _StringGuts, to right: _StringGuts ) -> Int { defer { _fixLifetime(left) } defer { _fixLifetime(right) } if left.isASCII && right.isASCII { let leftASCII = left._unmanagedASCIIView let rightASCII = right._unmanagedASCIIView let result = leftASCII.compareASCII(to: rightASCII) return result } let leftBits = left.rawBits let rightBits = right.rawBits return _compareUnicode(leftBits, rightBits) } } extension StringProtocol { @inlinable // FIXME(sil-serialize-all) public static func ==<S: StringProtocol>(lhs: Self, rhs: S) -> Bool { return _StringGuts.isEqual( lhs._wholeString._guts, lhs._encodedOffsetRange, to: rhs._wholeString._guts, rhs._encodedOffsetRange) } @inlinable // FIXME(sil-serialize-all) public static func !=<S: StringProtocol>(lhs: Self, rhs: S) -> Bool { return !(lhs == rhs) } @inlinable // FIXME(sil-serialize-all) public static func < <R: StringProtocol>(lhs: Self, rhs: R) -> Bool { return _StringGuts.isLess( lhs._wholeString._guts, lhs._encodedOffsetRange, than: rhs._wholeString._guts, rhs._encodedOffsetRange) } @inlinable // FIXME(sil-serialize-all) public static func > <R: StringProtocol>(lhs: Self, rhs: R) -> Bool { return rhs < lhs } @inlinable // FIXME(sil-serialize-all) public static func <= <R: StringProtocol>(lhs: Self, rhs: R) -> Bool { return !(rhs < lhs) } @inlinable // FIXME(sil-serialize-all) public static func >= <R: StringProtocol>(lhs: Self, rhs: R) -> Bool { return !(lhs < rhs) } } extension String : Equatable { // FIXME: Why do I need this? If I drop it, I get "ambiguous use of operator" @inlinable // FIXME(sil-serialize-all) public static func ==(lhs: String, rhs: String) -> Bool { return _StringGuts.isEqual(lhs._guts, to: rhs._guts) } } extension String : Comparable { // FIXME: Why do I need this? If I drop it, I get "ambiguous use of operator" @inlinable // FIXME(sil-serialize-all) public static func < (lhs: String, rhs: String) -> Bool { return _StringGuts.isLess(lhs._guts, than: rhs._guts) } } extension Substring : Equatable {}
apache-2.0
7a32d5ab5ce41ba1a257cd61f9a8c100
29.396552
80
0.644167
4.081019
false
false
false
false
blitzagency/events
Events/Channels/Drivers/WatchKitChannelDriver.swift
1
5003
// // WatchKitChannelDriver.swift // Events // // Created by Adam Venturella on 7/29/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation import Foundation import WatchConnectivity #if TEST typealias WatchSessionType = MockWCSession #else typealias WatchSessionType = WCSession #endif @available(iOS 9.0, watchOS 2.0, *) @objc public class WatchKitChannelDriver: NSObject, WCSessionDelegate, ChannelDriver{ static var _driver: WatchKitChannelDriver? var _session: WatchSessionType? public var channels = [String: WatchKitChannel]() public static func driver() -> WatchKitChannelDriver{ if let driver = _driver{ return driver } let driver = WatchKitChannelDriver() _driver = driver return driver } override public init(){ super.init() initSession() } func initSession(){ // the session is always available on watchOS if WatchSessionType.isSupported(){ let defaultSession = WatchSessionType.default() as! WatchSessionType defaultSession.delegate = self defaultSession.activate() _session = defaultSession } } public func get<Label: RawRepresentable>(_ key: Label) -> WatchKitChannel where Label.RawValue == String { return get(key.rawValue) } public func get(_ key: String = "default") -> WatchKitChannel{ if let channel = channels[key]{ print("Got Existing Key: '\(key)'") return channel } print("Creating new channel: '\(key)'") let channel = WatchKitChannel(label: key, driver: self) channels[key] = channel return channel } @available(iOSApplicationExtension 9.3, *) public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){ } @available(iOS 9.3, *) public func sessionDidBecomeInactive(_ session: WCSession){ } @available(iOS 9.3, *) public func sessionDidDeactivate(_ session: WCSession){ } public func send(_ payload:[String: Any]){ // data has to be AnyObject to be serialized guard let session = _session, session.isReachable else { print("No Session or session is not reachable") return } session.sendMessage(payload, replyHandler: nil, errorHandler: nil) } public func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { guard let channelLabel = message["channel"] as? String else { fatalError("No channel label provided") } guard let channel = channels[channelLabel] else { return } guard let event = message["event"] as? String else { fatalError("Message received without a key: 'event' or that value was not convertible to a String") } if let request = message["request"] as? [String: AnyObject] { handleRequest(channel, event: event, message: message, request: request) } else { handleEvent(channel, event: event, message: message) } } func handleRequest(_ channel: WatchKitChannel, event: String, message: [String: Any], request: [String: Any]){ let args = request["args"] as? [Any] let argCount = args?.count ?? 0 // cast the channel to EventManagerHost // so we don't end up in an infinite loop. // We want to call trigger() on the EventManagerHost so it // doesn't try to send the data over the WCSession switch argCount{ case 0: let args = deserializeWatchKitRequestEventNoArgs(request) let event = buildEvent(event, publisher: channel, data: args) (channel as EventManagerHost).trigger(event) case 1: let args = deserializeWatchKitRequestEventArgs1(request) let event = buildEvent(event, publisher: channel, data: args) (channel as EventManagerHost).trigger(event) case 2: let args = deserializeWatchKitRequestEventArgs2(request) let event = buildEvent(event, publisher: channel, data: args) (channel as EventManagerHost).trigger(event) case 3: let args = deserializeWatchKitRequestEventArgs3(request) let event = buildEvent(event, publisher: channel, data: args) (channel as EventManagerHost).trigger(event) default: fatalError("Unable to handle argument count '\(argCount)'") } } func handleEvent(_ channel: WatchKitChannel, event: String, message: [String: Any]){ if let data = message["data"]{ let event = buildEvent(event, publisher: channel, data: data) (channel as EventManagerHost).trigger(event) } else { (channel as EventManagerHost).trigger(event) } } }
mit
8a512fdcd5bacb3930006afb3ff3401c
29.315152
130
0.626349
4.795781
false
false
false
false
cpimhoff/AntlerKit
Framework/AntlerKit/Scene/SceneStack.swift
1
2682
// // SceneStack.swift // AntlerKit // // Created by Charlie Imhoff on 1/18/17. // Copyright © 2017 Charlie Imhoff. All rights reserved. // import Foundation import SpriteKit public extension Scene { /// Adds the scene to the top of the scene stack and transitions to it /// /// - Parameters: /// - nextScene: The Scene to enter /// - transition: The transition to use between the scenes public func push(_ nextScene: Scene, using transition: SKTransition? = nil) { guard let renderer = self.root.view else { return } SceneStack.shared.push(nextScene, on: renderer, with: transition) } /// Removes this scene from the scene stack and transitions to the scene below /// /// - Note: The scene stack must have a scene below this one /// - Parameter transition: The transition to use between the scenes public func pop(using transition: SKTransition? = nil) { guard let renderer = self.root.view else { return } SceneStack.shared.pop(from: renderer, with: transition) } /// Swaps this scene with another and transitions to it. Doesn't affect the scene stack below. /// /// - Parameters: /// - scene: The Scene to enter /// - transition: The transition to use between the scenes public func swap(to scene: Scene, using transition: SKTransition? = nil) { guard let renderer = self.root.view else { return } SceneStack.shared.swap(to: scene, on: renderer, with: transition) } } internal class SceneStack { static var shared = SceneStack() private var scenes = [Scene]() var head : Scene! { return scenes.last } var height : Int { return scenes.count } func push(_ scene: Scene, on view: SKView, with transition: SKTransition? = nil) { scenes.append(scene) self.transition(to: scene, on: view, with: transition) } func pop(from view: SKView, with transition: SKTransition? = nil) { guard self.height > 1 else { fatalError("Attempted to pop a scene off the scene stack when there is only one scene remaining") } scenes.removeLast() let revealed = scenes.last! self.transition(to: revealed, on: view, with: transition) } func swap(to scene: Scene, on view: SKView, with transition: SKTransition? = nil) { scenes.removeLast() self.push(scene, on: view, with: transition) } func swapEntire(toNewBase scene: Scene, on view: SKView, with transition: SKTransition? = nil) { scenes.removeAll() self.push(scene, on: view, with: transition) } private func transition(to scene: Scene, on view: SKView, with transition: SKTransition?) { if transition != nil { view.presentScene(scene.root, transition: transition!) } else { view.presentScene(scene.root) } } }
mit
44124f575c4033dca25fc57a35a163c6
27.521277
100
0.696382
3.536939
false
false
false
false
drmohundro/Nimble
Nimble/Matchers/BeAnInstanceOf.swift
1
990
import Foundation public func beAnInstanceOf(expectedClass: AnyClass) -> MatcherFunc<NSObject?> { return MatcherFunc { actualExpression, failureMessage in let instance = actualExpression.evaluate() if let validInstance = instance { failureMessage.actualValue = "<\(NSStringFromClass(validInstance.dynamicType)) instance>" } else { failureMessage.actualValue = "<nil>" } failureMessage.postfixMessage = "be an instance of \(NSStringFromClass(expectedClass))" return instance.hasValue && instance!.isMemberOfClass(expectedClass) } } extension NMBObjCMatcher { public class func beAnInstanceOfMatcher(expected: AnyClass) -> NMBMatcher { return NMBObjCMatcher { actualExpression, failureMessage, location in let expr = Expression(expression: actualExpression, location: location) return beAnInstanceOf(expected).matches(expr, failureMessage: failureMessage) } } }
apache-2.0
d343690600bedb660dcfa2c912d2de57
42.043478
101
0.70404
5.689655
false
false
false
false
sschiau/swift
test/SILGen/unmanaged.swift
2
2483
// RUN: %target-swift-emit-sil -module-name unmanaged %s | %FileCheck %s class C {} struct Holder { unowned(unsafe) var value: C } _ = Holder(value: C()) // CHECK-LABEL:sil hidden @$s9unmanaged6HolderV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned C, @thin Holder.Type) -> Holder // CHECK: bb0([[T0:%.*]] : $C, // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C // CHECK-NEXT: strong_release [[T0]] : $C // CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C) // CHECK-NEXT: return [[T2]] : $Holder func set(holder holder: inout Holder) { holder.value = C() } // CHECK-LABEL:sil hidden @$s9unmanaged3set6holderyAA6HolderVz_tF : $@convention(thin) (@inout Holder) -> () // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK: [[T0:%.*]] = function_ref @$s9unmanaged1CC{{[_0-9a-zA-Z]*}}fC // CHECK: [[C:%.*]] = apply [[T0]]( // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[ADDR]] : $*Holder // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[WRITE]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]] // CHECK-NEXT: store [[T1]] to [[T0]] // CHECK-NEXT: strong_release [[C]] // CHECK-NEXT: end_access [[WRITE]] : $*Holder // CHECK-NEXT: tuple () // CHECK-NEXT: return func get(holder holder: inout Holder) -> C { return holder.value } // CHECK-LABEL:sil hidden @$s9unmanaged3get6holderAA1CCAA6HolderVz_tF : $@convention(thin) (@inout Holder) -> @owned C // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK-NEXT: debug_value_addr %0 : $*Holder, var, name "holder", argno 1 // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [static] [[ADDR]] : $*Holder // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[READ]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*@sil_unmanaged C // CHECK-NEXT: [[T2:%.*]] = copy_unmanaged_value [[T1]] // CHECK-NEXT: end_access [[READ]] : $*Holder // CHECK-NEXT: return [[T2]] func project(fn fn: () -> Holder) -> C { return fn().value } // CHECK-LABEL: sil hidden @$s9unmanaged7project2fnAA1CCAA6HolderVyXE_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Holder) -> @owned C // CHECK: bb0([[FN:%.*]] : $@noescape @callee_guaranteed () -> Holder): // CHECK-NEXT: debug_value // CHECK-NEXT: [[T0:%.*]] = apply [[FN]]() // CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value // CHECK-NEXT: [[T2:%.*]] = copy_unmanaged_value [[T1]] // CHECK-NEXT: return [[T2]]
apache-2.0
f23b493fc0a0f040a23c096b187c05f4
44.145455
149
0.590415
2.938462
false
false
false
false
pisarm/Gojira
Gojira WatchKit Extension/Source/Services/Jira.swift
1
2680
// // JiraService.swift // Gojira // // Created by Flemming Pedersen on 24/10/15. // Copyright © 2015 pisarm.dk. All rights reserved. // import Foundation enum EndPointType { case Favourite case Search(String) func urlString() -> String { switch self { case .Favourite: return "/filter/favourite" case let .Search(jql): return "/search?jql=\(jql)" } } } struct EndPoint { let baseURL: String let type: EndPointType func endPointURL() -> NSURL? { let urlString = baseURL + "/rest/api/2" + type.urlString() guard let encodedURLString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()), url = NSURL(string: encodedURLString) else { return nil } return url } } struct BasicAuth { let username: String let password: String func authValue() -> String? { guard let dataToEncode = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return nil } return "Basic \(dataToEncode.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)))" } } private enum HTTPHeaderField: String { case Authorization } final class Jira { private var session: NSURLSessionDataTask? //MARK: Fetch func fetchFilterData(baseURL: String, basicAuth: BasicAuth, completion: (data: NSData?) -> Void) { guard let url = EndPoint(baseURL: baseURL, type: .Favourite).endPointURL(), authValue = basicAuth.authValue() else { completion(data: nil) return } fetch(url, authValue: authValue, completion: completion) } func fetchTotalData(jql: String, baseURL: String, basicAuth: BasicAuth, completion: (data: NSData?) -> Void) { guard let url = EndPoint(baseURL: baseURL, type: .Search(jql)).endPointURL(), authValue = basicAuth.authValue() else { completion(data: nil) return } fetch(url, authValue: authValue, completion: completion) } //MARK: Internal private func fetch(url: NSURL, authValue: String, completion: (data: NSData?) -> Void) { let request = NSMutableURLRequest(URL: url) request.addValue(authValue, forHTTPHeaderField: HTTPHeaderField.Authorization.rawValue) session?.cancel() session = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, _, _ in completion(data: data) } session?.resume() } }
mit
e490c6bf56e4dd1296bf73e754e8b062
26.336735
130
0.612169
4.683566
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/PWM Oscillator Bank.xcplaygroundpage/Contents.swift
1
2517
//: ## PWM Oscillator Bank import XCPlayground import AudioKit let osc = AKPWMOscillatorBank(pulseWidth: 0.5) AudioKit.output = osc AudioKit.start() class PlaygroundView: AKPlaygroundView, AKKeyboardDelegate { var keyboard: AKKeyboardView? override func setup() { addTitle("PWM Oscillator Bank") addSubview(AKPropertySlider( property: "Pulse Width", value: osc.pulseWidth, color: AKColor.redColor() ) { amount in osc.pulseWidth = amount }) addSubview(AKPropertySlider( property: "Attack", format: "%0.3f s", value: osc.attackDuration, maximum: 2, color: AKColor.greenColor() ) { duration in osc.attackDuration = duration }) addSubview(AKPropertySlider( property: "Release", format: "%0.3f s", value: osc.releaseDuration, maximum: 2, color: AKColor.greenColor() ) { duration in osc.releaseDuration = duration }) addSubview(AKPropertySlider( property: "Detuning Offset", format: "%0.1f Cents", value: osc.releaseDuration, minimum: -100, maximum: 100, color: AKColor.greenColor() ) { offset in osc.detuningOffset = offset }) addSubview(AKPropertySlider( property: "Detuning Multiplier", value: osc.detuningMultiplier, minimum: 0.5, maximum: 2.0, color: AKColor.greenColor() ) { multiplier in osc.detuningMultiplier = multiplier }) keyboard = AKKeyboardView(width: 440, height: 100, firstOctave: 3, octaveCount: 3) keyboard!.polyphonicMode = false keyboard!.delegate = self addSubview(keyboard!) addSubview(AKButton(title: "Go Polyphonic") { self.keyboard?.polyphonicMode = !self.keyboard!.polyphonicMode if self.keyboard!.polyphonicMode { return "Go Monophonic" } else { return "Go Polyphonic" } }) } func noteOn(note: MIDINoteNumber) { osc.play(noteNumber: note, velocity: 80) } func noteOff(note: MIDINoteNumber) { osc.stop(noteNumber: note) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
02c678b6781efb32573b79dfdc3826fc
27.280899
74
0.570918
4.984158
false
false
false
false
PhamBaTho/BTNavigationDropdownMenu
Demo/Demo/ViewController.swift
1
2407
// // ViewController.swift // BTNavigationDropdownMenu // // Created by Pham Ba Tho on 6/8/15. // Copyright (c) 2015 PHAM BA THO. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var selectedCellLabel: UILabel! var menuView: BTNavigationDropdownMenu! override func viewDidLoad() { super.viewDidLoad() let items = ["Most Popular", "Latest", "Trending", "Nearest", "Top Picks"] self.selectedCellLabel.text = items.first self.navigationController?.navigationBar.isTranslucent = false self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.0/255.0, green:180/255.0, blue:220/255.0, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] // "Old" version // menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: "Dropdown Menu", items: items) menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: BTTitle.index(2), items: items) // Another way to initialize: // menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: BTTitle.title("Dropdown Menu"), items: items) menuView.cellHeight = 50 menuView.cellBackgroundColor = self.navigationController?.navigationBar.barTintColor menuView.cellSelectionColor = UIColor(red: 0.0/255.0, green:160.0/255.0, blue:195.0/255.0, alpha: 1.0) menuView.shouldKeepSelectedCellColor = true menuView.cellTextLabelColor = UIColor.white menuView.cellTextLabelFont = UIFont(name: "Avenir-Heavy", size: 17) menuView.cellTextLabelAlignment = .left // .Center // .Right // .Left menuView.arrowPadding = 15 menuView.animationDuration = 0.5 menuView.maskBackgroundColor = UIColor.black menuView.maskBackgroundOpacity = 0.3 menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> Void in print("Did select item at index: \(indexPath)") self.selectedCellLabel.text = items[indexPath] } self.navigationItem.titleView = menuView } }
mit
084b059080ffc83d1ec57fb653e9ee78
47.14
196
0.709597
4.843058
false
false
false
false
lewis-smith/Unobtrusive
UnobtrusiveDemo/UnobtrusiveDemo/AppDelegate.swift
1
3340
// // AppDelegate.swift // UnobtrusivePrompt // // Created by Lewis Smith on 18/01/2017. // Copyright © 2017 Lewis Makes Apps. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
217b918d10dc0f23492ba042d35c8bb5
53.737705
285
0.762204
6.183333
false
false
false
false
davedelong/DDMathParser
MathParser/Sources/MathParser/Functions+Defaults.swift
1
44894
// // StandardFunctions.swift // DDMathParser // // Created by Dave DeLong on 8/20/15. // // import Foundation extension Function { // MARK: - Angle mode helpers internal static func _dtor(_ d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .degrees else { return d } return d / 180 * Double.pi } internal static func _rtod(_ d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .degrees else { return d } return d / Double.pi * 180 } public static let standardFunctions: Array<Function> = [ add, subtract, multiply, divide, mod, negate, factorial, factorial2, pow, sqrt, cuberoot, nthroot, random, abs, percent, log, ln, log2, exp, and, or, not, xor, lshift, rshift, sum, product, count, min, max, average, median, stddev, ceil, floor, sin, cos, tan, asin, acos, atan, atan2, csc, sec, cotan, acsc, asec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, csch, sech, cotanh, acsch, asech, acotanh, versin, vercosin, coversin, covercosin, haversin, havercosin, hacoversin, hacovercosin, exsec, excsc, crd, dtor, rtod, `true`, `false`, phi, pi, pi_2, pi_4, tau, sqrt2, e, log2e, log10e, ln2, ln10, l_and, l_or, l_not, l_eq, l_neq, l_lt, l_gt, l_ltoe, l_gtoe, l_if ] // MARK: - Basic functions public static let add = Function(name: "add", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return arg1 + arg2 }) public static let subtract = Function(name: "subtract", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return arg1 - arg2 }) public static let multiply = Function(names: ["multiply", "implicitmultiply"], evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return arg1 * arg2 }) public static let divide = Function(name: "divide", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) guard arg2 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return arg1 / arg2 }) public static let mod = Function(names: ["mod", "modulo"], evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return fmod(arg1, arg2) }) public static let negate = Function(name: "negate", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return -arg1 }) public static let factorial = Function(name: "factorial", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return arg1.factorial() }) public static let factorial2 = Function(name: "factorial2", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 >= 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } guard arg1 == Darwin.floor(arg1) else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } if arg1.truncatingRemainder(dividingBy: 2) == 0 { let k = arg1 / 2 return Darwin.pow(2, k) * k.factorial() } else { let k = (arg1 + 1) / 2 let numerator = (2*k).factorial() let denominator = Darwin.pow(2, k) * k.factorial() guard denominator != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return numerator / denominator } }) public static let pow = Function(name: "pow", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Darwin.pow(arg1, arg2) }) public static let sqrt = Function(name: "sqrt", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let value = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.sqrt(value) }) public static let cuberoot = Function(name: "cuberoot", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) if arg1 < 0 { let root = Darwin.pow(-arg1, 1.0/3.0) return -root } else { return Darwin.pow(arg1, 1.0/3.0) } }) public static let nthroot = Function(name: "nthroot", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) guard arg2 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } if arg1 < 0 && arg2.truncatingRemainder(dividingBy: 2) == 1 { // for negative numbers with an odd root, the result will be negative let root = Darwin.pow(-arg1, 1/arg2) return -root } else { return Darwin.pow(arg1, 1/arg2) } }) public static let random = Function(name: "random", evaluator: { state throws -> Double in guard state.arguments.count <= 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var argValues = Array<Double>() for arg in state.arguments { let argValue = try state.evaluator.evaluate(arg, substitutions: state.substitutions) argValues.append(argValue) } var lowerBound = 0.0 var upperBound = 1.0 switch argValues.count { case 1: upperBound = argValues[0] case 2: lowerBound = argValues[0] upperBound = argValues[1] default: break } guard lowerBound < upperBound else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let range = upperBound - lowerBound return drand48() * range + lowerBound }) public static let log = Function(name: "log", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.log10(arg1) }) public static let ln = Function(name: "ln", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.log(arg1) }) public static let log2 = Function(name: "log2", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.log2(arg1) }) public static let exp = Function(name: "exp", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.exp(arg1) }) public static let abs = Function(name: "abs", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Swift.abs(arg1) }) public static let percent = Function(name: "percent", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let percentArgument = state.arguments[0] let percentValue = try state.evaluator.evaluate(percentArgument, substitutions: state.substitutions) let percent = percentValue / 100 let percentExpression = percentArgument.parent let percentContext = percentExpression?.parent guard let contextKind = percentContext?.kind else { return percent } guard case let .function(f, contextArgs) = contextKind else { return percent } // must be XXXX + n% or XXXX - n% guard let builtIn = BuiltInOperator(rawValue: f), builtIn == .add || builtIn == .minus else { return percent } // cannot be n% + XXXX or n% - XXXX guard contextArgs[1] === percentExpression else { return percent } let context = try state.evaluator.evaluate(contextArgs[0], substitutions: state.substitutions) return context * percent }) // MARK: - Bitwise functions public static let and = Function(name: "and", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Double(Int(arg1) & Int(arg2)) }) public static let or = Function(name: "or", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Double(Int(arg1) | Int(arg2)) }) public static let not = Function(name: "not", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Double(~Int(arg1)) }) public static let xor = Function(name: "xor", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Double(Int(arg1) ^ Int(arg2)) }) public static let rshift = Function(name: "rshift", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Double(Int(arg1) >> Int(arg2)) }) public static let lshift = Function(name: "lshift", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Double(Int(arg1) << Int(arg2)) }) // MARK: - Aggregate functions public static let average = Function(names: ["average", "avg", "mean"], evaluator: { state throws -> Double in guard state.arguments.count > 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let value = try sum.evaluator(state) return value / Double(state.arguments.count) }) public static let sum = Function(names: ["sum", "∑"], evaluator: { state throws -> Double in guard state.arguments.count > 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var value = 0.0 for arg in state.arguments { value += try state.evaluator.evaluate(arg, substitutions: state.substitutions) } return value }) public static let product = Function(names: ["product", "∏"], evaluator: { state throws -> Double in guard state.arguments.count > 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var value = 1.0 for arg in state.arguments { value *= try state.evaluator.evaluate(arg, substitutions: state.substitutions) } return value }) public static let count = Function(name: "count", evaluator: { state throws -> Double in return Double(state.arguments.count) }) public static let min = Function(name: "min", evaluator: { state throws -> Double in guard state.arguments.count > 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var value = Double.greatestFiniteMagnitude for arg in state.arguments { let argValue = try state.evaluator.evaluate(arg, substitutions: state.substitutions) value = Swift.min(value, argValue) } return value }) public static let max = Function(name: "max", evaluator: { state throws -> Double in guard state.arguments.count > 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var value = Double.leastNormalMagnitude for arg in state.arguments { let argValue = try state.evaluator.evaluate(arg, substitutions: state.substitutions) value = Swift.max(value, argValue) } return value }) public static let median = Function(name: "median", evaluator: { state throws -> Double in guard state.arguments.count >= 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } var evaluated = Array<Double>() for arg in state.arguments { evaluated.append(try state.evaluator.evaluate(arg, substitutions: state.substitutions)) } if evaluated.count % 2 == 1 { let index = evaluated.count / 2 return evaluated[index] } else { let highIndex = evaluated.count / 2 let lowIndex = highIndex - 1 return Double((evaluated[highIndex] + evaluated[lowIndex]) / 2) } }) public static let stddev = Function(name: "stddev", evaluator: { state throws -> Double in guard state.arguments.count >= 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let avg = try average.evaluator(state) var stddev = 0.0 for arg in state.arguments { let value = try state.evaluator.evaluate(arg, substitutions: state.substitutions) let diff = avg - value stddev += (diff * diff) } return Darwin.sqrt(stddev / Double(state.arguments.count)) }) public static let ceil = Function(name: "ceil", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.ceil(arg1) }) public static let floor = Function(names: ["floor", "trunc"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.floor(arg1) }) // MARK: - Trigonometric functions public static let sin = Function(name: "sin", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let cos = Function(name: "cos", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.cos(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let tan = Function(name: "tan", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.tan(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let asin = Function(names: ["asin", "sin⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Function._rtod(Darwin.asin(arg1), evaluator: state.evaluator) }) public static let acos = Function(names: ["acos", "cos⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Function._rtod(Darwin.acos(arg1), evaluator: state.evaluator) }) public static let atan = Function(names: ["atan", "tan⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Function._rtod(Darwin.atan(arg1), evaluator: state.evaluator) }) public static let atan2 = Function(name: "atan2", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return Function._rtod(Darwin.atan2(arg1, arg2), evaluator: state.evaluator) }) public static let csc = Function(name: "csc", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator)) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let sec = Function(name: "sec", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.cos(Function._dtor(arg1, evaluator: state.evaluator)) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let cotan = Function(name: "cotan", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.tan(Function._dtor(arg1, evaluator: state.evaluator)) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let acsc = Function(names: ["acsc", "csc⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Function._rtod(Darwin.asin(1.0 / arg1), evaluator: state.evaluator) }) public static let asec = Function(names: ["asec", "sec⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Function._rtod(Darwin.acos(1.0 / arg1), evaluator: state.evaluator) }) public static let acotan = Function(names: ["acotan", "cotan⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Function._rtod(Darwin.atan(1.0 / arg1), evaluator: state.evaluator) }) // MARK: - Hyperbolic trigonometric functions public static let sinh = Function(name: "sinh", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.sinh(arg1) }) public static let cosh = Function(name: "cosh", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.cosh(arg1) }) public static let tanh = Function(name: "tanh", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.tanh(arg1) }) public static let asinh = Function(names: ["asinh", "sinh⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.asinh(arg1) }) public static let acosh = Function(names: ["acosh", "cosh⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.acosh(arg1) }) public static let atanh = Function(names: ["atanh", "tanh⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return Darwin.atanh(arg1) }) public static let csch = Function(name: "csch", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.sinh(arg1) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let sech = Function(name: "sech", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.cosh(arg1) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let cotanh = Function(name: "cotanh", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg = Darwin.tanh(arg1) guard sinArg != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return 1.0 / sinArg }) public static let acsch = Function(names: ["acsch", "csch⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Darwin.asinh(1.0 / arg1) }) public static let asech = Function(names: ["asech", "sech⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Darwin.acosh(1.0 / arg1) }) public static let acotanh = Function(names: ["acotanh", "cotanh⁻¹"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) guard arg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return Darwin.atanh(1.0 / arg1) }) // MARK: - Geometric functions public static let versin = Function(names: ["versin", "vers", "ver"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return 1.0 - Darwin.cos(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let vercosin = Function(names: ["vercosin", "vercos"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return 1.0 + Darwin.cos(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let coversin = Function(names: ["coversin", "cvs"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return 1.0 - Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let covercosin = Function(name: "covercosin", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return 1.0 + Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator)) }) public static let haversin = Function(name: "haversin", evaluator: { state throws -> Double in return try versin.evaluator(state) / 2.0 }) public static let havercosin = Function(name: "havercosin", evaluator: { state throws -> Double in return try vercosin.evaluator(state) / 2.0 }) public static let hacoversin = Function(name: "hacoversin", evaluator: { state throws -> Double in return try coversin.evaluator(state) / 2.0 }) public static let hacovercosin = Function(name: "hacovercosin", evaluator: { state throws -> Double in return try covercosin.evaluator(state) / 2.0 }) public static let exsec = Function(name: "exsec", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let cosArg1 = Darwin.cos(Function._dtor(arg1, evaluator: state.evaluator)) guard cosArg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return (1.0/cosArg1) - 1.0 }) public static let excsc = Function(name: "excsc", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator)) guard sinArg1 != 0 else { throw MathParserError(kind: .divideByZero, range: state.expressionRange) } return (1.0/sinArg1) - 1.0 }) public static let crd = Function(names: ["crd", "chord"], evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: state.evaluator) / 2.0) return 2 * sinArg1 }) public static let dtor = Function(name: "dtor", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return arg1 / 180.0 * Double.pi }) public static let rtod = Function(name: "rtod", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return arg1 / Double.pi * 180 }) // MARK: - Constant functions public static let `true` = Function(names: ["true", "yes"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return 1.0 }) public static let `false` = Function(names: ["false", "no"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return 0.0 }) public static let phi = Function(names: ["phi", "ϕ"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return 1.6180339887498948 }) public static let pi = Function(names: ["pi", "π", "tau_2"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return Double.pi }) public static let pi_2 = Function(names: ["pi_2", "tau_4"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return Double.pi / 2 }) public static let pi_4 = Function(names: ["pi_4", "tau_8"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return Double.pi / 4 }) public static let tau = Function(names: ["tau", "τ"], evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return 2 * Double.pi }) public static let sqrt2 = Function(name: "sqrt2", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return 2.squareRoot() }) public static let e = Function(name: "e", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return M_E }) public static let log2e = Function(name: "log2e", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return M_LOG2E }) public static let log10e = Function(name: "log10e", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return M_LOG10E }) public static let ln2 = Function(name: "ln2", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return M_LN2 }) public static let ln10 = Function(name: "ln10", evaluator: { state throws -> Double in guard state.arguments.count == 0 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } return M_LN10 }) // MARK: - Logical Functions public static let l_and = Function(name: "l_and", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 != 0 && arg2 != 0) ? 1.0 : 0.0 }) public static let l_or = Function(name: "l_or", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 != 0 || arg2 != 0) ? 1.0 : 0.0 }) public static let l_not = Function(name: "l_not", evaluator: { state throws -> Double in guard state.arguments.count == 1 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) return (arg1 == 0) ? 1.0 : 0.0 }) public static let l_eq = Function(name: "l_eq", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 == arg2) ? 1.0 : 0.0 }) public static let l_neq = Function(name: "l_neq", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 != arg2) ? 1.0 : 0.0 }) public static let l_lt = Function(name: "l_lt", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 < arg2) ? 1.0 : 0.0 }) public static let l_gt = Function(name: "l_gt", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 > arg2) ? 1.0 : 0.0 }) public static let l_ltoe = Function(name: "l_ltoe", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 <= arg2) ? 1.0 : 0.0 }) public static let l_gtoe = Function(name: "l_gtoe", evaluator: { state throws -> Double in guard state.arguments.count == 2 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) let arg2 = try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) return (arg1 >= arg2) ? 1.0 : 0.0 }) public static let l_if = Function(names: ["l_if", "if"], evaluator: { state throws -> Double in guard state.arguments.count == 3 else { throw MathParserError(kind: .invalidArguments, range: state.expressionRange) } let arg1 = try state.evaluator.evaluate(state.arguments[0], substitutions: state.substitutions) if arg1 != 0 { return try state.evaluator.evaluate(state.arguments[1], substitutions: state.substitutions) } else { return try state.evaluator.evaluate(state.arguments[2], substitutions: state.substitutions) } }) }
mit
b4fa9985460239cb7667e5408d77d1d7
51.518735
126
0.66081
4.276411
false
false
false
false
yangxiaodongcn/iOSAppBase
iOSAppBase/Carthage/Checkouts/XCGLogger/DemoApps/iOSDemo/iOSDemo/AppDelegate.swift
2
7133
// // AppDelegate.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright (c) 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import UIKit import XCGLogger let appDelegate = UIApplication.shared.delegate as! AppDelegate let log: XCGLogger = { // Setup XCGLogger let log = XCGLogger.default #if USE_NSLOG // Set via Build Settings, under Other Swift Flags log.remove(destinationWithIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) log.add(destination: AppleSystemLogDestination(identifier: XCGLogger.Constants.systemLogDestinationIdentifier)) log.logAppDetails() #else let logPath: URL = appDelegate.cacheDirectory.appendingPathComponent("XCGLogger_Log.txt") log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath) // Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS // This is mostly useful when testing in the simulator, or if you have the app sending you log files remotely if let fileDestination: FileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination { let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter() ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint]) ansiColorLogFormatter.colorize(level: .debug, with: .black) ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline]) ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint]) ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold]) ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red) fileDestination.formatters = [ansiColorLogFormatter] } // Add colour to the console destination. // - Note: You need the XcodeColors Plug-in https://github.com/robbiehanson/XcodeColors installed in Xcode // - to see colours in the Xcode console. Plug-ins have been disabled in Xcode 8, so offically you can not see // - coloured logs in Xcode 8. //if let consoleDestination: ConsoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination { // let xcodeColorsLogFormatter: XcodeColorsLogFormatter = XcodeColorsLogFormatter() // xcodeColorsLogFormatter.colorize(level: .verbose, with: .lightGrey) // xcodeColorsLogFormatter.colorize(level: .debug, with: .darkGrey) // xcodeColorsLogFormatter.colorize(level: .info, with: .blue) // xcodeColorsLogFormatter.colorize(level: .warning, with: .orange) // xcodeColorsLogFormatter.colorize(level: .error, with: .red) // xcodeColorsLogFormatter.colorize(level: .severe, with: .white, on: .red) // consoleDestination.formatters = [xcodeColorsLogFormatter] //} #endif // You can also change the labels for each log level, most useful for alternate languages, French, German etc, but Emoji's are more fun // log.levelDescriptions[.verbose] = "🗯" // log.levelDescriptions[.debug] = "🔹" // log.levelDescriptions[.info] = "ℹ️" // log.levelDescriptions[.warning] = "⚠️" // log.levelDescriptions[.error] = "‼️" // log.levelDescriptions[.severe] = "💣" // Alternatively, you can use emoji to highlight log levels (you probably just want to use one of these methods at a time). let emojiLogFormatter = PrePostFixLogFormatter() emojiLogFormatter.apply(prefix: "🗯🗯🗯 ", postfix: " 🗯🗯🗯", to: .verbose) emojiLogFormatter.apply(prefix: "🔹🔹🔹 ", postfix: " 🔹🔹🔹", to: .debug) emojiLogFormatter.apply(prefix: "ℹ️ℹ️ℹ️ ", postfix: " ℹ️ℹ️ℹ️", to: .info) emojiLogFormatter.apply(prefix: "⚠️⚠️⚠️ ", postfix: " ⚠️⚠️⚠️", to: .warning) emojiLogFormatter.apply(prefix: "‼️‼️‼️ ", postfix: " ‼️‼️‼️", to: .error) emojiLogFormatter.apply(prefix: "💣💣💣 ", postfix: " 💣💣💣", to: .severe) log.formatters = [emojiLogFormatter] return log }() // Create custom tags for your logs extension Tag { static let sensitive = Tag("sensitive") static let ui = Tag("ui") static let data = Tag("data") } // Create custom developers for your logs extension Dev { static let dave = Dev("dave") static let sabby = Dev("sabby") } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Properties var window: UIWindow? let documentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.endIndex - 1] }() let cacheDirectory: URL = { let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) return urls[urls.endIndex - 1] }() // MARK: - Life cycle methods func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
cdae75d89516d2da7b453e5bbccd05b7
51.924242
285
0.716862
4.568999
false
false
false
false
stuartjmoore/D-D
D&D/Models/Player.swift
1
2121
// // Character.swift // D&D // // Created by Moore, Stuart on 2/13/15. // Copyright (c) 2015 Stuart Moore. All rights reserved. // enum Proficiency: Float { case None = 0, Half = 0.5, Single = 1, Double = 2 } struct Alignment { enum Order { case Lawful, Neutral, Chaotic } enum Altruism { case Good, Neutral, Evil } let order: Order, altruism: Altruism } class Player { var name: String = "" var alignment: Alignment = Alignment(order: .Neutral, altruism: .Neutral) var race: Race! = nil var classes: [Class] = [] lazy var abilities: Abilities = Abilities(character: self) lazy var skills: Skills = Skills(character: self) lazy var armor: Armor = Armor(character: self) var bonus: Int { return level < 5 ? 2 : level < 9 ? 3 : level < 13 ? 4 : level < 17 ? 5 : level < 21 ? 6 : 0 } var level: Int { var _level = 0 for i in 0 ..< classes.count { _level += classes[i].level } return _level } var hitPoints: Int = 0 var hitPointsMin: Int = 0 var hitPointsMax: Int { var _hitPoints = 0, _constitution = 0 for i in 0 ..< classes.count { _hitPoints += classes[i].hitPoints _constitution += classes[i].constitution } return _hitPoints + _constitution } var experiencePoints: Int = 0 var experiencePointsMin: Int = 0 var experiencePointsMax: Int = 0 var inspired: Bool = false var speed: Int = 25 // ft/s var languages: [Language] = [] func classWithName(className: Class.Name) -> (object: Class, index: Int)? { for i in 0 ..< classes.count { if classes[i].name == className { return (object: classes[i], index: i) } } return nil } func levelUp(className: Class.Name) { if var (playerClass, i) = classWithName(className) { playerClass.level++ classes[i] = playerClass } } }
unlicense
9a202ac6a0c338afb985092a6b32ff5b
23.37931
99
0.539368
3.884615
false
false
false
false
cristov26/moviesApp
MoviesApp/Core/Services/Adapters/VideosWebService.swift
1
1887
// // VideosWebService.swift // MoviesApp // // Created by Cristian Tovar on 11/16/17. // Copyright © 2017 Cristian Tovar. All rights reserved. // import Foundation typealias videosClosure = ([Video]?) -> Void class VideosWebService: BaseService, VideoService{ static let endPoint = AppConstants.endPoint func retrieveVideos(movieId: String, completion: @escaping (ServiceResponse) -> Void) { let url = (type(of: self).endPoint + "/movie/" + movieId + "?api_key=\(super.appKey)&append_to_response=videos") super.callEndpoint(endPoint: url, completion: completion) } override func parse(response: AnyObject) -> [AnyObject]? { return VideosWebService.parse(data: response) as [AnyObject]? } } private extension VideosWebService{ static func parse(data: AnyObject) -> [Video]? { if (data is NSDictionary) { guard let feed = data[VideosServiceParseConstants.videos] as? NSDictionary, let videos = feed[VideosServiceParseConstants.results] as? [NSDictionary] else { return nil } return videos.enumerated().map(parseVideos).filter { $0 != nil }.map { $0! } } return nil } static func parseVideos(rank: Int, data: NSDictionary) -> Video? { guard let id = data.value(forKeyPath: VideosServiceParseConstants.id) as? String else { return nil } guard let key = data.value(forKeyPath: VideosServiceParseConstants.key) as? String else { return nil } guard let site = data.value(forKeyPath: VideosServiceParseConstants.site) as? String else { return nil } return RawVideo(id: id, key: key, site: site) } }
mit
e16f9a98a905bbe426af6e58cafcae68
30.433333
120
0.593849
4.588808
false
false
false
false
evering7/iSpeak8
iSpeak8/Helper_Reachability.swift
1
3691
// // Helper_Reachability.swift // iSpeak8 // // Created by JianFei Li on 14/08/2017. // Copyright © 2017 JianFei Li. All rights reserved. // import Foundation import ReachabilitySwift let globalReachability = GlobalReachability() class GlobalReachability: NSObject { var reachability: Reachability? func ensureNetworkReachability() { let isAllSitesOK = isReachabilityOK("") let isBaiDuOK = isReachabilityOK("www.baidu.com") let isGoogleOK = isReachabilityOK("www.google.com") if isAllSitesOK || isBaiDuOK || isGoogleOK { printLog("We could proceed") } else { printLog("Network no ok, need to ask for permission") ensureNetworkReachability_V2() } } func ensureNetworkReachability_V2() { do { Network.reachability = try Reachability_V2(hostname: "www.baidu.com") do { try Network.reachability?.start() } catch let error as Network.Error { printLog(error) } catch { printLog(error) } } catch { printLog(error) } } func isReachabilityOK(_ hostName: String) -> Bool { if hostName == "" { reachability = Reachability() } else { reachability = Reachability(hostname: hostName) } if let reachability_unWrapper = reachability { if reachability_unWrapper.isReachable { return true } else { return false } } else { return false } } func setupReachability(_ hostName: String?, useClosures: Bool) { let trueHostName = hostName != nil ? hostName : "no host name" printLog("set up with host name = \(String(describing: trueHostName))") reachability = (hostName == nil) ? Reachability() : Reachability(hostname: hostName!) if useClosures { reachability?.whenReachable = { reachability in DispatchQueue.main.async { // some action in main queue printLog("network reachable") } }// reachability? reachability?.whenUnreachable = { reachability in DispatchQueue.main.async { printLog("network is now unreachable") } } } else { // if use Closures NotificationCenter.default.addObserver(self, selector: #selector(GlobalReachability.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability) } // useClosures } // 2017.8.14 func setupReachability func reachabilityChanged(_ note: Notification) { let reachability = note.object as! Reachability if reachability.isReachable { printLog("network is reachable") } else { printLog("network is unreachable") } } func stopNotifier() { printLog("--- stop notifier") reachability?.stopNotifier() NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: nil) reachability = nil } deinit { stopNotifier() printLog("Finish notifier") printLog("Deinitialization \(type(of: self))") } } // GlobalReachability 2017.8.14
mit
da348a4cac6b21765c284e8cf8df4521
29
93
0.536585
5.68567
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/NSDate+Utilities.swift
1
2494
// // NSDate+Utilities.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit extension Date { public func startOfDay() -> Date { let calendar = Calendar.current let unitFlags: NSCalendar.Unit = [.day, .month, .year] let components = (calendar as NSCalendar).components(unitFlags, from: self) return calendar.date(from: components) ?? self } public var isToday: Bool { return self.startOfDay() == Date().startOfDay() } public var isTomorrow: Bool { return self.startOfDay() == Date().startOfDay().addingNumberOfDays(1) } public func addingNumberOfDays(_ days: Int) -> Date { let calendar = Calendar.current return calendar.date(byAdding: .day, value: days, to: self, wrappingComponents: false)! } }
bsd-3-clause
3971ee1741d220691ff0da98e683952f
41.982759
95
0.72844
4.677298
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/01722-getselftypeforcontainer.swift
1
472
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { typealias B : ExtensibleCollectionType>(a<h = [Byte] (A.E == [""foobar"foo"ab"a"") } class A { private let foo as a<d<S { } func g(a class A? = D> { } protocol a { print(g<b: C = b: A, f(start: Sequence> { }()") func b> T) typealias f : b[T, A
apache-2.0
28447afc06c71fe61cb17146c4b78ce1
21.47619
87
0.665254
2.95
false
true
false
false
robzimpulse/mynurzSDK
mynurzSDK/Classes/EndpointManager.swift
1
9372
// // EndpointManager.swift // Pods // // Created by Robyarta on 5/15/17. // // import UIKit public class EndpointManager: NSObject { public static let sharedInstance = EndpointManager(mode: .Local) public static let devSharedInstance = EndpointManager(mode: .Development) public static let liveSharedInstance = EndpointManager(mode: .Live) public init(mode: Server) { switch mode { case .Live: host = "https://new-dev.mynurz.com" break case .Development: host = "https://new-dev.mynurz.com" break default: break } } var host = "http://mynurznew.app" var midtransClientKey = "VT-client-AoZKEG2XOkHtEPw2" var omisePublicKey = "pkey_test_58820b5b9axpbqqmmgv" var stripePublishableKey = "pk_test_sE3n6dQNn01rQzfXP89fKMcx" var googleMapKey = "AIzaSyAhTxXrCjwOP1kGNY1RmROaZ_GJ8mgOK6M" lazy var cleanHost: String = {return self.host.replacingOccurrences(of: "https://", with: "").replacingOccurrences(of: "http://", with: "")}() // MARKL - Midtrans merchant url lazy var MIDTRANS_CHARGE: String = {return self.host.appending("/api/midtrans")}() lazy var STRIPE_CHARGE: String = {return self.host.appending("/api/stripe/charge")}() lazy var OMISE_CHARGE: String = {return self.host.appending("/api/omise/charge")}() // MARK: - Authentication lazy var PUSHER_PRIVATE: String = {return self.host.appending("/api/pusher_private")}() lazy var PUSHER_PRESENCE: String = {return self.host.appending("/api/pusher_presence")}() lazy var LOGIN: String = {return self.host.appending("/api/login")}() lazy var REGISTER_CUSTOMER: String = {return self.host.appending("/api/register_customer")}() lazy var REGISTER_FREELANCER: String = {return self.host.appending("/api/register_freelancer")}() lazy var RESET_LINK: String = {return self.host.appending("/api/reset")}() lazy var REFRESH_TOKEN: String = {return self.host.appending("/api/refresh_token")}() lazy var GET_SKILL: String = {return self.host.appending("/api/setting/skills")}() lazy var GET_SKILL_EXPERIENCE: String = {return self.host.appending("/api/setting/skill_experiences")}() lazy var GET_ROLE: String = {return self.host.appending("/api/setting/roles")}() lazy var GET_RELIGION: String = {return self.host.appending("/api/setting/religions")}() lazy var GET_PROMOTION_CATEGORY: String = {return self.host.appending("/api/setting/promotion_categories")}() lazy var GET_PROFESSION: String = {return self.host.appending("/api/setting/professions")}() lazy var GET_JOB_STATUS: String = {return self.host.appending("/api/setting/job_statuses")}() lazy var GET_EMPLOYMENT: String = {return self.host.appending("/api/setting/employments")}() lazy var GET_DEGREE: String = {return self.host.appending("/api/setting/degrees")}() lazy var GET_RELATIONSHIP: String = {return self.host.appending("/api/setting/relationships")}() lazy var GET_COUNTRY: String = {return self.host.appending("/api/setting/countries")}() lazy var GET_STATE: String = {return self.host.appending("/api/setting/states")}() lazy var GET_CITY: String = {return self.host.appending("/api/setting/cities")}() lazy var GET_DISTRICT: String = {return self.host.appending("/api/setting/districts")}() lazy var GET_AREA: String = {return self.host.appending("/api/setting/areas")}() lazy var FIREBASE_TOKEN: String = {return self.host.appending("/api/firebase_token")}() lazy var LOGOUT: String = {return self.host.appending("/api/logout")}() // MARK: - Customer End Point lazy var CUSTOMER_PHOTO: String = {return self.host.appending("/api/customer/photo")}() lazy var CUSTOMER_SUBSCRIBE: String = {return self.host.appending("/api/customer/subscribe")}() lazy var CUSTOMER_ADDRESS: String = {return self.host.appending("/api/customer/address")}() lazy var CUSTOMER_PROFILE: String = {return self.host.appending("/api/customer/profile")}() lazy var CUSTOMER_NAME: String = {return self.host.appending("/api/customer/name")}() lazy var CUSTOMER_PASSWORD: String = {return self.host.appending("/api/customer/password")}() lazy var CUSTOMER_PHONE: String = {return self.host.appending("/api/customer/phone")}() lazy var CUSTOMER_NATIONALITY: String = {return self.host.appending("/api/customer/nationality")}() lazy var CUSTOMER_SEARCH_FREELANCER: String = {return self.host.appending("/api/customer/search_freelancer")}() lazy var CUSTOMER_SEARCH_CUSTOMER: String = {return self.host.appending("/api/customer/search_customer")}() lazy var CUSTOMER_PATIENT_GET: String = {return self.host.appending("/api/customer/patient")}() lazy var CUSTOMER_PATIENT_ADD: String = {return self.host.appending("/api/customer/patient/add")}() lazy var CUSTOMER_PATIENT_UPDATE: String = {return self.host.appending("/api/customer/patient/update")}() lazy var CUSTOMER_PATIENT_REMOVE: String = {return self.host.appending("/api/customer/patient/remove")}() lazy var CUSTOMER_INQUIRY_GET: String = {return self.host.appending("/api/customer/inquiry")}() lazy var CUSTOMER_INQUIRY_ADD: String = {return self.host.appending("/api/customer/inquiry/add")}() lazy var CUSTOMER_INQUIRY_UPDATE: String = {return self.host.appending("/api/customer/inquiry/update")}() lazy var CUSTOMER_INQUIRY_PUBLISH: String = {return self.host.appending("/api/customer/inquiry/publish")}() // MARK: - Freelancer End Point lazy var FREELANCER_PHOTO: String = {return self.host.appending("/api/freelancer/photo")}() lazy var FREELANCER_IDCARD: String = {return self.host.appending("/api/freelancer/id_card")}() lazy var FREELANCER_PROFILE: String = {return self.host.appending("/api/freelancer/profile")}() lazy var FREELANCER_SUBSCRIBE: String = {return self.host.appending("/api/freelancer/subscribe")}() lazy var FREELANCER_PACKAGE_PRICE: String = {return self.host.appending("/api/freelancer/package_price")}() lazy var FREELANCER_NAME: String = {return self.host.appending("/api/freelancer/name")}() lazy var FREELANCER_PASSWORD: String = {return self.host.appending("/api/freelancer/password")}() lazy var FREELANCER_PHONE: String = {return self.host.appending("/api/freelancer/phone")}() lazy var FREELANCER_ADDRESS: String = {return self.host.appending("/api/freelancer/address")}() lazy var FREELANCER_NATIONALITY: String = {return self.host.appending("/api/freelancer/nationality")}() lazy var FREELANCER_SEARCH_FREELANCER: String = {return self.host.appending("/api/freelancer/search_freelancer")}() lazy var FREELANCER_SEARCH_CUSTOMER: String = {return self.host.appending("/api/freelancer/search_customer")}() lazy var FREELANCER_ACADEMIC_ADD: String = {return self.host.appending("/api/freelancer/academic/add")}() lazy var FREELANCER_ACADEMIC_UPDATE: String = {return self.host.appending("/api/freelancer/academic/update")}() lazy var FREELANCER_ACADEMIC_REMOVE: String = {return self.host.appending("/api/freelancer/academic/remove")}() lazy var FREELANCER_TRAINING_ADD: String = {return self.host.appending("/api/freelancer/training/add")}() lazy var FREELANCER_TRAINING_UPDATE: String = {return self.host.appending("/api/freelancer/training/update")}() lazy var FREELANCER_TRAINING_REMOVE: String = {return self.host.appending("/api/freelancer/training/remove")}() lazy var FREELANCER_WORKING_AREA_ADD: String = {return self.host.appending("/api/freelancer/working_area/add")}() lazy var FREELANCER_WORKING_AREA_REMOVE: String = {return self.host.appending("/api/freelancer/working_area/remove")}() lazy var FREELANCER_SKILL_ADD: String = {return self.host.appending("/api/freelancer/skill/add")}() lazy var FREELANCER_SKILL_UPDATE: String = {return self.host.appending("/api/freelancer/skill/update")}() lazy var FREELANCER_SKILL_REMOVE: String = {return self.host.appending("/api/freelancer/skill/remove")}() lazy var FREELANCER_WORKING_EXPERIENCE_ADD: String = {return self.host.appending("/api/freelancer/working_experience/add")}() lazy var FREELANCER_WORKING_EXPERIENCE_UPDATE: String = {return self.host.appending("/api/freelancer/working_experience/update")}() lazy var FREELANCER_WORKING_EXPERIENCE_REMOVE: String = {return self.host.appending("/api/freelancer/working_experience/remove")}() lazy var FREELANCER_INQUIRY_GET: String = {return self.host.appending("/api/freelancer/inquiries")}() lazy var FREELANCER_PROPOSAL_GET: String = {return self.host.appending("/api/freelancer/proposal")}() lazy var FREELANCER_PROPOSAL_ADD: String = {return self.host.appending("/api/freelancer/proposal/add")}() lazy var FREELANCER_PROPOSAL_UPDATE: String = {return self.host.appending("/api/freelancer/proposal/update")}() lazy var FREELANCER_PROPOSAL_SUBMIT: String = {return self.host.appending("/api/freelancer/proposal/submit")}() lazy var FREELANCER_PROPOSAL_COLLABORATOR_ADD: String = {return self.host.appending("/api/freelancer/proposal/collaborator/add")}() lazy var FREELANCER_PROPOSAL_COLLABORATOR_REMOVE: String = {return self.host.appending("/api/freelancer/proposal/collaborator/remove")}() }
mit
3e3d984324d2d492298b08932246a49e
66.42446
146
0.709774
3.519339
false
false
false
false
manGoweb/S3
Sources/S3Kit/Extensions/S3+Request.swift
1
1275
import Foundation import NIO import AsyncHTTPClient extension S3 { /// Make an S3 request func make(request url: URL, method: HTTPMethod, headers: HTTPHeaders, data: Data? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy, on eventLoop: EventLoop) -> EventLoopFuture<HTTPClient.Response> { do { let body: HTTPClient.Body? if let data = data { body = HTTPClient.Body.data(data) } else { body = nil } var headers = headers headers.add(name: "User-Agent", value: "S3Kit-for-Swift") headers.add(name: "Accept", value: "*/*") headers.add(name: "Connection", value: "keep-alive") headers.add(name: "Content-Length", value: String(data?.count ?? 0)) let request = try HTTPClient.Request( url: url.absoluteString, method: method, headers: headers, body: body ) let client = HTTPClient(eventLoopGroupProvider: .shared(eventLoop)) return client.execute(request: request) } catch { return eventLoop.makeFailedFuture(error) } } }
mit
56df4e54c8e8c957ca536b8e2969b44e
33.459459
222
0.549804
4.829545
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Live/View/ChatContentVIew/ChatContentView.swift
1
1935
// // ChatContentView.swift // GYJTV // // Created by 田全军 on 2017/6/5. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit private let kChatContentCell = "kChatContentCell" class ChatContentView: UIView, NibLoadable { @IBOutlet weak var tableView: UITableView! fileprivate lazy var messageArr : [NSAttributedString] = [NSAttributedString]() override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clear tableView.register(ChatContentCell.self, forCellReuseIdentifier: kChatContentCell) tableView.separatorStyle = .none tableView.backgroundColor = UIColor.clear tableView.showsVerticalScrollIndicator = false tableView.delegate = self tableView.dataSource = self //高度的自动布局 tableView.estimatedRowHeight = 30 tableView.rowHeight = UITableViewAutomaticDimension } //添加消息 func insertMessage(_ message : NSAttributedString) { messageArr.append(message) tableView.reloadData() //tableView移动到最后一条消息的位置 let indexPath = IndexPath(row: messageArr.count - 1, section: 0) UIView.animate(withDuration: 0.25) { self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) } } } // MARK: UITableViewDelegate, UITableViewDataSource extension ChatContentView : UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kChatContentCell, for: indexPath) as! ChatContentCell cell.contentLabel.attributedText = messageArr[indexPath.row] return cell } }
mit
ba5398f3f7a3d088c7d81c7a1b228fc8
33.181818
118
0.700532
5.026738
false
false
false
false
istx25/lunchtime
Lunchtime/Controller/SetupPageFifthViewController.swift
1
1337
// // SetupPageFifthViewController.swift // Lunchtime // // Created by Willow Bumby on 2015-11-18. // Copyright © 2015 Lighthouse Labs. All rights reserved. // import UIKit import Realm class SetupPageFifthViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var picker: UIDatePicker? // MARK: - Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() picker?.datePickerMode = .Time } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) guard let picker = picker else { return } let realm = RLMRealm.defaultRealm() let user = User() user.lunchtime = picker.date user.preferredDistance = NSNumber(integer: 1500) user.identifier = NSNumber(integer: 1) user.category = "food" do { realm.beginWriteTransaction() User.createOrUpdateInRealm(realm, withValue: user) try realm.commitWriteTransaction() } catch let error { print("Something went wrong...") print("Error Reference: \(error)") } let notification = LunchtimeNotification(date: picker.date) UIApplication.sharedApplication().scheduleLocalNotification(notification) } }
mit
bade8b4df584308881e81c42afe5907a
25.196078
81
0.631737
4.823105
false
false
false
false
lzpfmh/actor-platform
actor-apps/app-ios/ActorApp/Styles.swift
1
4813
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation func initStyles() { // Text root styles registerStyle("root.text") { (s) -> () in s.foregroundColor = UIColor.blackColor() } registerStyle("root.accent") { (s) -> () in s.foregroundColor = UIColor.RGB(0x5085CB) } registerStyle("label", parent: "root.text") { (s) -> () in s.foregroundColor = s.foregroundColor!.alpha(0xDE/255.0) } registerStyle("hint") { (s) -> () in s.foregroundColor = UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } // TabView registerStyle("tab.icon") { (s) -> () in s.foregroundColor = MainAppTheme.tab.unselectedIconColor } registerStyle("tab.icon.selected", parent: "root.accent") { (s) -> () in s.foregroundColor = MainAppTheme.tab.selectedIconColor } registerStyle("tab.text") { (s) -> () in s.foregroundColor = MainAppTheme.tab.unselectedTextColor } registerStyle("tab.text.selected", parent: "root.accent") { (s) -> () in s.foregroundColor = MainAppTheme.tab.selectedTextColor } // Cell style registerStyle("cell") { (s) -> () in s.backgroundColor = MainAppTheme.list.bgColor // s.selectedColor = MainAppTheme.list.bgSelectedColor s.cellTopSeparatorVisible = false s.cellBottomSeparatorVisible = true s.cellSeparatorsLeftInset = 15 } registerStyle("cell.titled", parent: "cell") registerStyle("cell.titled.title", parent: "root.accent") { (s) -> () in s.font = UIFont.systemFontOfSize(14.0) } registerStyle("cell.titled.content") { (s) -> () in s.font = UIFont.systemFontOfSize(17.0) } // User online style registerStyle("user.online", parent: "root.accent") registerStyle("user.offline", parent: "hint") // Avatars registerStyle("avatar.round") { (s) -> () in s.avatarType = .Rounded } registerStyle("avatar.square") { (s) -> () in s.avatarType = .Square } registerStyle("avatar.round.small", parent: "avatar.round") { (s) -> () in s.avatarSize = 40 } // Dialog list style registerStyle("dialogs.cell", parent: "cell") { (s) -> () in s.cellSeparatorsLeftInset = 75 } registerStyle("dialogs.cell.last", parent: "cell") { (s) -> () in s.cellSeparatorsLeftInset = 0 } registerStyle("dialogs.avatar", parent: "avatar.round") { (s) -> () in s.avatarSize = 48 } registerStyle("dialogs.title", parent: "label") { (s) -> () in s.font = UIFont.mediumSystemFontOfSize(17) s.foregroundColor = MainAppTheme.list.dialogTitle } registerStyle("dialogs.date", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(14) s.foregroundColor = MainAppTheme.list.dialogDate s.textAlignment = .Right } registerStyle("dialogs.message", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(16) s.foregroundColor = MainAppTheme.list.dialogText } registerStyle("dialogs.message.highlight", parent: "dialogs.message") { (s) -> () in s.foregroundColor = MainAppTheme.list.dialogTitle } registerStyle("dialogs.counter", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(14) s.foregroundColor = MainAppTheme.list.unreadText s.textAlignment = .Center } registerStyle("dialogs.counter.bg") { (s) -> () in s.image = Imaging.imageWithColor(MainAppTheme.list.unreadBg, size: CGSizeMake(18, 18)) .roundImage(18).resizableImageWithCapInsets(UIEdgeInsetsMake(9, 9, 9, 9)) } registerStyle("dialogs.status") { (s) -> () in s.contentMode = UIViewContentMode.Center } // Members registerStyle("members.cell", parent: "cell") { (s) -> () in s.cellSeparatorsLeftInset = 75 } registerStyle("members.name", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(18.0) } registerStyle("members.online", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(14.0) } registerStyle("members.admin", parent: "label") { (s) -> () in s.font = UIFont.systemFontOfSize(14.0) s.foregroundColor = UIColor.redColor() } // List registerStyle("list.label", parent: "label") { (s) -> () in } // Controllers registerStyle("controller.settings") { (s) -> () in s.backgroundColor = MainAppTheme.list.bgColor s.title = localized("TabSettings") } }
mit
cb7eae7d173a3637847fc0c2b8abdc97
28.353659
96
0.58155
3.93219
false
false
false
false
prangbi/PrBasicREST
iOS/PrBasicRest/PrBasicRest/Common/Util.swift
1
3602
// // Util.swift // PrBasicRest // // Created by 구홍석 on 2017. 2. 8.. // Copyright © 2017년 Prangbi. All rights reserved. // import UIKit class Util: NSObject { class func dictionaryWithData(_ data: Data?) -> Dictionary<String, AnyObject>? { return Util.dictionaryWithData(data, rootKey: nil) } class func dictionaryWithData(_ data: Data?, rootKey: String?) -> Dictionary<String, AnyObject>? { var resultDic: Dictionary<String, AnyObject>? if nil == data { return resultDic } var jsonDic: Dictionary<String, AnyObject>? do { try jsonDic = JSONSerialization.jsonObject( with: data!, options: []) as? Dictionary<String, AnyObject> } catch { print(error) } if nil != rootKey { resultDic = jsonDic?[rootKey!] as? Dictionary<String, AnyObject> } else { resultDic = jsonDic } return resultDic } class func dictionaryArrayWithData(_ data: Data?) -> Array<Dictionary<String, AnyObject>>? { return Util.dictionaryArrayWithData(data, rootKey: nil) } class func dictionaryArrayWithData(_ data: Data?, rootKey: String?) -> Array<Dictionary<String, AnyObject>>? { var resultDics: Array<Dictionary<String, AnyObject>>? if nil == data { return resultDics } if nil != rootKey { var jsonDic: Dictionary<String, AnyObject>? do { try jsonDic = JSONSerialization.jsonObject( with: data!, options: []) as? Dictionary<String, AnyObject> } catch { print(error) } resultDics = jsonDic?[rootKey!] as? Array<Dictionary<String, AnyObject>> } else { do { try resultDics = JSONSerialization.jsonObject( with: data!, options: []) as? Array<Dictionary<String, AnyObject>> } catch { print(error) } } return resultDics } class func showSimpleAlert(target: UIViewController, title: String?, message: String?, handler: ((UIAlertAction) -> Void)? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: handler) alertController.addAction(alertAction) target.present(alertController, animated: true, completion: nil) } class func showAlert(target: UIViewController, title: String?, message: String?, actionTitles: [String]? = nil, actionHandlers: [((UIAlertAction) -> Void)?]? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) if nil != actionTitles { for actionTitle in actionTitles! { let index = actionTitles!.index(of: actionTitle) if nil == index { continue } let actionHandler = actionHandlers?[index!] let alertAction = UIAlertAction(title: actionTitle, style: .default, handler: actionHandler) alertController.addAction(alertAction) } } target.present(alertController, animated: true, completion: nil) } }
unlicense
6e0dc99901afed928efd6b9fe306ad78
35.292929
114
0.551072
5.192197
false
false
false
false
apple/swift-driver
Sources/swift-build-sdk-interfaces/main.swift
1
7250
//===--------------- main.swift - swift-build-sdk-interfaces ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// import SwiftDriverExecution import SwiftDriver #if os(Windows) import CRT #elseif os(iOS) || os(macOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif import TSCBasic // <<< import class TSCBasic.DiagnosticsEngine import class TSCBasic.ProcessSet import enum TSCBasic.ProcessEnv import func TSCBasic.withTemporaryFile import struct TSCBasic.AbsolutePath import var TSCBasic.localFileSystem import var TSCBasic.stderrStream let diagnosticsEngine = DiagnosticsEngine(handlers: [Driver.stderrDiagnosticsHandler]) func getArgument(_ flag: String, _ env: String? = nil) -> String? { if let id = CommandLine.arguments.firstIndex(of: flag) { let nextId = id.advanced(by: 1) if nextId < CommandLine.arguments.count { return CommandLine.arguments[nextId] } } if let env = env { return ProcessEnv.vars[env] } return nil } func getArgumentAsPath(_ flag: String, _ env: String? = nil) throws -> AbsolutePath? { if let raw = getArgument(flag, env) { return try VirtualPath(path: raw).absolutePath } return nil } guard let rawOutputDir = getArgument("-o") else { diagnosticsEngine.emit(.error("need to specify -o")) exit(1) } /// When -core is specified, only most significant modules are handled. Currently, /// they are Foundation and anything below. let coreMode = CommandLine.arguments.contains("-core") /// Verbose to print more info let verbose = CommandLine.arguments.contains("-v") /// Skip executing the jobs let skipExecution = CommandLine.arguments.contains("-n") do { let sdkPathArg = try getArgumentAsPath("-sdk", "SDKROOT") guard let sdkPath = sdkPathArg else { diagnosticsEngine.emit(.error("need to set SDKROOT")) exit(1) } if !localFileSystem.exists(sdkPath) { diagnosticsEngine.emit(error: "cannot find sdk: \(sdkPath.pathString)") exit(1) } let logDir = try getArgumentAsPath("-log-path") let collector = SDKPrebuiltModuleInputsCollector(sdkPath, diagnosticsEngine) var outputDir = try VirtualPath(path: rawOutputDir).absolutePath! // if the given output dir ends with 'prebuilt-modules', we should // append the SDK version number so all modules will built into // the SDK-versioned sub-directory. if outputDir.basename == "prebuilt-modules" { outputDir = AbsolutePath(collector.versionString, relativeTo: outputDir) } if !localFileSystem.exists(outputDir) { try localFileSystem.createDirectory(outputDir, recursive: true) } let swiftcPathRaw = ProcessEnv.vars["SWIFT_EXEC"] var swiftcPath: AbsolutePath if let swiftcPathRaw = swiftcPathRaw { swiftcPath = try VirtualPath(path: swiftcPathRaw).absolutePath! } else { swiftcPath = AbsolutePath("Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc", relativeTo: sdkPath.parentDirectory .parentDirectory .parentDirectory .parentDirectory .parentDirectory) } if !localFileSystem.exists(swiftcPath) { diagnosticsEngine.emit(error: "cannot find swift compiler: \(swiftcPath.pathString)") exit(1) } let sysVersionFile = outputDir.appending(component: "SystemVersion.plist") if localFileSystem.exists(sysVersionFile) { try localFileSystem.removeFileTree(sysVersionFile) } // Copy $SDK/System/Library/CoreServices/SystemVersion.plist file from the SDK // into the prebuilt module file to keep track of which SDK build we are generating // the modules from. try localFileSystem.copy(from: sdkPath.appending(component: "System") .appending(component: "Library") .appending(component: "CoreServices") .appending(component: "SystemVersion.plist"), to: sysVersionFile) let processSet = ProcessSet() let inputTuple = try collector.collectSwiftInterfaceMap() let allAdopters = inputTuple.adopters let currentABIDir = try getArgumentAsPath("-current-abi-dir") try SwiftAdopter.emitSummary(allAdopters, to: currentABIDir) let inputMap = inputTuple.inputMap let allModules = coreMode ? ["Foundation"] : Array(inputMap.keys) try withTemporaryFile(suffix: ".swift") { let tempPath = $0.path try localFileSystem.writeFileContents(tempPath, body: { for module in allModules { $0 <<< "import " <<< module <<< "\n" } }) let executor = try SwiftDriverExecutor(diagnosticsEngine: diagnosticsEngine, processSet: processSet, fileSystem: localFileSystem, env: ProcessEnv.vars) var args = ["swiftc", "-target", collector.targetTriple, tempPath.description, "-sdk", sdkPath.pathString] let mcpFlag = "-module-cache-path" // Append module cache path if given by the client if let mcp = getArgument(mcpFlag) { args.append(mcpFlag) args.append(mcp) } let baselineABIDir = try getArgumentAsPath("-baseline-abi-dir") var driver = try Driver(args: args, diagnosticsEngine: diagnosticsEngine, executor: executor, compilerExecutableDir: swiftcPath.parentDirectory) let (jobs, danglingJobs) = try driver.generatePrebuitModuleGenerationJobs(with: inputMap, into: outputDir, exhaustive: !coreMode, dotGraphPath: getArgumentAsPath("-dot-graph-path"), currentABIDir: currentABIDir, baselineABIDir: baselineABIDir) if verbose { Driver.stdErrQueue.sync { stderrStream <<< "job count: \(jobs.count + danglingJobs.count)\n" stderrStream.flush() } } if skipExecution { exit(0) } let delegate = PrebuitModuleGenerationDelegate(jobs, diagnosticsEngine, verbose, logDir) do { try executor.execute(workload: DriverExecutorWorkload.init(jobs, nil, continueBuildingAfterErrors: true), delegate: delegate, numParallelJobs: 128) } catch { // Only fail when critical failures happened. if delegate.hasCriticalFailure { exit(1) } } do { if !danglingJobs.isEmpty && delegate.shouldRunDanglingJobs { try executor.execute(workload: DriverExecutorWorkload.init(danglingJobs, nil, continueBuildingAfterErrors: true), delegate: delegate, numParallelJobs: 128) } } catch { // Failing of dangling jobs don't fail the process. exit(0) } } } catch { print("error: \(error)") exit(1) }
apache-2.0
ea74b652a531ee7a99b6646688421b89
37.978495
163
0.654621
4.447853
false
false
false
false
huangboju/Moots
Examples/URLSession/URLSession/WebViewController.swift
1
9673
// // Copyright © 2015年 huangyibiao. All rights reserved. // import WebKit class WebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate { var webView: WKWebView! var progressView: UIProgressView! var testUrl = "" override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = [] // 创建webveiew // 创建一个webiview的配置项 let configuretion = WKWebViewConfiguration() // Webview的偏好设置 configuretion.preferences = WKPreferences() configuretion.preferences.minimumFontSize = 10 configuretion.preferences.javaScriptEnabled = true // 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开 configuretion.preferences.javaScriptCanOpenWindowsAutomatically = false // 通过js与webview内容交互配置 configuretion.userContentController = WKUserContentController() // 添加一个JS到HTML中,这样就可以直接在JS中调用我们添加的JS方法 let script = WKUserScript(source: "function showAlert() { alert('在载入webview时通过Swift注入的JS方法'); }", injectionTime: .atDocumentStart, // 在载入时就添加JS forMainFrameOnly: true) // 只添加到mainFrame中 configuretion.userContentController.addUserScript(script) // 添加一个名称,就可以在JS通过这个名称发送消息: // window.webkit.messageHandlers.AppModel.postMessage({body: 'xxx'}) configuretion.userContentController.add(self, name: "AppModel") self.webView = WKWebView(frame: self.view.bounds, configuration: configuretion) // let url = NSBundle.mainBundle().URLForResource("pic", withExtension: "html") // self.webView.loadRequest(NSURLRequest(URL: url ?? NSURL())) // UIApplication.sharedApplication().openURL(NSURL(string: "http://huaban.com/")!) self.webView.load(URLRequest(url: URL(string: "http://www.cmcaifu.com/")!)) view.addSubview(self.webView) // 监听支持KVO的属性 self.webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) self.webView.navigationDelegate = self self.webView.uiDelegate = self self.progressView = UIProgressView(progressViewStyle: .default) self.progressView.frame.size.width = self.view.frame.width self.view.addSubview(self.progressView) // self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "前进", style: .Done, target: self, action: #selector(previousPage)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "后退", style: .done, target: self, action: #selector(nextPage)) let textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 100)) textLabel.backgroundColor = UIColor.red webView.addSubview(textLabel) webView.sendSubviewToBack(textLabel) webView.scrollView.delegate = self } func scrollViewDidScroll(_ scrollView: UIScrollView) { let y = scrollView.contentOffset.y if y <= 0 { scrollView.backgroundColor = .clear } else { scrollView.backgroundColor = UIColor.white } } func previousPage() { if self.webView.canGoBack { self.webView.goBack() } } @objc func nextPage() { if self.webView.canGoForward { self.webView.goForward() } } // MARK: - WKScriptMessageHandler func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.body) if message.name == "AppModel" { print("message name is AppModel") } } // MARK: - KVO override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "loading" { print("loading") } else if keyPath == "title" { self.title = self.webView.title } else if keyPath == "estimatedProgress" { print(webView.estimatedProgress) self.progressView.setProgress(Float(webView.estimatedProgress), animated: true) } // 已经完成加载时,我们就可以做我们的事了 if !webView.isLoading { // 手动调用JS代码 let js = "callJsAlert()" self.webView.evaluateJavaScript(js) { (_, _) -> Void in print("call js alert") } UIView.animate(withDuration: 0.55, animations: { () -> Void in self.progressView.alpha = 0.0 }) } } // MARK: - WKNavigationDelegate // 决定导航的动作,通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制,不允许跨域,因此我们要对不能跨域的链接 // 单独处理。但是,对于Safari是允许跨域的,不用这么处理。 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping(WKNavigationActionPolicy) -> Void) { print(#function) let hostname = navigationAction.request.url?.absoluteString // 处理跨域问题 if navigationAction.navigationType == .linkActivated && hostname!.contains("image-preview:") { // 手动跳转 decisionHandler(.cancel) } else { self.progressView.alpha = 1.0 decisionHandler(.allow) } } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { print(#function) } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { print(#function) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let aa = "function registerImageClickAction(){var imgs=document.getElementsByTagName('img'); var length=imgs.length; for(var i=0;i<length;i++){img=imgs[i]; img.onclick=function(){window.location.href='image-preview:'+this.src}}}" webView.evaluateJavaScript(aa) { (str, error) in print(error as Any) } webView.evaluateJavaScript("registerImageClickAction();") { (str, error) in print(error as Any) } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print(#function) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print(#function) } func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { print(#function) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print(#function) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping(WKNavigationResponsePolicy) -> Void) { print(#function) decisionHandler(.allow) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping(URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print(#function) completionHandler(.performDefaultHandling, nil) } // MARK: - WKUIDelegate func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping() -> Void) { let alert = UIAlertController(title: "Tip", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in // We must call back js completionHandler() })) self.present(alert, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping(Bool) -> Void) { let alert = UIAlertController(title: "Tip", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in completionHandler(true) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) -> Void in completionHandler(false) })) self.present(alert, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping(String?) -> Void) { let alert = UIAlertController(title: prompt, message: defaultText, preferredStyle: .alert) alert.addTextField { (textField: UITextField) -> Void in textField.textColor = UIColor.red } alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in completionHandler(alert.textFields![0].text!) })) self.present(alert, animated: true, completion: nil) } func webViewDidClose(_ webView: WKWebView) { print(#function) } }
mit
599d8a03f0a6548fceb742381501c830
38.722944
237
0.657258
4.791645
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/GasPricesDatasorce.swift
1
2003
// // GasPricesDatasorce.swift // lasgasmx // // Created by Desarrollo on 3/29/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit class GasPricesDatasorce: CollectionDatasource { let storageManager = GasPriceStorageManager() lazy var gasApi: GasApiManager = { let configManager = (UIApplication.shared.delegate as! AppDelegate).configManager return GasApiManager(baseUrl: configManager["API_BASE_URL"]) }() override func cellClasses() -> [CollectionDatasourceCell.Type] { return [GasPriceCell.self, GasPriceEmptyCell.self] } override func cellClass(_ indexPath: IndexPath) -> CollectionDatasourceCell.Type? { guard (objects?[indexPath.item] as? GasPriceInState) != nil else { return GasPriceEmptyCell.self } return GasPriceCell.self } func fetchStroage(){ var prices = storageManager.fetchAllAsGasPrices() as [AnyObject] if prices.count < 5 { prices.append(1 as AnyObject) } objects = prices updateDatasorce() } func updateStorageItems() { let entitys = storageManager.fetchAll() // TODO: Indicador de Carga for entity in entitys { guard entity.canUpdate() else { continue } let location = GasPriceLocation(state: entity.state!, city: entity.city!) gasApi.getPriceBy(location: location, completition: { dataResult in switch dataResult { case .Success(let data): DispatchQueue.main.async { entity.update(with: data) self.storageManager.saveChanges() self.fetchStroage() } case .Failure: break } }) } } func updateCarrousell() { fetchStroage() updateStorageItems() } }
mit
ec140141d160d96b3f01cfa287dc1d64
30.777778
107
0.575924
4.688525
false
false
false
false
grpc/grpc-swift
Sources/GRPC/TLSVerificationHandler.swift
1
1937
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Logging import NIOCore import NIOTLS /// Application protocol identifiers for ALPN. internal enum GRPCApplicationProtocolIdentifier { static let gRPC = "grpc-exp" static let h2 = "h2" static let http1_1 = "http/1.1" static let client = [gRPC, h2] static let server = [gRPC, h2, http1_1] static func isHTTP2Like(_ value: String) -> Bool { switch value { case self.gRPC, self.h2: return true default: return false } } static func isHTTP1(_ value: String) -> Bool { return value == self.http1_1 } } internal class TLSVerificationHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Any private let logger: Logger init(logger: Logger) { self.logger = logger } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if let tlsEvent = event as? TLSUserEvent { switch tlsEvent { case let .handshakeCompleted(negotiatedProtocol: .some(`protocol`)): self.logger.debug("TLS handshake completed, negotiated protocol: \(`protocol`)") case .handshakeCompleted(negotiatedProtocol: nil): self.logger.debug("TLS handshake completed, no protocol negotiated") case .shutdownCompleted: () } } context.fireUserInboundEventTriggered(event) } }
apache-2.0
f3b36dd97dbfd01418e57ab069e05d39
28.8
88
0.706247
4.138889
false
false
false
false
koke/WordPressComKit
WordPressComKit/SiteService.swift
1
2384
import Foundation import Alamofire public class SiteService { public init() {} public func fetchSite(siteID: Int, completion: (Site?, NSError?) -> Void) { Alamofire .request(RequestRouter.Site(siteID: siteID)) .validate() .responseJSON { response in guard response.result.isSuccess else { completion(nil, response.result.error) return } let json = response.result.value as? [String: AnyObject] let site = self.mapJSONToSite(json!) completion(site, nil) } } public func fetchSites(showActiveOnly: Bool = true, completion:([Site]?, NSError?) -> Void) { Alamofire .request(RequestRouter.Sites(showActiveOnly: showActiveOnly)) .validate() .responseJSON { response in guard response.result.isSuccess else { completion(nil, response.result.error) return } let json = response.result.value as? [String: AnyObject] let sitesDictionary = json!["sites"] as! [[String: AnyObject]] let sites = sitesDictionary.map(self.mapJSONToSite) completion(sites, nil) } } func mapJSONToSite(json: [String: AnyObject]) -> Site { let site = Site() let rawIcon = json["icon"] as? NSDictionary site.ID = json["ID"] as! Int site.name = json["name"] as? String site.description = json["description"] as? String site.URL = NSURL(string: json["URL"] as! String) site.icon = rawIcon?["img"] as? String site.jetpack = json["jetpack"] as! Bool site.postCount = json["post_count"] as! Int site.subscribersCount = json["subscribers_count"] as! Int site.language = json["lang"] as! String site.visible = json["visible"] as! Bool site.isPrivate = json["is_private"] as! Bool let options = json["options"] as? [String: AnyObject] if let timeZoneName = options?["timezone"] as? String { site.timeZone = NSTimeZone(name: timeZoneName) } return site } }
mit
bc5338a523c9ee4842e797a346d67ef4
34.597015
97
0.530621
4.865306
false
false
false
false
huaf22/zhihuSwiftDemo
zhihuSwiftDemo/BCComponents/Article/View/WLYArticleDetailToolBarView.swift
1
2779
// // WLYArticleDetailToolBarView.swift // zhihuSwiftDemo // // Created by Afluy on 16/8/15. // Copyright © 2016年 helios. All rights reserved. // import Foundation import UIKit class WLYArticleDetailToolBarView: UIView { let ButtonWidth: CGFloat = 45 let ButtonHeight: CGFloat = 43 var backButton: UIButton! var nextButton: UIButton! var likeButton: UIButton! var shareButton: UIButton! var commentButton: UIButton! var buttonArray: [UIButton]! override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupView() { self.backgroundColor = UIColor.white self.backButton = UIButton(type: .custom) self.backButton.setImage(UIImage(named: "News_Navigation_Arrow"), for: UIControlState()) self.backButton.setImage(UIImage(named: "News_Navigation_Arrow_Highlight"), for: .highlighted) self.nextButton = UIButton(type: .custom) self.nextButton.setImage(UIImage(named: "News_Navigation_Next"), for: UIControlState()) self.nextButton.setImage(UIImage(named: "News_Navigation_Next_Highlight"), for: .highlighted) self.likeButton = UIButton(type: .custom) self.likeButton.setImage(UIImage(named: "News_Navigation_Vote"), for: UIControlState()) self.likeButton.setImage(UIImage(named: "News_Navigation_Voted"), for: .highlighted) self.shareButton = UIButton(type: .custom) self.shareButton.setImage(UIImage(named: "News_Navigation_Share"), for: UIControlState()) self.shareButton.setImage(UIImage(named: "News_Navigation_Share_Highlight"), for: .highlighted) self.commentButton = UIButton(type: .custom) self.commentButton.setImage(UIImage(named: "News_Navigation_Comment"), for: UIControlState()) self.commentButton.setImage(UIImage(named: "News_Navigation_Comment_Highlight"), for: .highlighted) self.buttonArray = [self.backButton, self.nextButton, self.likeButton, self.shareButton, self.commentButton] for index in 0..<self.buttonArray.count { let button = self.buttonArray[index] self.addSubview(button) button.imageView?.contentMode = .scaleAspectFit let offsetX: CGFloat = UIScreen.main.bounds.width / CGFloat(self.buttonArray.count + 1) * (CGFloat(index) + 1) - ButtonWidth / 2 button.snp.makeConstraints({ (make) in make.top.bottom.equalTo(self) make.width.equalTo(50) make.left.equalTo(self).offset(offsetX) }) } } }
mit
fc8d184b14ac2a309c5c4dcf67d88234
37.027397
140
0.648415
4.36478
false
false
false
false
FlappyHeart/balloonCat
ballooncat/GameViewController.swift
1
3366
// // GameViewController.swift // ballooncat // // Created by Alfred on 14-8-28. // Copyright (c) 2014年 HackSpace. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController{ @IBOutlet weak var gameOverView: UIView! @IBOutlet weak var shareButton: UIButton! @IBOutlet weak var totalScoreLabel: UILabel! @IBOutlet weak var bestScoreLabel: UILabel! var userDefault = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() gameOverView.hidden = true /* Pick a size for the scene */ NSNotificationCenter.defaultCenter().addObserver(self, selector: "gameOver", name: "gameOverNotification", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "pause", name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "resume", name: UIApplicationWillEnterForegroundNotification, object: nil) // let scene = GameScene(fileNamed:"GameScene") let scene = GameScene(size: CGSizeMake(320,568)) // Configure the view. let skView = self.view as SKView /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } func pause(){ var skView = self.view as SKView skView.paused = true } func resume(){ var skView = self.view as SKView skView.paused = false } func gameOver(){ gameOverView.hidden = false totalScoreLabel.text = String(userDefault.integerForKey("total")) bestScoreLabel.text = String(userDefault.integerForKey("best")) } @IBAction func restartGame(sender: UIButton) { sender.superview?.hidden = true // let scene = GameScene(fileNamed:"GameScene") let scene = GameScene(size: CGSizeMake(320,568)) // Configure the view. let skView = self.view as SKView skView.showsFPS = false skView.showsNodeCount = false /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) skView.paused = false } @IBAction func share(sender: UIButton) { //share game } }
mit
9a84abc3a9da094c404720d1626cba80
30.148148
147
0.639417
5.417069
false
false
false
false
uchuugaka/OysterKit
Mac/Tokenizer/Tokenizer/Tokenizer/AppDelegate.swift
1
7300
/* Copyright (c) 2014, RED When Excited All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Cocoa import OysterKit class AppDelegate: NSObject, NSApplicationDelegate, NSTextStorageDelegate { let keyTokenizerString = "tokString" let keyTokenizerText = "tokText" let keyColors = "tokColors" let keyColor = "tokColor" var buildTokenizerTimer : NSTimer? @IBOutlet var window: NSWindow! @IBOutlet var tokenizerDefinitionScrollView: NSScrollView! @IBOutlet var testInputScroller : NSScrollView! @IBOutlet var highlighter: TokenHighlighter! @IBOutlet var okScriptHighlighter: TokenHighlighter! @IBOutlet var colorDictionaryController: NSDictionaryController! @IBOutlet var buildProgressIndicator: NSProgressIndicator! var textString:NSString? var lastDefinition:String = "" var lastInput = "" var testInputTextView : NSTextView { return testInputScroller.contentView.documentView as! NSTextView } var tokenizerDefinitionTextView : NSTextView { return tokenizerDefinitionScrollView.contentView.documentView as! NSTextView } func registerDefaults(){ NSUserDefaults.standardUserDefaults().registerDefaults([ keyTokenizerString : "begin{\n\t\"O\".\"K\"->oysterKit\n}", keyTokenizerText : "OK", keyColors : [ "oysterKit" : NSArchiver.archivedDataWithRootObject(NSColor.purpleColor()) ] ]) } func saveToDefaults(){ var defaults = NSUserDefaults.standardUserDefaults() defaults.setValue(tokenizerDefinitionTextView.string, forKey: keyTokenizerString) defaults.setValue(highlighter.textStorage.string, forKey: keyTokenizerText) var tokenColorDict = [String:NSData]() for (tokenName:String, color:NSColor) in highlighter.tokenColorMap{ tokenColorDict[tokenName] = NSArchiver.archivedDataWithRootObject(color) } defaults.setValue(tokenColorDict, forKey: keyColors) } func loadFromDefaults(){ var defaults = NSUserDefaults.standardUserDefaults() tokenizerDefinitionTextView.string = defaults.stringForKey(keyTokenizerString) testInputTextView.string = defaults.stringForKey(keyTokenizerText) var dictionary = defaults.dictionaryForKey(keyColors) as! Dictionary<String, NSData> highlighter.tokenColorMap = [String:NSColor]() for (tokenName,tokenColorData) in dictionary { var tokenColor : NSColor = NSUnarchiver.unarchiveObjectWithData(tokenColorData) as! NSColor highlighter.tokenColorMap[tokenName] = tokenColor } } func prepareTextView(view:NSTextView){ //For some reason IB settings are not making it through view.automaticQuoteSubstitutionEnabled = false view.automaticSpellingCorrectionEnabled = false view.automaticDashSubstitutionEnabled = false //Change the font, set myself as a delegate, and set a default string view.textStorage?.font = NSFont(name: "Courier", size: 14.0) } func applicationDidFinishLaunching(aNotification: NSNotification) { registerDefaults() colorDictionaryController.initialKey = "token" colorDictionaryController.initialValue = NSColor.grayColor() //Tie the highlighters to their text views highlighter.textStorage = testInputTextView.textStorage okScriptHighlighter.textStorage = tokenizerDefinitionTextView.textStorage okScriptHighlighter.textDidChange = { self.buildTokenizer() } loadFromDefaults() okScriptHighlighter.tokenColorMap = [ "loop" : NSColor.purpleColor(), "not" : NSColor.purpleColor(), "quote" : NSColor.purpleColor(), "Char" : NSColor.stringColor(), "single-quote" :NSColor.stringColor(), "delimiter" : NSColor.stringColor(), "token" : NSColor.purpleColor(), "variable" : NSColor.variableColor(), "state-name" : NSColor.variableColor(), "start-branch" : NSColor.purpleColor(), "start-repeat" : NSColor.purpleColor(), "start-delimited" : NSColor.purpleColor(), "end-branch" :NSColor.purpleColor(), "end-repeat" : NSColor.purpleColor(), "end-delimited" : NSColor.purpleColor(), "tokenizer" : NSColor.purpleColor(), "exit-state" : NSColor.purpleColor() ] okScriptHighlighter.tokenizer = OKScriptTokenizer() prepareTextView(testInputTextView) prepareTextView(tokenizerDefinitionTextView) } func applicationWillTerminate(notification: NSNotification) { saveToDefaults() } func doBuild(){ highlighter.backgroundQueue.addOperationWithBlock(){ if let newTokenizer:Tokenizer = OKStandard.parseTokenizer(self.tokenizerDefinitionTextView.string!) { self.highlighter.tokenizer = newTokenizer } } buildProgressIndicator.stopAnimation(self) } func buildTokenizer(){ if let timer = buildTokenizerTimer { timer.invalidate() } buildProgressIndicator.startAnimation(self) buildTokenizerTimer = NSTimer(timeInterval: 1.0, target: self, selector:Selector("doBuild"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(buildTokenizerTimer!, forMode: NSRunLoopCommonModes) } } extension NSColor{ class func variableColor()->NSColor{ return NSColor(calibratedRed: 0, green: 0.4, blue: 0.4, alpha: 1.0) } class func commentColor()->NSColor{ return NSColor(calibratedRed: 0, green: 0.6, blue: 0, alpha: 1.0) } class func stringColor()->NSColor{ return NSColor(calibratedRed: 0.5, green: 0.4, blue: 0.2, alpha: 1.0) } }
bsd-2-clause
7931ebf7977f480cf8616cc892da5c6f
37.020833
131
0.682329
5.137227
false
false
false
false