repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationLineScale.swift
2
2741
// // KRActivityIndicatorAnimationBarScale.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa class KRActivityIndicatorAnimationLineScale: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes = [0.1, 0.2, 0.3, 0.4, 0.5] let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw lines for i in 0 ..< 5 { let line = KRActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } }
mit
81787f3b60ddf6487fede0b97434ba54
42.507937
128
0.685151
4.493443
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/DiffListContextCell.swift
2
6200
import UIKit protocol DiffListContextCellDelegate: class { func didTapContextExpand(indexPath: IndexPath) } class DiffListContextCell: UICollectionViewCell { static let reuseIdentifier = "DiffListContextCell" @IBOutlet var innerLeadingConstraint: NSLayoutConstraint! @IBOutlet var innerTrailingConstraint: NSLayoutConstraint! @IBOutlet var innerBottomConstraint: NSLayoutConstraint! @IBOutlet var innerTopConstraint: NSLayoutConstraint! @IBOutlet var containerStackView: UIStackView! @IBOutlet var contextItemStackView: UIStackView! @IBOutlet var headingLabel: UILabel! @IBOutlet var expandButton: UIButton! private var viewModel: DiffListContextViewModel? private var indexPath: IndexPath? weak var delegate: DiffListContextCellDelegate? func update(_ viewModel: DiffListContextViewModel, indexPath: IndexPath?) { if let indexPath = indexPath { self.indexPath = indexPath } innerLeadingConstraint.constant = viewModel.innerPadding.leading innerTrailingConstraint.constant = viewModel.innerPadding.trailing innerTopConstraint.constant = viewModel.innerPadding.top innerBottomConstraint.constant = viewModel.innerPadding.bottom containerStackView.spacing = DiffListContextViewModel.containerStackSpacing contextItemStackView.spacing = DiffListContextViewModel.contextItemStackSpacing headingLabel.font = viewModel.headingFont headingLabel.text = viewModel.heading if self.viewModel == nil { expandButton.setTitle(viewModel.expandButtonTitle, for: .normal) } else { expandButton.alpha = 0 expandButton.setTitle(viewModel.expandButtonTitle, for: .normal) UIView.animate(withDuration: 0.2) { self.expandButton.alpha = 1 } } expandButton.titleLabel?.font = viewModel.contextFont apply(theme: viewModel.theme) if needsNewContextViews(newViewModel: viewModel) { removeContextViews(from: contextItemStackView) addContextViews(to: contextItemStackView, newViewModel: viewModel) } updateContextViews(in: contextItemStackView, newViewModel: viewModel, theme: viewModel.theme) self.viewModel = viewModel } @IBAction func tappedExpandButton(_ sender: UIButton) { if let indexPath = indexPath { delegate?.didTapContextExpand(indexPath: indexPath) } } } private extension DiffListContextCell { func removeContextViews(from stackView: UIStackView) { for subview in stackView.arrangedSubviews { stackView.removeArrangedSubview(subview) subview.removeFromSuperview() } } func addContextViews(to stackView: UIStackView, newViewModel: DiffListContextViewModel) { for item in newViewModel.items { if item != nil { //needs label let label = UILabel() label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.translatesAutoresizingMaskIntoConstraints = false let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) let top = label.topAnchor.constraint(equalTo: view.topAnchor, constant: DiffListContextViewModel.contextItemTextPadding.top) let bottom = view.bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: DiffListContextViewModel.contextItemTextPadding.bottom) let leading = label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: DiffListContextViewModel.contextItemTextPadding.leading) let trailing = view.trailingAnchor.constraint(equalTo: label.trailingAnchor, constant: DiffListContextViewModel.contextItemTextPadding.trailing) view.addConstraints([top, bottom, leading, trailing]) stackView.addArrangedSubview(view) } else { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false let heightConstraint = view.heightAnchor.constraint(equalToConstant: newViewModel.emptyContextLineHeight) view.addConstraint(heightConstraint) stackView.addArrangedSubview(view) } } } func updateContextViews(in stackView: UIStackView, newViewModel: DiffListContextViewModel, theme: Theme) { for (index, subview) in stackView.arrangedSubviews.enumerated() { subview.backgroundColor = theme.colors.diffContextItemBackground subview.borderColor = theme.colors.diffContextItemBorder subview.borderWidth = 1 subview.layer.cornerRadius = 5 if let item = newViewModel.items[safeIndex: index] as? DiffListContextItemViewModel, let label = subview.subviews.first as? UILabel { label.attributedText = item.textAttributedString } } } func needsNewContextViews(newViewModel: DiffListContextViewModel) -> Bool { guard let viewModel = viewModel else { return true } if viewModel.items != newViewModel.items { return true } return false } } extension DiffListContextCell: Themeable { func apply(theme: Theme) { headingLabel.textColor = theme.colors.secondaryText expandButton.tintColor = theme.colors.link backgroundColor = theme.colors.paperBackground contentView.backgroundColor = theme.colors.paperBackground if let viewModel = viewModel { updateContextViews(in: contextItemStackView, newViewModel: viewModel, theme: theme) } } }
mit
396fd163b58035fce4a32fdc44b90308
37.993711
160
0.648871
5.799813
false
false
false
false
eselkin/DirectionFieldiOS
DirectionField/Complex.swift
1
4019
// // Complex.swift // DirectionField // // Created by Eli Selkin on 12/27/15. // Copyright © 2015 DifferentialEq. All rights reserved. // import Foundation enum ComplexError: ErrorType { case BadRegexConstruction(message: String) case BadStringConstruction(message: String) } class Complex : CustomStringConvertible { let epsilon:Float32 = 1e-5 var real:Float32 var imaginary:Float32 var description:String { get { return String(format: "%+5.4f%+5.4fi", self.real, self.imaginary) } } /* constructor -- initializer with 0, 1, or 2 Float32 attributes */ init(r: Float32 = 0.0, i: Float32 = 0.0){ self.real = r self.imaginary = i } /* constructor -- initializer with 0, 1, or 2 integer attributes */ init(r: Int = 0, i: Int = 0){ self.real = Float32(r) self.imaginary = Float32(i) } /* Constructor -- initializer for string interpolation FAILABLE convenience! */ convenience init (realimag: String) throws { // first conveniently create a new Complex instance self.init(r: 0.0, i: 0.0) // then try to store the real values do { let internalRegularExpression = try NSRegularExpression(pattern: "^([+-]?[0-9]*[.]?[0-9]+)([+-][0-9]*[.]?[0-9]+)[i]$", options: .CaseInsensitive) let matches = internalRegularExpression.matchesInString(realimag, options: .Anchored, range: NSRange(location: 0, length: realimag.utf16.count)) for match in matches as [NSTextCheckingResult] { let realString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(1)) self.real = realString.floatValue let imagString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(2)) self.imaginary = imagString.floatValue } } catch { throw ComplexError.BadRegexConstruction(message: "Bad expression") } } /** * http://floating-point-gui.de/errors/comparison/ Comparing complex conjugate to 0.0+0.0i */ func isZero() -> Bool { let absR = abs(self.real) let absI = abs(self.imaginary) if (self.real == 0 && self.imaginary == 0){ return true } else if (absR <= epsilon && absI <= epsilon){ self.real = 0 self.imaginary = 0 return true } else { return false } } /** Distance on CxR plane */ func distanceFromZero() -> Float32 { return sqrtf((self.real*self.real)+(self.imaginary*self.imaginary)) } } func +(LHS: Complex, RHS: Complex) -> Complex{ return Complex(r: (LHS.real + RHS.real), i: (LHS.imaginary + RHS.imaginary)) } func -(LHS: Complex, RHS: Complex) -> Complex { return Complex(r: (LHS.real - RHS.real), i: (LHS.imaginary - RHS.imaginary)) } func *(LHS: Complex, RHS: Complex) -> Complex { return Complex(r: (LHS.real*RHS.real)-(LHS.imaginary*RHS.imaginary), i: (LHS.real*RHS.imaginary)+(LHS.imaginary*RHS.real)) } func /(LHS: Complex, RHS: Complex) -> Complex { if LHS.isZero() { return Complex(r: 0.0, i: 0.0) } var real:Float32 = LHS.real * RHS.real real += LHS.imaginary * RHS.imaginary var imaginary = LHS.real * RHS.imaginary * -1.0 imaginary += LHS.imaginary * RHS.real let denominator:Float32 = RHS.real * RHS.real + RHS.imaginary * RHS.imaginary return Complex(r: real/denominator, i: imaginary/denominator) } func >= (LHS: Complex, RHS: Complex) -> Bool { return (LHS.real >= RHS.real) } func == (LHS: Complex, RHS: Complex) -> Bool { return (approxEqual(LHS.real, RHS: RHS.real, epsilon: 1E-10) && approxEqual(LHS.imaginary, RHS: RHS.imaginary, epsilon: 1E-10)) } func square(base:Complex) -> Complex { return base*base } func realSqrt(radicand: Complex) -> Complex { return Complex(r: sqrtf(radicand.real)) }
gpl-3.0
6ff74241a24e62ec779a3cf500a60132
30.390625
157
0.610254
3.72037
false
false
false
false
VArbiter/Rainville_iOS-Swift
Rainville-Swift/Rainville-Swift/Classes/Modules/Main/Views/CCMainHeaderView.swift
1
4002
// // CCMainHeaderView.swift // Rainville-Swift // // Created by 冯明庆 on 01/06/2017. // Copyright © 2017 冯明庆. All rights reserved. // import UIKit protocol CCPlayActionDelegate { func ccHeaderButtonActionWithPlayOrPause(bool : Bool) -> Void ; } class CCMainHeaderView: UIView { var delegate : CCPlayActionDelegate? ; @IBOutlet private weak var viewBackground: UIView! @IBOutlet private weak var labelUpDown: UILabel! @IBOutlet private weak var labelIcon: UILabel! @IBOutlet private weak var buttonPlayPause: UIButton! @IBOutlet private weak var labelDesc: UILabel! @IBOutlet private weak var viewLightLine: UIView! @IBOutlet private weak var labelAppName: UILabel! @IBOutlet weak var labelCountDown: UILabel! class func initFromNib() -> CCMainHeaderView? { let viewHeader : CCMainHeaderView? = Bundle.main.loadNibNamed("CCMainHeaderView", owner: nil, options: nil)?.first as? CCMainHeaderView; viewHeader?.frame = CGRect(x: 0, y: 0, width: ccScreenWidth(), height: ccScreenHeight()); if let viewHeaderT = viewHeader { viewHeaderT.ccSetUpDownLabel(true); viewHeaderT.ccInitSubViewSettings(); viewHeaderT.ccShowIcon(); return viewHeaderT; } return nil; } func ccSetUpDownLabel(_ bool : Bool) { let _ = self.labelUpDown.ccElegantIcons(25.0, bool ? "6" : "7"); self.labelUpDown.sizeToFit(); self.ccSetBackGroundOpaque(!bool); self.ccSetBriefInfoHidden(!bool); } func ccSetButtonStatus(bool : Bool) { self.buttonPlayPause.isSelected = bool; self.buttonPlayPause.backgroundColor = ccHexColor(bool ? 0x22A1A2 : 0x333333); } func ccIsAudioPlay() -> Bool { return self.buttonPlayPause.isSelected; } private func ccInitSubViewSettings() { let isContainEnglish : Bool = _CC_LANGUAGE_().contains("English"); if isContainEnglish { let _ = self.labelAppName.ccMusket(30.0, _CC_APP_NAME_()); } else { self.labelAppName.text = _CC_APP_NAME_(); } self.labelAppName.sizeToFit(); let _ = self.labelDesc.ccMusketWithString(_CC_APP_DESP_()); self.labelDesc.sizeToFit(); let _ = self.labelIcon.ccWeatherIcons(70.0, "\u{f006}"); // 特殊字体调用 self.labelIcon.sizeToFit(); let _ = self.labelCountDown.ccMusket(25.0, "00 : 00"); self.labelCountDown.isHidden = true; if isContainEnglish { self.buttonPlayPause.titleLabel?.font = UIFont.ccMusketFontWithSize(15.0); } self.buttonPlayPause.setTitle(_CC_PLAY_(), for: UIControlState.normal); self.buttonPlayPause.setTitle(_CC_STOP_(), for: UIControlState.selected); self.buttonPlayPause.width = self.labelIcon.width - 20.0; } private func ccShowIcon() { self.labelIcon.alpha = 0.0; weak var pSelf = self; UIView.animate(withDuration: 1.0) { pSelf?.labelIcon.alpha = 1.0; }; } private func ccSetBackGroundOpaque(_ bool : Bool) { weak var pSelf = self; UIView.animate(withDuration: 0.5) { pSelf?.viewBackground.alpha = bool ? 0.65 : 0.95; } } private func ccSetBriefInfoHidden(_ bool : Bool) { weak var pSelf = self; UIView.animate(withDuration: 0.5) { pSelf?.labelAppName.alpha = bool ? 0.0 : 1.0 ; pSelf?.labelDesc.alpha = bool ? 0.0 : 1.0 ; pSelf?.viewLightLine.alpha = bool ? 0.0 : 1.0 ; }; } @IBAction private func ccButtonPlayPauseAction(_ sender: UIButton) { sender.isSelected = !sender.isSelected; sender.backgroundColor = ccHexColor(sender.isSelected ? 0x22A1A2 : 0x333333); self.delegate?.ccHeaderButtonActionWithPlayOrPause(bool: sender.isSelected); } }
gpl-3.0
d71b928937a5bd966ce938cd4dddc0b4
34.828829
144
0.622328
3.925962
false
false
false
false
DannyKG/BoLianEducation
BoLianEducation/Task/ViewController/SearchResultController.swift
1
5960
// // SearchResultController.swift // BoLianEducation // // Created by BoLian on 2017/6/16. // Copyright © 2017年 BoLian. All rights reserved. // import UIKit class SearchResultController: SBaseTableViewController { var boolArray = Array<Bool>() var searchLabel: String? var taskType: String! lazy var searchBar: RCDSearchBar = { let barHeight = 60 * ApplicationStyle.proportion_weight() let totalHeight = 100 * ApplicationStyle.proportion_weight() let bar = RCDSearchBar.init(frame: CGRect.init(x: 0, y: (totalHeight - barHeight)/2.0, width: KUIScreenWidth, height: barHeight)) bar.delegate = (self as UISearchBarDelegate) return bar }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let text = searchLabel { if text.characters.count != 0 { getSearchTask(input: "") } } } //MARK:-- request func getSearchTask(input: String) { let model = TaskViewModel() if currentPage == 1 { MBProgressHUD.showMessage("加载中...", to: view) } model.returnBlock = { [weak self] (response: Any, count: Int) in self?.analysisData(data: response, count: count) } model.errorBlock = { [weak self] (error: Any) in self?.endRefresh() MBProgressHUD.hide(for: self?.view) let errorObject = error as AnyObject if errorObject.isKind!(of: NSString.self) { MBProgressHUD.showError(errorObject as! String) } } if input.characters.count != 0 { model.filterTask(withCondition: currentPage, label: "", inputText: input, taskType: taskType, boolArray: boolArray) } else { if let text = searchLabel { model.filterTask(withCondition: currentPage, label: text, inputText: "", taskType: taskType, boolArray: boolArray) } } } override func loadMoreCommentData() { currentPage += 1 var condition = "" if let text = searchBar.text { condition = text } getSearchTask(input: condition) } func endRefresh() { if currentPage > 1 { tableView.mj_footer.endRefreshing() self.view.endEditing(true) } } func analysisData(data: Any, count: Int) { endRefresh() MBProgressHUD.hide(for: self.view) let result = data as! Array<NSObject> itemDataArray += result if itemDataArray.count == count || result.count < 8 { tableView.mj_footer.endRefreshingWithNoMoreData() } tableView.reloadData() } override func initOriginUI() { canLoadMore = true super.initOriginUI() currentPage = 1 title = "查找任务" let topView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: KUIScreenWidth, height: 100 * ApplicationStyle.proportion_weight())) topView.backgroundColor = UIColor.white topView.addSubview(searchBar) tableView.tableHeaderView = topView } override func setTableView(){ tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: KUIScreenWidth, height: KUIScreenHeight - kNavigationBarHeight), style: UITableViewStyle.grouped) tableView.delegate = self tableView.dataSource = self tableView.showsHorizontalScrollIndicator = false tableView.showsVerticalScrollIndicator = false tableView.separatorStyle = UITableViewCellSeparatorStyle.none tableView.backgroundColor = MainRGBColor tableView.tableFooterView = UIView.init() tableView.sectionFooterHeight = 0.01 let cellHeight = 126 * ApplicationStyle.proportion_weight() + 30 tableView.rowHeight = cellHeight registerCellForTable() view.addSubview(tableView) } override func registerCellForTable() { tableView.register(UINib.init(nibName: "SearchResultCell", bundle: Bundle.main), forCellReuseIdentifier: NSStringFromClass(SearchResultCell.self)) } override func numberOfSections(in tableView: UITableView) -> Int { return itemDataArray.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(SearchResultCell.self), for: indexPath) as! SearchResultCell cell.selectionStyle = UITableViewCellSelectionStyle.none cell.updateWithTaskModel(taskModel: (itemDataArray[indexPath.section] as! AllTaskModel)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { view.endEditing(true) let model = TaskViewModel() let taskModel = self.itemDataArray[indexPath.section] as! AllTaskModel model.communityTaskDetial(with: taskModel, with: self) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SearchResultController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if let text = searchBar.text { searchBar.resignFirstResponder() itemDataArray.removeAll() getSearchTask(input: text) } } }
apache-2.0
23ed842dd3f8080641bd663a6e66d55b
33.947059
172
0.636257
5.000842
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/operations/VerifyLocker.swift
1
13630
// // VerifyLocker.swift // BartlebyKit // // Created by Benoit Pereira da silva on 25/03/2016. // // import Foundation #if !USE_EMBEDDED_MODULES import Alamofire #endif open class VerifyLocker { /** Proceed to verification Local or distant If the Locker as been grabbed its verificationMethod is set Automatically. (!) A Local locker must be added to the local locker collection before to be verifyed. - parameter lockerUID: the locker UID - parameter documentUID: the documentUID - parameter code: the code - parameter success: the sucess closure - parameter failure: the failure closure */ open static func execute( _ lockerUID: String, inDocumentWithUID documentUID: String, code: String, accessGranted success:@escaping (_ locker: Locker)->(), accessRefused failure:@escaping (_ context: HTTPContext)->()) { if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID){ // Let's determine if we should verify locally or not. let verifyer=VerifyLocker() if let _:Locker=try? Bartleby.registredObjectByUID(lockerUID){ verifyer._proceedToLocalVerification(lockerUID, inDocumentWithUID:document.UID, code: code, accessGranted: success, accessRefused: failure) }else{ verifyer._proceedToDistantVerification(lockerUID, inDocumentWithUID:document.UID, code: code, accessGranted: success, accessRefused: failure) } }else{ let context = HTTPContext( code: 1, caller: "VerifyLocker.execute", relatedURL:nil, httpStatusCode:417) context.responseString = "{\"message\":\"Attempt to verify a locker out of a document\"}" failure(context) } } /** Local verification - parameter lockerUID: lockerUID - parameter documentUID: the UID of the space - parameter code: code - parameter success: success - parameter failure: failure */ fileprivate func _proceedToLocalVerification( _ lockerUID: String, inDocumentWithUID documentUID: String, code: String, accessGranted success:@escaping (_ locker: Locker)->(), accessRefused failure:@escaping (_ context: HTTPContext)->()) { let context = HTTPContext( code: 900, caller: "VerifyLocker.proceedToLocalVerification", relatedURL:nil, httpStatusCode: 0) if let locker:Locker=try? Bartleby.registredObjectByUID(lockerUID){ locker.verificationMethod=Locker.VerificationMethod.offline if locker.code==code { self._verifyLockerBusinessLogic(locker, accessGranted: success, accessRefused: failure) } else { context.code = 1 context.responseString = "bad code" failure(context) } }else{ context.code = 2 context.responseString = "The locker do not exists locally" failure(context) } } /** Server side (== distant) verification - parameter spaceUID: spaceUID - parameter lockerUID: lockerUID - parameter code: code - parameter success: success - parameter failure: failure */ fileprivate func _proceedToDistantVerification( _ lockerUID: String, inDocumentWithUID documentUID: String, code: String, accessGranted success:@escaping (_ locker: Locker)->(), accessRefused failure:@escaping (_ context: HTTPContext)->()) { if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID){ let pathURL=document.baseURL.appendingPathComponent("locker/verify") let dictionary: Dictionary<String, AnyObject>?=["lockerUID":lockerUID as AnyObject, "code":code as AnyObject] let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:document.UID, withActionName:"VerifyLocker", forMethod:"POST", and: pathURL) do { let r=try JSONEncoding().encode(urlRequest,with:dictionary) request(r).validate().responseString(completionHandler: { (response) in let request=response.request let result=response.result let timeline=response.timeline let statusCode=response.response?.statusCode ?? 0 let metrics=Metrics() metrics.operationName="VerifyLocker" metrics.latency=timeline.latency metrics.requestDuration=timeline.requestDuration metrics.serializationDuration=timeline.serializationDuration metrics.totalDuration=timeline.totalDuration let context = HTTPContext( code: 901, caller: "VerifyLocker.execute", relatedURL:request?.url, httpStatusCode: statusCode) if let request=request{ context.request=HTTPRequest(urlRequest: request) } if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { context.responseString=utf8Text } metrics.httpContext=context document.report(metrics) var reactions = Array<Reaction> () reactions.append(Reaction.track(result: nil, context: context)) // Tracking if result.isFailure { let m = NSLocalizedString("locker verification", comment: "locker verification failure description") let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt result.isFailure is true", comment: "Unsuccessfull attempt"), body:"\(m) httpStatus code = \(statusCode) | \(String(describing: result.value))" , transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } else { if 200...299 ~= statusCode { if let data = response.data{ if let instance = try? JSON.decoder.decode(Locker.self, from: data){ success(instance) }else{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Deserialization issue", comment: "Deserialization issue"), body:"(result.value)", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } }else{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("No String Deserialization issue", comment: "No String Deserialization issue"), body:"(result.value)", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } else { // Bartlby does not currenlty discriminate status codes 100 & 101 // and treats any status code >= 300 the same way // because we consider that failures differentiations could be done by the caller. let m = NSLocalizedString("locker verification", comment: "locker verification failure description") let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt", comment: "Unsuccessfull attempt"), body:"\(m) httpStatus code = \(statusCode) | \(String(describing: result.value))" , transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } //Let's react according to the context. document.perform(reactions, forContext: context) }) }catch{ let context = HTTPContext( code:2 , caller: "VerifyLocker._proceedToDistantVerification", relatedURL:nil, httpStatusCode:500) context.responseString="{\"message\":\"\(error)}" failure(context) } }else{ let context = HTTPContext( code: 1, caller: "VerifyLocker._proceedToDistantVerification", relatedURL:nil, httpStatusCode:417) context.responseString = "{\"message\":\"Attempt to verify a locker out of a document\"}" failure(context) } } fileprivate func _verifyLockerBusinessLogic( _ locker: Locker, accessGranted success:(_ locker: Locker)->(), accessRefused failure:(_ context: HTTPContext)->()) { let context = HTTPContext( code: 902, caller: "VerifyLocker._verifyLockerBusinessLogic", relatedURL:nil, httpStatusCode: 0) context.responseString = "" if locker.verificationMethod==Locker.VerificationMethod.offline { // Let find the current user if let documentUID=locker.associatedDocumentUID { // 1. Verify the data space consistency if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID) { // 2. Verify the current user iUD if let user=document.metadata.currentUser { if user.UID == locker.userUID { // 3. Verify the date let referenceDate=Date() if locker.startDate.compare(referenceDate)==ComparisonResult.orderedAscending && locker.endDate.compare(referenceDate)==ComparisonResult.orderedDescending { success(locker) return } else { context.responseString="The Date is not valid" failure(context) return } } else { context.responseString="The current user is the natural recipient of locker" failure(context) return } } else { context.responseString="There is no current user in the document" failure(context) return } } else { context.responseString="documentUID is not valid" failure(context) return } } else { context.responseString="documentUID is not valid" failure(context) return } } else { // } context.responseString="Undefined failure" failure(context) return } }
apache-2.0
6ca307a94c5d360f73bece978ca20843
46
157
0.472267
6.552885
false
false
false
false
Zewo/Core
Sources/Axis/Time/Time.swift
5
1877
#if os(Linux) import Glibc var ts = timespec() #else import Darwin.C var factor: Double = { var mtid = mach_timebase_info_data_t() mach_timebase_info(&mtid) return Double(mtid.numer) / Double(mtid.denom) / 1E9 }() #endif /// Absolute time in seconds public func now() -> Double { #if os(Linux) clock_gettime(CLOCK_MONOTONIC, &ts) return Double(ts.tv_sec) + Double(ts.tv_nsec) / 1E9 #else return Double(mach_absolute_time()) * factor #endif } extension Double { /// Interval of `self` from now. public func fromNow() -> Double { return now() + self } } public protocol TimeUnitRepresentable { var seconds: Double { get } } extension TimeUnitRepresentable { public var milliseconds: Double { if self.seconds == .never { return .never } return self.seconds / 1000 } public var millisecond: Double { return self.milliseconds } public var second: Double { return self.seconds } public var minutes: Double { if self.seconds == .never { return .never } return self.seconds * 60 } public var minute: Double { return self.minutes } public var hours: Double { if self.seconds == .never { return .never } return self.minutes * 60 } public var hour: Double { return self.hours } } extension Double { public var int64milliseconds: Int64 { return Int64(self * 1000) } } extension Double : TimeUnitRepresentable { public var seconds: Double { return self } } extension Int : TimeUnitRepresentable { public var seconds: Double { return Double(self) } } extension Double { public static var never: Double { return -1 } }
mit
31aa2ecadb3df3f4557b5faf920c6c33
20.089888
60
0.582845
4.010684
false
false
false
false
JohsonChou/radeo
Radeo/AddChannelViewController.swift
1
2291
// // AddChannelViewController.swift // Radeo // // Created by Johnson Zhou on 2/10/15. // Copyright (c) 2015 Johnson Zhou. All rights reserved. // import UIKit import CoreData class AddChannelViewController: UIViewController { @IBAction func dismissAdd(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var callSign: UITextField! @IBOutlet weak var channelID: UITextField! @IBOutlet weak var saveButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // hiding the keyboard if touching elsewhere override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = event.allTouches()?.anyObject() as UITouch if (callSign.isFirstResponder())&&(touch.view != callSign) { // if not touching callSign, resign callSign.resignFirstResponder() } else if (channelID.isFirstResponder())&&(touch.view != channelID) { // if not touching channelID resgin channelID.resignFirstResponder() } super.touchesBegan(touches, withEvent: event) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //saving to CoreData override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if saveButton == sender as? UIBarButtonItem { return } if (channelID.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 8)&&(callSign.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) { //check if it is okay... adding alert view later let appDelegate = AppDelegate() let newItem = NSEntityDescription.insertNewObjectForEntityForName("ChannelPack", inManagedObjectContext: appDelegate.managedObjectContext!) as ChannelPack newItem.callSign = callSign.text newItem.channelID = channelID.text var error : NSError? if(appDelegate.managedObjectContext!.save(&error)) { println(error?.localizedDescription) } } } }
apache-2.0
c2ad92530660d0f7b27c108a22d56593
35.365079
203
0.656918
5.254587
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/Transaction.swift
1
7106
// // Transaction.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // 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 Storefront { /// An object representing exchange of money for a product or service. open class TransactionQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = Transaction /// The amount of money that the transaction was for. @discardableResult open func amount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> TransactionQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "amount", aliasSuffix: alias, subfields: subquery) return self } /// The amount of money that the transaction was for. @available(*, deprecated, message:"Use `amount` instead.") @discardableResult open func amountV2(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> TransactionQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "amountV2", aliasSuffix: alias, subfields: subquery) return self } /// The kind of the transaction. @discardableResult open func kind(alias: String? = nil) -> TransactionQuery { addField(field: "kind", aliasSuffix: alias) return self } /// The status of the transaction. @available(*, deprecated, message:"Use `statusV2` instead.") @discardableResult open func status(alias: String? = nil) -> TransactionQuery { addField(field: "status", aliasSuffix: alias) return self } /// The status of the transaction. @discardableResult open func statusV2(alias: String? = nil) -> TransactionQuery { addField(field: "statusV2", aliasSuffix: alias) return self } /// Whether the transaction was done in test mode or not. @discardableResult open func test(alias: String? = nil) -> TransactionQuery { addField(field: "test", aliasSuffix: alias) return self } } /// An object representing exchange of money for a product or service. open class Transaction: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = TransactionQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "amount": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "amountV2": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "kind": guard let value = value as? String else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return TransactionKind(rawValue: value) ?? .unknownValue case "status": guard let value = value as? String else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return TransactionStatus(rawValue: value) ?? .unknownValue case "statusV2": if value is NSNull { return nil } guard let value = value as? String else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return TransactionStatus(rawValue: value) ?? .unknownValue case "test": guard let value = value as? Bool else { throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } return value default: throw SchemaViolationError(type: Transaction.self, field: fieldName, value: fieldValue) } } /// The amount of money that the transaction was for. open var amount: Storefront.MoneyV2 { return internalGetAmount() } func internalGetAmount(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "amount", aliasSuffix: alias) as! Storefront.MoneyV2 } /// The amount of money that the transaction was for. @available(*, deprecated, message:"Use `amount` instead.") open var amountV2: Storefront.MoneyV2 { return internalGetAmountV2() } func internalGetAmountV2(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "amountV2", aliasSuffix: alias) as! Storefront.MoneyV2 } /// The kind of the transaction. open var kind: Storefront.TransactionKind { return internalGetKind() } func internalGetKind(alias: String? = nil) -> Storefront.TransactionKind { return field(field: "kind", aliasSuffix: alias) as! Storefront.TransactionKind } /// The status of the transaction. @available(*, deprecated, message:"Use `statusV2` instead.") open var status: Storefront.TransactionStatus { return internalGetStatus() } func internalGetStatus(alias: String? = nil) -> Storefront.TransactionStatus { return field(field: "status", aliasSuffix: alias) as! Storefront.TransactionStatus } /// The status of the transaction. open var statusV2: Storefront.TransactionStatus? { return internalGetStatusV2() } func internalGetStatusV2(alias: String? = nil) -> Storefront.TransactionStatus? { return field(field: "statusV2", aliasSuffix: alias) as! Storefront.TransactionStatus? } /// Whether the transaction was done in test mode or not. open var test: Bool { return internalGetTest() } func internalGetTest(alias: String? = nil) -> Bool { return field(field: "test", aliasSuffix: alias) as! Bool } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "amount": response.append(internalGetAmount()) response.append(contentsOf: internalGetAmount().childResponseObjectMap()) case "amountV2": response.append(internalGetAmountV2()) response.append(contentsOf: internalGetAmountV2().childResponseObjectMap()) default: break } } return response } } }
mit
cdab2ee36ea00d1a4c79415373399eb0
33
101
0.713622
3.978723
false
false
false
false
Hovo-Infinity/radio
Radio/DrawWaveform.swift
1
4276
// // DrawWaveform.swift // Radio // // Created by Hovhannes Stepanyan on 2/16/18. // Copyright © 2018 Hovhannes Stepanyan. All rights reserved. // import UIKit import Accelerate class DrawWaveform: UIView { override func draw(_ rect: CGRect) { // Drawing code //downsample and convert to [CGFloat] self.convertToPoints() var f = 0 //the waveform on top let aPath = UIBezierPath() //the waveform on the bottom let aPath2 = UIBezierPath() //lineWidth aPath.lineWidth = 2.0 aPath2.lineWidth = 2.0 //start drawing at: aPath.move(to: CGPoint(x:0.0 , y:rect.height/2 )) aPath2.move(to: CGPoint(x:0.0 , y:rect.height )) //Loop the array for _ in ReadFile.points{ //Distance between points var x:CGFloat = 2.5 //next location to draw aPath.move(to: CGPoint(x:aPath.currentPoint.x + x , y:aPath.currentPoint.y )) //y is the amplitude of each square aPath.addLine(to: CGPoint(x:aPath.currentPoint.x , y:aPath.currentPoint.y - (ReadFile.points[f] * 70) - 1.0)) aPath.close() x += 1 f += 1 } //If you want to stroke it with a Orange color UIColor.orange.set() aPath.stroke() //If you want to fill it as well aPath.fill() f = 0 aPath2.move(to: CGPoint(x:0.0 , y:rect.height/2 )) //Reflection of waveform for _ in ReadFile.points{ var x:CGFloat = 2.5 aPath2.move(to: CGPoint(x:aPath2.currentPoint.x + x , y:aPath2.currentPoint.y )) //y is the amplitude of each square aPath2.addLine(to: CGPoint(x:aPath2.currentPoint.x , y:aPath2.currentPoint.y - ((-1.0 * ReadFile.points[f]) * 50))) // aPath.close() aPath2.close() //print(aPath.currentPoint.x) x += 1 f += 1 } //If you want to stroke it with a Orange color UIColor.orange.set() //Reflection and make it transparent aPath2.stroke(with: CGBlendMode.normal, alpha: 0.5) //If you want to fill it as well aPath2.fill() } func convertToPoints() { var processingBuffer = [Float](repeating: 0.0, count: Int(ReadFile.arrayFloatValues.count)) let sampleCount = vDSP_Length(ReadFile.arrayFloatValues.count) //print(sampleCount) vDSP_vabs(ReadFile.arrayFloatValues, 1, &processingBuffer, 1, sampleCount); // print(processingBuffer) //THIS IS OPTIONAL // convert do dB // var zero:Float = 1; // vDSP_vdbcon(floatArrPtr, 1, &zero, floatArrPtr, 1, sampleCount, 1); // //print(floatArr) // // // clip to [noiseFloor, 0] // var noiseFloor:Float = -50.0 // var ceil:Float = 0.0 // vDSP_vclip(floatArrPtr, 1, &noiseFloor, &ceil, // floatArrPtr, 1, sampleCount); //print(floatArr) var multiplier = 1.0 print(multiplier) if multiplier < 1{ multiplier = 1.0 } let samplesPerPixel = Int(150 * multiplier) let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: Int(samplesPerPixel)) let downSampledLength = Int(ReadFile.arrayFloatValues.count / samplesPerPixel) var downSampledData = [Float](repeating:0.0, count:downSampledLength) vDSP_desamp(processingBuffer, vDSP_Stride(samplesPerPixel), filter, &downSampledData, vDSP_Length(downSampledLength), vDSP_Length(samplesPerPixel)) // print(" DOWNSAMPLEDDATA: \(downSampledData.count)") //convert [Float] to [CGFloat] array ReadFile.points = downSampledData.map{CGFloat($0)} } }
gpl-3.0
a339ef937a31712f1763c050b34a3a9e
31.633588
128
0.522105
4.300805
false
false
false
false
ul7290/realm-cocoa
RealmSwift-swift1.2/Realm.swift
1
25184
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** A Realm instance (also referred to as "a realm") represents a Realm database. Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`). Realm instances are cached internally, and constructing equivalent Realm objects (with the same path or identifier) produces limited overhead. If you specifically want to ensure a Realm object is destroyed (for example, if you wish to open a realm, check some property, and then possibly delete the realm file and re-open it), place the code which uses the realm within an `autoreleasepool {}` and ensure you have no other strong references to it. :warning: Realm instances are not thread safe and can not be shared across threads or dispatch queues. You must construct a new instance on each thread you want to interact with the realm on. For dispatch queues, this means that you must call it in each block which is dispatched, as a queue is not guaranteed to run on a consistent thread. */ public final class Realm { // MARK: Properties /// Path to the file where this Realm is persisted. public var path: String { return rlmRealm.path } /// Indicates if this Realm was opened in read-only mode. public var readOnly: Bool { return rlmRealm.readOnly } /// The Schema used by this realm. public var schema: Schema { return Schema(rlmRealm.schema) } /// Returns the `Configuration` that was used to create this `Realm` instance. public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) } /// Indicates if this Realm contains any objects. public var isEmpty: Bool { return rlmRealm.isEmpty } // MARK: Initializers /** Obtains a Realm instance with the given configuration. Defaults to the default Realm configuration, which can be changed by setting `Realm.Configuration.defaultConfiguration`. :param: configuration The configuration to use when creating the Realm instance. :param: error If an error occurs, upon return contains an `NSError` object that describes the problem. If you are not interested in possible errors, omit the argument, or pass in `nil`. */ public convenience init?(configuration: Configuration, error: NSErrorPointer = nil) { if let rlmRealm = RLMRealm(configuration: configuration.rlmConfiguration, error: error) { self.init(rlmRealm) } else { self.init(RLMRealm()) return nil } } /** Obtains a Realm instance with the default `Realm.Configuration`. */ public convenience init() { let rlmRealm = RLMRealm.defaultRealm() self.init(rlmRealm) } /** Obtains a Realm instance persisted at the specified file path. :param: path Path to the realm file. */ public convenience init(path: String) { self.init(RLMRealm(path: path, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: nil, error: nil)!) } // MARK: Transactions /** Performs actions contained within the given block inside a write transation. Write transactions cannot be nested, and trying to execute a write transaction on a `Realm` which is already in a write transaction will throw an exception. Calls to `write` from `Realm` instances in other threads will block until the current write transaction completes. Before executing the write transaction, `write` updates the `Realm` to the latest Realm version, as if `refresh()` was called, and generates notifications if applicable. This has no effect if the `Realm` was already up to date. :param: block The block to be executed inside a write transaction. :param: error If an error occurs, upon return contains an `NSError` object that describes the problem. If you are not interested in possible errors, omit the argument, or pass in `nil`. :returns: Whether the transaction succeeded. */ public func write(error: NSErrorPointer = nil, @noescape block: (() -> Void)) -> Bool { return rlmRealm.transactionWithBlock(block, error: error) } /** Begins a write transaction in a `Realm`. Only one write transaction can be open at a time. Write transactions cannot be nested, and trying to begin a write transaction on a `Realm` which is already in a write transaction will throw an exception. Calls to `beginWrite` from `Realm` instances in other threads will block until the current write transaction completes. Before beginning the write transaction, `beginWrite` updates the `Realm` to the latest Realm version, as if `refresh()` was called, and generates notifications if applicable. This has no effect if the `Realm` was already up to date. It is rarely a good idea to have write transactions span multiple cycles of the run loop, but if you do wish to do so you will need to ensure that the `Realm` in the write transaction is kept alive until the write transaction is committed. */ public func beginWrite() { rlmRealm.beginWriteTransaction() } /** Commits all writes operations in the current write transaction, and ends the transaction. Calling this when not in a write transaction will throw an exception. :param: error If an error occurs, upon return contains an `NSError` object that describes the problem. If you are not interested in possible errors, omit the argument, or pass in `nil`. :returns: Whether the transaction succeeded. */ public func commitWrite(error: NSErrorPointer = nil) -> Bool { return rlmRealm.commitWriteTransaction(error) } /** Revert all writes made in the current write transaction and end the transaction. This rolls back all objects in the Realm to the state they were in at the beginning of the write transaction, and then ends the transaction. This restores the data for deleted objects, but does not revive invalidated object instances. Any `Object`s which were added to the Realm will be invalidated rather than switching back to standalone objects. Given the following code: ```swift let oldObject = objects(ObjectType).first! let newObject = ObjectType() realm.beginWrite() realm.add(newObject) realm.delete(oldObject) realm.cancelWrite() ``` Both `oldObject` and `newObject` will return `true` for `invalidated`, but re-running the query which provided `oldObject` will once again return the valid object. Calling this when not in a write transaction will throw an exception. */ public func cancelWrite() { rlmRealm.cancelWriteTransaction() } /** Indicates if this Realm is currently in a write transaction. :warning: Wrapping mutating operations in a write transaction if this property returns `false` may cause a large number of write transactions to be created, which could negatively impact Realm's performance. Always prefer performing multiple mutations in a single transaction when possible. */ public var inWriteTransaction: Bool { return rlmRealm.inWriteTransaction } // MARK: Adding and Creating objects /** Adds or updates an object to be persisted it in this Realm. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. When added, all (child) relationships referenced by this object will also be added to the Realm if they are not already in it. If the object or any related objects already belong to a different Realm an exception will be thrown. Use one of the `create` functions to insert a copy of a persisted object into a different Realm. The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `invalidated` must be false). :param: object Object to be added to this Realm. :param: update If true will try to update existing objects with the same primary key. */ public func add(object: Object, update: Bool = false) { if update && object.objectSchema.primaryKeyProperty == nil { throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated") } RLMAddObjectToRealm(object, rlmRealm, update) } /** Adds or updates objects in the given sequence to be persisted it in this Realm. :see: add(object:update:) :warning: This method can only be called during a write transaction. :param: objects A sequence which contains objects to be added to this Realm. :param: update If true will try to update existing objects with the same primary key. */ public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) { for obj in objects { add(obj, update: update) } } /** Create an `Object` with the given value. Creates or updates an instance of this object and adds it to the `Realm` populating the object with the given value. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. :warning: This method can only be called during a write transaction. :param: type The object type to create. :param: value The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in an `Array`, all properties must be present, valid and in the same order as the properties defined in the model. :param: update If true will try to update existing objects with the same primary key. :returns: The created object. */ public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T { if update && schema[T.className()]?.primaryKeyProperty == nil { throwRealmException("'\(T.className())' does not have a primary key and can not be updated") } return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, T.className(), value, update), T.self) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `create(type:value:update:)`. Creates or updates an object with the given class name and adds it to the `Realm`, populating the object with the given value. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. :warning: This method can only be called during a write transaction. :param: className The class name of the object to create. :param: value The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in an `Array`, all properties must be present, valid and in the same order as the properties defined in the model. :param: update If true will try to update existing objects with the same primary key. :returns: The created object. :nodoc: */ public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject { if update && schema[className]?.primaryKeyProperty == nil { throwRealmException("'\(className)' does not have a primary key and can not be updated") } return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self) } // MARK: Deleting objects /** Deletes the given object from this Realm. :warning: This method can only be called during a write transaction. :param: object The object to be deleted. */ public func delete(object: Object) { RLMDeleteObjectFromRealm(object, rlmRealm) } /** Deletes the given objects from this Realm. :warning: This method can only be called during a write transaction. :param: objects The objects to be deleted. This can be a `List<Object>`, `Results<Object>`, or any other enumerable `SequenceType` which generates `Object`. */ public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) { for obj in objects { delete(obj) } } /** Deletes the given objects from this Realm. :warning: This method can only be called during a write transaction. :param: objects The objects to be deleted. Must be `List<Object>`. :nodoc: */ public func delete<T: Object>(objects: List<T>) { rlmRealm.deleteObjects(objects._rlmArray) } /** Deletes the given objects from this Realm. :warning: This method can only be called during a write transaction. :param: objects The objects to be deleted. Must be `Results<Object>`. :nodoc: */ public func delete<T: Object>(objects: Results<T>) { rlmRealm.deleteObjects(objects.rlmResults) } /** Deletes all objects from this Realm. :warning: This method can only be called during a write transaction. */ public func deleteAll() { RLMDeleteAllObjectsFromRealm(rlmRealm) } // MARK: Object Retrieval /** Returns all objects of the given type in the Realm. :param: type The type of the objects to be returned. :returns: All objects of the given type in Realm. */ public func objects<T: Object>(type: T.Type) -> Results<T> { return Results<T>(RLMGetObjects(rlmRealm, T.className(), nil)) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `objects(type:)`. Returns all objects for a given class name in the Realm. :warning: This method is useful only in specialized circumstances. :param: className The class name of the objects to be returned. :returns: All objects for the given class name as dynamic objects :nodoc: */ public func dynamicObjects(className: String) -> Results<DynamicObject> { return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil)) } /** Get an object with the given primary key. Returns `nil` if no object exists with the given primary key. This method requires that `primaryKey()` be overridden on the given subclass. :see: Object.primaryKey() :param: type The type of the objects to be returned. :param: key The primary key of the desired object. :returns: An object of type `type` or `nil` if an object with the given primary key does not exist. */ public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? { return unsafeBitCast(RLMGetObject(rlmRealm, type.className(), key), Optional<T>.self) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `objectForPrimaryKey(type:key:)`. Get a dynamic object with the given class name and primary key. Returns `nil` if no object exists with the given class name and primary key. This method requires that `primaryKey()` be overridden on the given subclass. :see: Object.primaryKey() :warning: This method is useful only in specialized circumstances. :param: className The class name of the object to be returned. :param: key The primary key of the desired object. :returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist. :nodoc: */ public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? { return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self) } // MARK: Notifications /** Add a notification handler for changes in this Realm. :param: block A block which is called to process Realm notifications. It receives the following parameters: - `Notification`: The incoming notification. - `Realm`: The realm for which this notification occurred. :returns: A notification token which can later be passed to `removeNotification(_:)` to remove this notification. */ public func addNotificationBlock(block: NotificationBlock) -> NotificationToken { return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block)) } /** Remove a previously registered notification handler using the token returned from `addNotificationBlock(_:)` :param: notificationToken The token returned from `addNotificationBlock(_:)` corresponding to the notification block to remove. */ public func removeNotification(notificationToken: NotificationToken) { rlmRealm.removeNotification(notificationToken) } // MARK: Autorefresh and Refresh /** Whether this Realm automatically updates when changes happen in other threads. If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm to update it to get the latest version. Note that on background threads, the run loop is not run by default and you will will need to manually call `refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`. Even with this enabled, you can still call `refresh()` at any time to update the Realm before the automatic refresh would occur. Notifications are sent when a write transaction is committed whether or not this is enabled. Disabling this on a `Realm` without any strong references to it will not have any effect, and it will switch back to YES the next time the `Realm` object is created. This is normally irrelevant as it means that there is nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong references to the containing `Realm`), but it means that setting `Realm().autorefresh = false` in `application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work. Defaults to true. */ public var autorefresh: Bool { get { return rlmRealm.autorefresh } set { rlmRealm.autorefresh = newValue } } /** Update a `Realm` and outstanding objects to point to the most recent data for this `Realm`. :returns: Whether the realm had any updates. Note that this may return true even if no data has actually changed. */ public func refresh() -> Bool { return rlmRealm.refresh() } // MARK: Invalidation /** Invalidate all `Object`s and `Results` read from this Realm. A Realm holds a read lock on the version of the data accessed by it, so that changes made to the Realm on different threads do not modify or delete the data seen by this Realm. Calling this method releases the read lock, allowing the space used on disk to be reused by later write transactions rather than growing the file. This method should be called before performing long blocking operations on a background thread on which you previously read data from the Realm which you no longer need. All `Object`, `Results` and `List` instances obtained from this `Realm` on the current thread are invalidated, and can not longer be used. The `Realm` itself remains valid, and a new read transaction is implicitly begun the next time data is read from the Realm. Calling this method multiple times in a row without reading any data from the Realm, or before ever reading any data from the Realm is a no-op. This method cannot be called on a read-only Realm. */ public func invalidate() { rlmRealm.invalidate() } // MARK: Writing a Copy /** Write an encrypted and compacted copy of the Realm to the given path. The destination file cannot already exist. Note that if this is called from within a write transaction it writes the *current* data, and not data when the last write transaction was committed. :param: path Path to save the Realm to. :param: encryptionKey Optional 64-byte encryption key to encrypt the new file with. :returns: If an error occurs, returns an `NSError` object, otherwise `nil`. :returns: Whether the realm was copied successfully. */ public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) -> NSError? { var error: NSError? if let encryptionKey = encryptionKey { rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey, error: &error) } else { rlmRealm.writeCopyToPath(path, error: &error) } return error } // MARK: Internal internal var rlmRealm: RLMRealm internal init(_ rlmRealm: RLMRealm) { self.rlmRealm = rlmRealm } } // MARK: Equatable extension Realm: Equatable { } /// Returns whether the two realms are equal. public func ==(lhs: Realm, rhs: Realm) -> Bool { return lhs.rlmRealm == rhs.rlmRealm } // MARK: Notifications /// A notification due to changes to a realm. public enum Notification: String { /** Posted when the data in a realm has changed. DidChange is posted after a realm has been refreshed to reflect a write transaction, i.e. when an autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:block:)`/`beginWrite()`, and after a local write transaction is committed. */ case DidChange = "RLMRealmDidChangeNotification" /** Posted when a write transaction has been committed to a Realm on a different thread for the same file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the notification has a chance to run. Realms with autorefresh disabled should normally have a handler for this notification which calls `refresh()` after doing some work. While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra copy of the data for the un-refreshed Realm. */ case RefreshRequired = "RLMRealmRefreshRequiredNotification" } /// Closure to run when the data in a Realm was modified. public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock { return { rlmNotification, rlmRealm in return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm)) } }
apache-2.0
372882a1d431e5fc7fdf3308de2cf9f9
38.35
125
0.689565
4.885354
false
false
false
false
EZ-NET/ESOcean
ESOcean/ProcessArguments/ProcessArguments.swift
1
3776
// // ProcessArguments.swift // ESOcean // // Created by Tomohiro Kumagai on H27/06/14. // // import Foundation import Swim public protocol ProcessArgumentOption : Hashable { associatedtype Name associatedtype Value var name:Name { get } var value:Value? { get } } extension CollectionType where Generator.Element : ProcessArgumentOption, Generator.Element.Name == String { public func indexOf(name:String) -> Index? { return self.indexOf { $0.name == name } } public subscript(name:String) -> Generator.Element.Value? { guard let index = self.indexOf(name) else { fatalError("'\(name)' is not found.") } return self[index].value } public func contains(name:String) -> Bool { return self.contains { $0.name == name } } public func containsAll(names:String...) -> Bool { return meetsAllOf(names) { self.contains($0) } } } public final class ProcessArguments { public struct Option : ProcessArgumentOption { public var name:String public var value:String? public var hashValue:Int { return name.hash } public init(_ name:String) { self.init(name, nil) } public init(_ name:String, _ value:String?) { self.name = name self.value = value } } public typealias Values = Array<String> public typealias Options = Set<Option> public internal(set) var values:Values public internal(set) var options:Options public init(_ arguments:[String], optionNamesWithNoValue:Set<String>) { var buffer = ( optionName:String?(), values:Values(), options:Options() ) let isOptionName = { (name:String) -> Bool in name.hasPrefix("-") } let insertOptionIfNeeded = { ()->Void in if let name = buffer.optionName { buffer.options.insert(Option(name)) buffer.optionName = nil } } let isOptionWithNoValue = { (name:String) -> Bool in optionNamesWithNoValue.contains(name) } for i in arguments.indices { let argument = arguments[i] if isOptionName(argument) { // オプション名が連続で登場した場合は、前に見つけたオプションを登録します。 insertOptionIfNeeded() buffer.optionName = argument // 値を取らないオプションの場合は、ここで値を登録します。 if isOptionWithNoValue(argument) { insertOptionIfNeeded() } } else { if let name = buffer.optionName { // 直前がオプションだった場合は、その値として記録します。 buffer.options.insert(Option(name, argument)) buffer.optionName = nil } else { // 直前がオプションではなかった場合は、普通の値として記録します。 buffer.values.append(argument) } } } // ループ終了後にオプション名が残っていた場合は、それを登録します。 insertOptionIfNeeded() self.values = buffer.values self.options = buffer.options } public convenience init(_ arguments:[String], optionNamesWithNoValue:String...) { self.init(arguments, optionNamesWithNoValue: Set(optionNamesWithNoValue)) } public convenience init(_ arguments:String...) { self.init(arguments, optionNamesWithNoValue: []) } public convenience init(optionNamesWithNoValue:String...) { self.init(optionNamesWithNoValue: Set(optionNamesWithNoValue)) } public convenience init(optionNamesWithNoValue:Set<String>) { self.init(NSProcessInfo.processInfo().arguments, optionNamesWithNoValue: []) } public convenience init() { self.init(optionNamesWithNoValue: []) } } public func == (lhs:ProcessArguments.Option, rhs:ProcessArguments.Option) -> Bool { return lhs.name == rhs.name }
mit
34489a55baced48edd21969b0f9ab763
18.391061
108
0.670605
3.401961
false
false
false
false
en2de/Geode
Geode/Extensions/UIView+Extensions.swift
1
1289
// // UIView+Extensions.swift // Geode // // Created by envy.chen on 30/09/2016. // Copyright © 2016 en2de.github.io. All rights reserved. // import Foundation import UIKit extension UIView { var width: CGFloat { get { return frame.width } set { var f = frame f.size.width = newValue frame = f } } var height: CGFloat { get { return frame.height } set { var f = frame f.size.height = newValue frame = f } } var top: CGFloat { get { return frame.minY } set { var f = frame f.origin.y = newValue frame = f } } var left: CGFloat { get { return frame.minX } set { var f = frame f.origin.x = newValue frame = f } } var bottom: CGFloat { get { return frame.maxY } set { top += newValue - bottom } } var right: CGFloat { get { return frame.maxX } set { left += newValue - right } } }
mit
d3fd5013cbd6465aa5a077dc8ea9b596
16.405405
58
0.40295
4.519298
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/OperatorUsageWhitespaceRule.swift
1
9096
import Foundation import SourceKittenFramework import SwiftSyntax struct OperatorUsageWhitespaceRule: OptInRule, CorrectableRule, ConfigurationProviderRule, SourceKitFreeRule { var configuration = OperatorUsageWhitespaceConfiguration() init() {} static let description = RuleDescription( identifier: "operator_usage_whitespace", name: "Operator Usage Whitespace", description: "Operators should be surrounded by a single whitespace when they are being used.", kind: .style, nonTriggeringExamples: OperatorUsageWhitespaceRuleExamples.nonTriggeringExamples, triggeringExamples: OperatorUsageWhitespaceRuleExamples.triggeringExamples, corrections: OperatorUsageWhitespaceRuleExamples.corrections ) func validate(file: SwiftLintFile) -> [StyleViolation] { return violationRanges(file: file).map { range, _ in StyleViolation(ruleDescription: Self.description, severity: configuration.severityConfiguration.severity, location: Location(file: file, byteOffset: range.location)) } } private func violationRanges(file: SwiftLintFile) -> [(ByteRange, String)] { OperatorUsageWhitespaceVisitor( allowedNoSpaceOperators: configuration.allowedNoSpaceOperators ) .walk(file: file, handler: \.violationRanges) .filter { byteRange, _ in !configuration.skipAlignedConstants || !isAlignedConstant(in: byteRange, file: file) }.sorted { lhs, rhs in lhs.0.location < rhs.0.location } } func correct(file: SwiftLintFile) -> [Correction] { let violatingRanges = violationRanges(file: file) .compactMap { byteRange, correction -> (NSRange, String)? in guard let range = file.stringView.byteRangeToNSRange(byteRange) else { return nil } return (range, correction) } .filter { range, _ in return file.ruleEnabled(violatingRanges: [range], for: self).isNotEmpty } var correctedContents = file.contents var adjustedLocations = [Int]() for (violatingRange, correction) in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: correction) adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: Self.description, location: Location(file: file, characterOffset: $0)) } } private func isAlignedConstant(in byteRange: ByteRange, file: SwiftLintFile) -> Bool { // Make sure we have match with assignment operator and with spaces before it guard let matchedString = file.stringView.substringWithByteRange(byteRange) else { return false } let equalityOperatorRegex = regex("\\s+=\\s") guard let match = equalityOperatorRegex.firstMatch( in: matchedString, options: [], range: matchedString.fullNSRange), match.range == matchedString.fullNSRange else { return false } guard let (lineNumber, _) = file.stringView.lineAndCharacter(forByteOffset: byteRange.upperBound), case let lineIndex = lineNumber - 1, lineIndex >= 0 else { return false } // Find lines above and below with the same location of = let currentLine = file.stringView.lines[lineIndex].content let index = currentLine.firstIndex(of: "=") guard let offset = index.map({ currentLine.distance(from: currentLine.startIndex, to: $0) }) else { return false } // Look around for assignment operator in lines around let lineIndexesAround = (1...configuration.linesLookAround) .flatMap { [lineIndex + $0, lineIndex - $0] } func isValidIndex(_ idx: Int) -> Bool { return idx != lineIndex && idx >= 0 && idx < file.stringView.lines.count } for lineIndex in lineIndexesAround where isValidIndex(lineIndex) { let line = file.stringView.lines[lineIndex].content guard !line.isEmpty else { continue } let index = line.index(line.startIndex, offsetBy: offset, limitedBy: line.index(line.endIndex, offsetBy: -1)) if index.map({ line[$0] }) == "=" { return true } } return false } } private class OperatorUsageWhitespaceVisitor: SyntaxVisitor { private let allowedNoSpaceOperators: Set<String> private(set) var violationRanges: [(ByteRange, String)] = [] init(allowedNoSpaceOperators: [String]) { self.allowedNoSpaceOperators = Set(allowedNoSpaceOperators) super.init(viewMode: .sourceAccurate) } override func visitPost(_ node: BinaryOperatorExprSyntax) { if let violation = violation(operatorToken: node.operatorToken) { violationRanges.append(violation) } } override func visitPost(_ node: InitializerClauseSyntax) { if let violation = violation(operatorToken: node.equal) { violationRanges.append(violation) } } override func visitPost(_ node: TypeInitializerClauseSyntax) { if let violation = violation(operatorToken: node.equal) { violationRanges.append(violation) } } override func visitPost(_ node: AssignmentExprSyntax) { if let violation = violation(operatorToken: node.assignToken) { violationRanges.append(violation) } } override func visitPost(_ node: TernaryExprSyntax) { if let violation = violation(operatorToken: node.colonMark) { violationRanges.append(violation) } if let violation = violation(operatorToken: node.questionMark) { violationRanges.append(violation) } } override func visitPost(_ node: UnresolvedTernaryExprSyntax) { if let violation = violation(operatorToken: node.colonMark) { violationRanges.append(violation) } if let violation = violation(operatorToken: node.questionMark) { violationRanges.append(violation) } } private func violation(operatorToken: TokenSyntax) -> (ByteRange, String)? { guard let previousToken = operatorToken.previousToken, let nextToken = operatorToken.nextToken else { return nil } let noSpacingBefore = previousToken.trailingTrivia.isEmpty && operatorToken.leadingTrivia.isEmpty let noSpacingAfter = operatorToken.trailingTrivia.isEmpty && nextToken.leadingTrivia.isEmpty let noSpacing = noSpacingBefore || noSpacingAfter let operatorText = operatorToken.withoutTrivia().text if noSpacing && allowedNoSpaceOperators.contains(operatorText) { return nil } let tooMuchSpacingBefore = previousToken.trailingTrivia.containsTooMuchWhitespacing && !operatorToken.leadingTrivia.containsNewlines() let tooMuchSpacingAfter = operatorToken.trailingTrivia.containsTooMuchWhitespacing && !operatorToken.trailingTrivia.containsNewlines() let tooMuchSpacing = (tooMuchSpacingBefore || tooMuchSpacingAfter) && !operatorToken.leadingTrivia.containsComments && !operatorToken.trailingTrivia.containsComments && !nextToken.leadingTrivia.containsComments guard noSpacing || tooMuchSpacing else { return nil } let location = ByteCount(previousToken.endPositionBeforeTrailingTrivia) let endPosition = ByteCount(nextToken.positionAfterSkippingLeadingTrivia) let range = ByteRange( location: location, length: endPosition - location ) let correction = allowedNoSpaceOperators.contains(operatorText) ? operatorText : " \(operatorText) " return (range, correction) } } private extension Trivia { var containsTooMuchWhitespacing: Bool { return contains { element in guard case let .spaces(spaces) = element, spaces > 1 else { return false } return true } } var containsComments: Bool { return contains { element in switch element { case .blockComment, .docLineComment, .docBlockComment, .lineComment: return true case .carriageReturnLineFeeds, .carriageReturns, .formfeeds, .newlines, .shebang, .spaces, .tabs, .unexpectedText, .verticalTabs: return false } } } }
mit
17a594f1a88f11ecc178f9f3123bbf05
37.058577
110
0.635994
5.248702
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Lint/CaptureVariableRule.swift
1
9234
import SourceKittenFramework struct CaptureVariableRule: ConfigurationProviderRule, AnalyzerRule, CollectingRule { struct Variable: Hashable { let usr: String let offset: ByteCount } typealias USR = String typealias FileInfo = Set<USR> static let description = RuleDescription( identifier: "capture_variable", name: "Capture Variable", description: "Non-constant variables should not be listed in a closure's capture list" + " to avoid confusion about closures capturing variables at creation time.", kind: .lint, nonTriggeringExamples: [ Example(""" class C { let i: Int init(_ i: Int) { self.i = i } } let j: Int = 0 let c = C(1) let closure: () -> Void = { [j, c] in print(c.i, j) } closure() """), Example(""" let iGlobal: Int = 0 class C { class var iClass: Int { 0 } static let iStatic: Int = 0 let iInstance: Int = 0 func callTest() { var iLocal: Int = 0 test { [unowned self, iGlobal, iInstance, iLocal, iClass=C.iClass, iStatic=C.iStatic] j in print(iGlobal, iClass, iStatic, iInstance, iLocal, j) } } func test(_ completionHandler: @escaping (Int) -> Void) { } } """), Example(""" var j: Int! j = 0 let closure: () -> Void = { [j] in print(j) } closure() j = 1 closure() """), Example(""" lazy var j: Int = { 0 }() let closure: () -> Void = { [j] in print(j) } closure() j = 1 closure() """) ], triggeringExamples: [ Example(""" var j: Int = 0 let closure: () -> Void = { [j] in print(j) } closure() j = 1 closure() """), Example(""" class C { let i: Int init(_ i: Int) { self.i = i } } var c = C(0) let closure: () -> Void = { [c] in print(c.i) } closure() c = C(1) closure() """), Example(""" var iGlobal: Int = 0 class C { func callTest() { test { [iGlobal] j in print(iGlobal, j) } } func test(_ completionHandler: @escaping (Int) -> Void) { } } """), Example(""" class C { static var iStatic: Int = 0 static func callTest() { test { [↓iStatic] j in print(iStatic, j) } } static func test(_ completionHandler: @escaping (Int) -> Void) { completionHandler(2) C.iStatic = 1 completionHandler(3) } } C.callTest() """), Example(""" class C { var iInstance: Int = 0 func callTest() { test { [iInstance] j in print(iInstance, j) } } func test(_ completionHandler: @escaping (Int) -> Void) { } } """) ], requiresFileOnDisk: true ) var configuration = SeverityConfiguration(.warning) init() {} func collectInfo(for file: SwiftLintFile, compilerArguments: [String]) -> CaptureVariableRule.FileInfo { file.declaredVariables(compilerArguments: compilerArguments) } func validate(file: SwiftLintFile, collectedInfo: [SwiftLintFile: CaptureVariableRule.FileInfo], compilerArguments: [String]) -> [StyleViolation] { file.captureListVariables(compilerArguments: compilerArguments) .filter { capturedVariable in collectedInfo.values.contains { $0.contains(capturedVariable.usr) } } .map { StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file, byteOffset: $0.offset)) } } } private extension SwiftLintFile { static var checkedDeclarationKinds: [SwiftDeclarationKind] { [.varClass, .varGlobal, .varInstance, .varStatic] } func captureListVariableOffsets() -> Set<ByteCount> { Self.captureListVariableOffsets(parentEntity: structureDictionary) } static func captureListVariableOffsets(parentEntity: SourceKittenDictionary) -> Set<ByteCount> { parentEntity.substructure .reversed() .reduce(into: (foundOffsets: Set<ByteCount>(), afterClosure: nil as ByteCount?)) { acc, entity in guard let offset = entity.offset else { return } if entity.expressionKind == .closure { acc.afterClosure = offset } else if let closureOffset = acc.afterClosure, closureOffset < offset, let length = entity.length, let nameLength = entity.nameLength, entity.declarationKind == .varLocal { acc.foundOffsets.insert(offset + length - nameLength) } else { acc.afterClosure = nil } acc.foundOffsets.formUnion(captureListVariableOffsets(parentEntity: entity)) } .foundOffsets } func captureListVariables(compilerArguments: [String]) -> Set<CaptureVariableRule.Variable> { let offsets = self.captureListVariableOffsets() guard !offsets.isEmpty, let indexEntities = index(compilerArguments: compilerArguments) else { return Set() } return Set(indexEntities.traverseEntitiesDepthFirst { guard let kind = $0.kind, kind.hasPrefix("source.lang.swift.ref.var."), let usr = $0.usr, let line = $0.line, let column = $0.column, let offset = stringView.byteOffset(forLine: line, bytePosition: column) else { return nil } return offsets.contains(offset) ? CaptureVariableRule.Variable(usr: usr, offset: offset) : nil }) } func declaredVariableOffsets() -> Set<ByteCount> { Self.declaredVariableOffsets(parentStructure: structureDictionary) } static func declaredVariableOffsets(parentStructure: SourceKittenDictionary) -> Set<ByteCount> { Set( parentStructure.traverseDepthFirst { let hasSetter = $0.setterAccessibility != nil let isAutoUnwrap = $0.typeName?.hasSuffix("!") ?? false guard hasSetter, !isAutoUnwrap, let declarationKind = $0.declarationKind, checkedDeclarationKinds.contains(declarationKind), !$0.enclosedSwiftAttributes.contains(.lazy), let nameOffset = $0.nameOffset else { return [] } return [nameOffset] } ) } func declaredVariables(compilerArguments: [String]) -> Set<CaptureVariableRule.USR> { let offsets = self.declaredVariableOffsets() guard !offsets.isEmpty, let indexEntities = index(compilerArguments: compilerArguments) else { return Set() } return Set(indexEntities.traverseEntitiesDepthFirst { guard let declarationKind = $0.declarationKind, Self.checkedDeclarationKinds.contains(declarationKind), let line = $0.line, let column = $0.column, let offset = stringView.byteOffset(forLine: line, bytePosition: column), offsets.contains(offset) else { return nil } return $0.usr }) } func index(compilerArguments: [String]) -> SourceKittenDictionary? { guard let path = self.path, let response = try? Request.index(file: path, arguments: compilerArguments).sendIfNotDisabled() else { queuedPrintError(""" Could not index file at path '\(self.path ?? "...")' with the \ \(CaptureVariableRule.description.identifier) rule. """) return nil } return SourceKittenDictionary(response) } } private extension SourceKittenDictionary { var usr: String? { value["key.usr"] as? String } }
mit
6d13a5cf7175ed219ddf879b9ce10945
31.854093
117
0.496642
5.198198
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/find-the-duplicate-number.swift
1
1000
/** * Problem Link: https://leetcode.com/problems/find-the-duplicate-number/ * * Binary Search. */ class Solution { func findDuplicate(_ nums: [Int]) -> Int { var left = 1 var right = nums.count while left < right { let mid = left + (right - left) / 2 var count = 0 // Count number of numbers equal or smaller than mid. for n in nums { if n <= mid { count += 1 } } /// Key: /// For mid, we would have mid numbers smaller or equal to mid. /// If there is x numbers qualifed, and x is larger than mid, we know the duplicate number is equal or smaller than mid. /// Otherwise, left = mid + 1. /// if count <= mid { left = mid + 1 } else { right = mid } } // print("\(left) - \(right)") return left } }
mit
f9143bf66e4345d314d77c2527ac561c
28.411765
132
0.451
4.545455
false
false
false
false
DianQK/Flix
Example/Example/CalendarEvent/Event/DateSelectProvider.swift
1
6703
// // DateSelectProvider.swift // Example // // Created by DianQK on 28/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import Flix class SelectedDateDisplayProvider: SingleUITableViewCellProvider { let titleLabel = UILabel() let dateLabel = UILabel() override init() { super.init() self.contentView.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 20).isActive = true titleLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true self.contentView.addSubview(dateLabel) dateLabel.translatesAutoresizingMaskIntoConstraints = false dateLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -20).isActive = true dateLabel.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor).isActive = true } } class DatePickerProvider: SingleUITableViewCellProvider { let datePicker = UIDatePicker() init(date: Date?) { super.init() if let date = date { self.datePicker.date = date } self.itemHeight = { _ in return 216 } self.contentView.addSubview(datePicker) datePicker.translatesAutoresizingMaskIntoConstraints = false datePicker.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true datePicker.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true datePicker.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true self.selectionStyle = .none } } class TitleDescProvider: SingleUITableViewCellProvider { let titleLabel = UILabel() let descLabel = UILabel() let disposeBag = DisposeBag() override init() { super.init() self.contentView.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 20).isActive = true titleLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true self.accessoryType = .disclosureIndicator self.contentView.addSubview(descLabel) descLabel.translatesAutoresizingMaskIntoConstraints = false descLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -5).isActive = true descLabel.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor).isActive = true } } extension Reactive where Base: UILabel { public var textColor: Binder<UIColor> { return Binder(self.base, binding: { (label, textColor) in label.textColor = textColor }) } } class DateSelectGroupProvider: AnimatableTableViewGroupProvider { let dateProvider = SelectedDateDisplayProvider() let pickerProvider: DatePickerProvider let timeZoneProvider = TitleDescProvider() var providers: [_AnimatableTableViewMultiNodeProvider] { return [dateProvider, pickerProvider, timeZoneProvider] } let isActive = BehaviorRelay(value: false) let disposeBag = DisposeBag() let tapActiveChanged = PublishSubject<Bool>() let dateIsAvailable = BehaviorRelay(value: true) let isAllDay: ControlProperty<Bool> init(timeZone: Observable<TimeZone>, isAllDay: ControlProperty<Bool>, date: Date?) { self.pickerProvider = DatePickerProvider(date: date) let timeZone = timeZone.share(replay: 1, scope: .forever) self.isAllDay = isAllDay self.dateProvider.event.selectedEvent.asObservable() .withLatestFrom(self.isActive.asObservable()).map { !$0 } .do(onNext: { [weak self] (isActive) in self?.tapActiveChanged.onNext(isActive) }) .bind(to: self.isActive) .disposed(by: disposeBag) let dateformatter = Observable.combineLatest(isAllDay.asObservable(), timeZone).map { (isAllDay, timeZone) -> DateFormatter in let dateformatter = DateFormatter() dateformatter.dateFormat = isAllDay ? "EEE, MMM d, y" : "MM/dd/yy h:mm:ss a z" dateformatter.timeZone = timeZone return dateformatter } let date: Observable<String> = Observable.combineLatest(pickerProvider.datePicker.rx.date, dateformatter) { $1.string(from: $0) } Observable.combineLatest( date, dateIsAvailable.asObservable(), isActive.asObservable().distinctUntilChanged().map { $0 ? UIColor(named: "Deep Carmine Pink")! : UIColor.darkText } ) .map { (date, isAvailable, textColor) -> NSAttributedString in return NSAttributedString( string: date, attributes: [ NSAttributedString.Key.strikethroughStyle: (isAvailable ? [] : NSUnderlineStyle.single).rawValue, NSAttributedString.Key.foregroundColor: textColor ] ) } .bind(to: dateProvider.dateLabel.rx.attributedText) .disposed(by: disposeBag) timeZoneProvider.titleLabel.text = "Time Zone" timeZone.map { $0.identifier } .bind(to: self.timeZoneProvider.descLabel.rx.text) .disposed(by: disposeBag) isAllDay.asObservable() .subscribe(onNext: { [weak self] (isAllDay) in guard let `self` = self else { return } self.pickerProvider.datePicker.datePickerMode = isAllDay ? .date : .dateAndTime }) .disposed(by: disposeBag) } func createAnimatableProviders() -> Observable<[_AnimatableTableViewMultiNodeProvider]> { return Observable .combineLatest(self.isActive.asObservable(), self.isAllDay.asObservable()) { [weak self] (isActive, isAllDay) -> [_AnimatableTableViewMultiNodeProvider] in guard let `self` = self else { return [] } switch (isActive, isAllDay) { case (true, true): return [self.dateProvider, self.pickerProvider] case (true, false): return [self.dateProvider, self.pickerProvider, self.timeZoneProvider] case (false, _): return [self.dateProvider] } } .distinctUntilChanged { (lhs, rhs) -> Bool in return lhs.count == rhs.count } } }
mit
86bb010f056234918916296f5c60c37c
35.423913
167
0.656371
5.139571
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Photo/cell/PublishQuestionHeadTableViewCell.swift
1
2405
// // PublishQuestionHeadTableViewCell.swift // Whereami // // Created by ChenPengyu on 16/3/17. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import PureLayout class PublishQuestionHeadTableViewCell: UITableViewCell,UITextViewDelegate { var selectedImageView:UIImageView? var textView:MessageTextView? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } func setupUI() { self.selectedImageView = UIImageView() self.selectedImageView?.contentMode = .ScaleAspectFill self.selectedImageView?.layer.masksToBounds = true self.selectedImageView?.layer.cornerRadius = 10.0 self.contentView.addSubview(selectedImageView!) self.textView = MessageTextView() self.textView?.placeHolder = "Write your question..." // self.textView?.layer.borderWidth = 1.0 // self.textView?.layer.borderColor = UIColor.lightGrayColor().CGColor // self.textView?.layer.cornerRadius = 5.0 self.contentView.addSubview(self.textView!) self.selectedImageView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 30) self.selectedImageView?.autoPinEdgeToSuperviewEdge(.Left, withInset: 16) self.selectedImageView?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 30) self.selectedImageView?.autoSetDimensionsToSize(CGSize(width: 100,height: 100)) self.textView?.autoPinEdge(.Left, toEdge: .Right, ofView: self.selectedImageView!,withOffset: 10) self.textView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 16) self.textView?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 16) self.textView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 16) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func textViewDidChange(textView: UITextView) { if (textView == self.textView) { if (textView.text.length > 250) { self.textView!.text = textView.text.substring(0, length: 250) } } } }
mit
7be2179483d45344d39f9c355792c475
35.953846
105
0.674438
5.014614
false
false
false
false
eneko/SwiftyJIRA
Sources/JIRAServerInfo.swift
1
1590
// // JIRAServerInfo.swift // SwiftyJIRA // // Created by Eneko Alonso on 1/28/16. // Copyright © 2016 Hathway, Inc. All rights reserved. // import Foundation import SwiftyJSON public struct JIRAServerInfo { var baseUrl: String var version: String var versionNumbers: [Int] var buildNumber: Int var buildDate: NSDate? var serverTime: NSDate? var scmInfo: String var buildPartnerName: String var serverTitle: String public init(json: JSON) { baseUrl = json["baseUrl"].stringValue version = json["version"].stringValue versionNumbers = json["versionNumbers"].arrayValue.map { $0.intValue } buildNumber = json["buildNumber"].intValue let formatter = NSDateFormatter() formatter.dateFormat = "YYYY-mm-dd'T'hh:mm:ss.sssZZZ" // "2016-01-27T07:30:52.026+0000" buildDate = formatter.dateFromString(json["buildDate"].stringValue) serverTime = formatter.dateFromString(json["serverTime"].stringValue) scmInfo = json["scmInfo"].stringValue buildPartnerName = json["buildPartnerName"].stringValue serverTitle = json["serverTitle"].stringValue } } public extension JIRAServerInfo { public static func serverInfo() -> JIRAServerInfo? { let result = JIRASession.sharedSession.get("serverInfo", params: ["doHealthCheck": false]) switch result { case .Success(let data, _): return JIRAServerInfo(json: JSON(data!)) case.Failure(let error, _, _): print(error) return nil } } }
mit
8190d16e089e897a6040a6477d6e2e51
28.425926
98
0.6545
4.248663
false
false
false
false
12207480/TYCyclePagerView
TYCyclePagerViewDemo_swift/ViewController.swift
1
4812
// // ViewController.swift // TYCyclePagerViewDemo_swift // // Created by tany on 2017/7/20. // Copyright © 2017年 tany. All rights reserved. // import UIKit class ViewController: UIViewController { lazy var datas = [UIColor]() lazy var pagerView: TYCyclePagerView = { let pagerView = TYCyclePagerView() pagerView.isInfiniteLoop = true pagerView.autoScrollInterval = 3.0 return pagerView }() lazy var pageControl: TYPageControl = { let pageControl = TYPageControl() pageControl.currentPageIndicatorSize = CGSize(width: 8, height: 8) return pageControl }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.addPagerView() self.addPageControl() self.loadData() } func addPagerView() { self.pagerView.layer.borderWidth = 1; self.pagerView.dataSource = self self.pagerView.delegate = self self.pagerView.register(TYCyclePagerViewCell.classForCoder(), forCellWithReuseIdentifier: "cellId") self.view.addSubview(self.pagerView) } func addPageControl() { self.pagerView.addSubview(self.pageControl) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.pagerView.frame = CGRect(x: 0, y: 64, width: self.view.frame.width, height: 200) self.pageControl.frame = CGRect(x: 0, y: self.pagerView.frame.height - 26, width: self.pagerView.frame.width, height: 26) } func loadData() { var i = 0 while i < 5 { self.datas.append(UIColor(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1)) i += 1 } self.pageControl.numberOfPages = self.datas.count self.pagerView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Action @IBAction func switchValueChangeAction(_ sender: UISwitch) { switch sender.tag { case 0: self.pagerView.isInfiniteLoop = sender.isOn self.pagerView.updateData() case 1: self.pagerView.autoScrollInterval = sender.isOn ? 3.0 : 0 case 2: self.pagerView.layout.itemHorizontalCenter = sender.isOn UIView.animate(withDuration: 0.3, animations: { self.pagerView.setNeedUpdateLayout() }) default: break } } @IBAction func sliderValueChangeAction(_ sender: UISlider) { switch sender.tag { case 0: self.pagerView.layout.itemSize = CGSize(width: self.pagerView.frame.width*CGFloat(sender.value), height: self.pagerView.frame.height*CGFloat(sender.value)) self.pagerView.setNeedUpdateLayout(); case 1: self.pagerView.layout.itemSpacing = CGFloat(30*sender.value) self.pagerView.setNeedUpdateLayout(); case 2: self.pageControl.pageIndicatorSize = CGSize(width: CGFloat(6*(1+sender.value)), height: CGFloat(6*(1+sender.value))) self.pageControl.currentPageIndicatorSize = CGSize(width: CGFloat(8*(1+sender.value)), height: CGFloat(8*(1+sender.value))) self.pageControl.pageIndicatorSpaing = CGFloat(1+sender.value)*10; default: break; } } @IBAction func buttonAction(_ sender: UIButton) { self.pagerView.layout.layoutType = TYCyclePagerTransformLayoutType(rawValue: UInt(sender.tag))! self.pagerView.setNeedUpdateLayout() } } extension ViewController: TYCyclePagerViewDelegate, TYCyclePagerViewDataSource { // MARK: TYCyclePagerViewDataSource func numberOfItems(in pageView: TYCyclePagerView) -> Int { return self.datas.count } func pagerView(_ pagerView: TYCyclePagerView, cellForItemAt index: Int) -> UICollectionViewCell { let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cellId", for: index) cell.backgroundColor = self.datas[index] return cell } func layout(for pageView: TYCyclePagerView) -> TYCyclePagerViewLayout { let layout = TYCyclePagerViewLayout() layout.itemSize = CGSize(width: pagerView.frame.width, height: pagerView.frame.height) layout.itemSpacing = 15 layout.itemHorizontalCenter = true return layout } func pagerView(_ pageView: TYCyclePagerView, didScrollFrom fromIndex: Int, to toIndex: Int) { self.pageControl.currentPage = toIndex; } }
mit
54e246ff4c960abcef231b1f3f1da740
34.10219
167
0.642337
4.536792
false
false
false
false
nemesit/RunSwiftScriptAction
Run Swift Script/Run_Swift_Script.swift
1
3657
// // Run_Swift_Script.swift // Run Swift Script // // Created by Felix Grabowski on 17/11/2016. // Copyright © 2016 FelixGrabowski. All rights reserved. // import Foundation import Automator enum SwiftError: Error, CustomNSError { case noParameters case noScript case scriptError(String) static var errorDomain: String { return "ScriptError" } var errorCode: Int { switch self { case .noParameters: return 0 case .noScript: return 1 case .scriptError(_): return errOSAScriptError } } var errorUserInfo: [String : Any] { switch self { case .noParameters: return [:] case .noScript: return [:] case .scriptError(let message): /// the docs say OSAScriptErrorMessage should work - it doesn't /// therefore NSLocalizedDescriptionKey gets the job done return [OSAScriptErrorNumber : errOSAScriptError, OSAScriptErrorMessage : message, NSLocalizedDescriptionKey: message] } } } /// saves the input into userdefaults so that the script can use it too /// input should be Array<String> else figure out the wanted type with dump(input) /// if it is not Array<String> then it's retrieval method also needs to be changed e.g. from .stringArray(forKey... to .object(forKey... func transferInput(_ input: Any?) throws { guard let input = input as? Array<String> else { return } // switch input { // case is Array<String>: // throw SwiftError.scriptError("Array<String>") // case is String: // throw SwiftError.scriptError("String") // case is NSURL: // throw SwiftError.scriptError("NSURL") // default: // throw SwiftError.scriptError("\(dump(input))") // } /// get input to where the script can find it UserDefaults(suiteName: "com.felixgrabowski.RunSwiftScript")?.setValue(input, forKey: "input") } class Run_Swift_Script: AMBundleAction, NSTextViewDelegate { var changeVar = "not working" var hasTextView = false /// avoiding cocoa bindings @IBOutlet var textView: NSTextView? { didSet { hasTextView = true guard let t = textView else { return } t.delegate = self } } /// If the container type of the action’s AMProvides property is List, prepare an output array for later use (usually by creating an NSMutableArray object) /// Iterate through the elements of the input array and for each perform whatever operation is required and write the resulting data item to the output array override func run(withInput input: Any?) throws -> Any { guard let params = parameters else { throw SwiftError.noParameters } guard let script: String = params.object(forKey: "script" as NSString) as? String else { throw SwiftError.noScript } if script.isEmpty { return [] } // TODO: complete whitespace check try transferInput(input) let swiftOutput = try runSwift(script: script) return ["\(swiftOutput)"] } /// avoiding cocoa bindings func textDidEndEditing(_ notification: Notification) { changeVar = "working" /// call update parameters here or some other stuff updateParameters() } override func updateParameters() { guard let script = textView?.string else { return } guard let params = parameters else { return } params.setObject(script, forKey: "script" as NSString) } // override func parametersUpdated() { // } }
mit
07d4997e7230b6ad6291b858c43e2211
33.471698
161
0.638752
4.573217
false
false
false
false
Vanlol/MyYDW
Pods/ReactiveSwift/Sources/Lifetime.swift
5
3197
import Foundation import enum Result.NoError /// Represents the lifetime of an object, and provides a hook to observe when /// the object deinitializes. public final class Lifetime { private let disposables: CompositeDisposable /// A signal that sends a `completed` event when the lifetime ends. /// /// - note: Consider using `Lifetime.observeEnded` if only a closure observer /// is to be attached. public var ended: Signal<Never, NoError> { return Signal { observer in return disposables += observer.sendCompleted } } /// A flag indicating whether the lifetime has ended. public var hasEnded: Bool { return disposables.isDisposed } /// Initialize a `Lifetime` object with the supplied composite disposable. /// /// - parameters: /// - signal: The composite disposable. internal init(_ disposables: CompositeDisposable) { self.disposables = disposables } /// Initialize a `Lifetime` from a lifetime token, which is expected to be /// associated with an object. /// /// - important: The resulting lifetime object does not retain the lifetime /// token. /// /// - parameters: /// - token: A lifetime token for detecting the deinitialization of the /// associated object. public convenience init(_ token: Token) { self.init(token.disposables) } /// Observe the termination of `self`. /// /// - parameters: /// - action: The action to be invoked when `self` ends. /// /// - returns: A disposable that detaches `action` from the lifetime, or `nil` /// if `lifetime` has already ended. @discardableResult public func observeEnded(_ action: @escaping () -> Void) -> Disposable? { return disposables += action } /// Add the given disposable as an observer of `self`. /// /// - parameters: /// - disposable: The disposable to be disposed of when `self` ends. /// /// - returns: A disposable that detaches `disposable` from the lifetime, or `nil` /// if `lifetime` has already ended. @discardableResult public static func += (lifetime: Lifetime, disposable: Disposable?) -> Disposable? { return (disposable?.dispose).flatMap(lifetime.observeEnded) } } extension Lifetime { /// Factory method for creating a `Lifetime` and its associated `Token`. /// /// - returns: A `(lifetime, token)` tuple. public static func make() -> (lifetime: Lifetime, token: Token) { let token = Token() return (Lifetime(token), token) } /// A `Lifetime` that has already ended. public static let empty: Lifetime = { let disposables = CompositeDisposable() disposables.dispose() return Lifetime(disposables) }() } extension Lifetime { /// A token object which completes its signal when it deinitializes. /// /// It is generally used in conjuncion with `Lifetime` as a private /// deinitialization trigger. /// /// ``` /// class MyController { /// private let (lifetime, token) = Lifetime.make() /// } /// ``` public final class Token { /// A signal that sends a Completed event when the lifetime ends. fileprivate let disposables: CompositeDisposable public init() { disposables = CompositeDisposable() } deinit { disposables.dispose() } } }
apache-2.0
1e2dbc7ebd44b077cdd9d8db1fd1a167
28.063636
85
0.681264
3.922699
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/SwiftDate/Sources/SwiftDate/DateComponents+Extension.swift
2
8819
// SwiftDate // Manage Date/Time & Timezone in Swift // // Created by: Daniele Margutti // Email: <[email protected]> // Web: <http://www.danielemargutti.com> // // Licensed under MIT License. import Foundation // MARK: - DateComponents Extension /// Invert the value expressed by a `DateComponents` instance /// /// - parameter dateComponents: instance to invert (ie. days=5 will become days=-5) /// /// - returns: a new `DateComponents` with inverted values public prefix func - (dateComponents: DateComponents) -> DateComponents { var invertedCmps = DateComponents() DateComponents.allComponents.forEach { component in let value = dateComponents.value(for: component) if value != nil && value != Int(NSDateComponentUndefined) { invertedCmps.setValue(-value!, for: component) } } return invertedCmps } /// Sum two date components; allows us to make `"5.days + 3.hours"` by producing a single `DateComponents` /// where both `.days` and `.hours` are set. /// /// - parameter lhs: first date component /// - parameter rhs: second date component /// /// - returns: a new `DateComponents` public func + (lhs: DateComponents, rhs: DateComponents) -> DateComponents { return lhs.add(components: rhs) } /// Same as su but with diff /// /// - parameter lhs: first date component /// - parameter rhs: second date component /// /// - returns: a new `DateComponents` public func - (lhs: DateComponents, rhs: DateComponents) -> DateComponents { return lhs.add(components: rhs, multipler: -1) } /// Merge two DateComponents values `(ex. a=1.hour,1.day, b=2.hour, the sum is c=3.hours,1.day)` /// /// - Parameters: /// - lhs: left date component /// - rhs: right date component /// - Returns: the sum of valid components of two instances public func && (lhs: DateComponents, rhs: DateComponents) -> DateComponents { var mergedComponents = DateComponents() let flagSet = DateComponents.allComponents flagSet.forEach { component in func sumComponent(left: Int?, right: Int?) -> Int? { let leftValue = (left != nil && left != Int(NSDateComponentUndefined) ? left : nil) let rightValue = (right != nil && right != Int(NSDateComponentUndefined) ? right : nil) if leftValue == nil && rightValue == nil { return nil } return (leftValue ?? 0) + (rightValue ?? 0) } let sum = sumComponent(left: lhs.value(for: component), right: rhs.value(for: component)) if sum != nil { mergedComponents.setValue(sum!, for: component) } } return mergedComponents } public extension DateComponents { /// A shortcut to produce a `DateInRegion` instance from an instance of `DateComponents`. /// It's the same of `DateInRegion(components:)` init func but it may return nil (instead of throwing an exception) /// if a valid date cannot be produced. public var dateInRegion: DateInRegion? { return DateInRegion(components: self) } /// Internal function helper for + and - operators between two `DateComponents` /// /// - parameter components: components /// - parameter multipler: optional multipler for each component /// /// - returns: a new `DateComponents` instance internal func add(components: DateComponents, multipler: Int = 1) -> DateComponents { let lhs = self let rhs = components var newCmps = DateComponents() let flagSet = DateComponents.allComponents flagSet.forEach { component in let left = lhs.value(for: component) let right = rhs.value(for: component) if left != nil && right != nil && left != Int(NSDateComponentUndefined) && right != Int(NSDateComponentUndefined) { let value = left! + (right! * multipler) newCmps.setValue(value, for: component) } else { if left != nil && left != Int(NSDateComponentUndefined) { newCmps.setValue(left!, for: component) } if right != nil && right != Int(NSDateComponentUndefined) { newCmps.setValue(right!, for: component) } } } return newCmps } /// Transform a `DateComponents` instance to a dictionary where key is the `Calendar.Component` and value is the /// value associated. /// /// - returns: a new `[Calendar.Component : Int]` dict representing source `DateComponents` instance internal func toComponentsDict() -> [Calendar.Component : Int] { var list: [Calendar.Component : Int] = [:] DateComponents.allComponents.forEach { component in let value = self.value(for: component) if value != nil && value != Int(NSDateComponentUndefined) { list[component] = value! } } return list } } public extension DateComponents { /// Create a new `Date` in absolute time from a specific date by adding self components /// /// - parameter date: reference date /// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead. /// /// - returns: a new `Date` public func from(date: Date, in region: Region? = nil) -> Date? { let srcRegion = region ?? Region.GMT() return srcRegion.calendar.date(byAdding: self, to: date) } /// Create a new `DateInRegion` from another `DateInRegion` by adding self components /// Returned object has the same `Region` of the source. /// /// - parameter dateInRegion: reference `DateInRegion` /// /// - returns: a new `DateInRegion` public func from(dateInRegion: DateInRegion) -> DateInRegion? { guard let absDate = dateInRegion.region.calendar.date(byAdding: self, to: dateInRegion.absoluteDate) else { return nil } let newDateInRegion = DateInRegion(absoluteDate: absDate, in: dateInRegion.region) return newDateInRegion } /// Create a new `Date` in absolute time from a specific date by subtracting self components /// /// - parameter date: reference date /// - parameter region: optional region to define the timezone and calendar. If not specific, Region.GTM() will be used instead /// /// - returns: a new `Date` public func ago(from date: Date, in region: Region? = nil) -> Date? { let srcRegion = region ?? Region.GMT() return srcRegion.calendar.date(byAdding: -self, to: date) } /// Create a new `DateInRegion` from another `DateInRegion` by subtracting self components /// Returned object has the same `Region` of the source. /// /// - parameter dateInRegion: reference `DateInRegion` /// /// - returns: a new `DateInRegion` public func ago(fromDateInRegion date: DateInRegion) -> DateInRegion? { guard let absDate = date.region.calendar.date(byAdding: -self, to: date.absoluteDate) else { return nil } let newDateInRegion = DateInRegion(absoluteDate: absDate, in: date.region) return newDateInRegion } /// Create a new `Date` in absolute time from current date by adding self components /// /// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead. /// /// - returns: a new `Date` public func fromNow(in region: Region? = nil) -> Date? { return self.from(date: Date(), in: region) } /// Create a new `DateInRegion` from current by subtracting self components /// Returned object has the same `Region` of the source. /// /// - parameter dateInRegion: reference `DateInRegion` /// /// - returns: a new `DateInRegion` public func ago(in region: Region? = nil) -> Date? { return self.ago(from: Date(), in: region) } /// Express a DateComponents instances in another time unit you choose /// /// - parameter component: time component /// - parameter calendar: context calendar to use /// /// - returns: the value of interval expressed in selected `Calendar.Component` public func `in`(_ component: Calendar.Component, of calendar: CalendarName? = nil) -> Int? { let cal = calendar ?? CalendarName.current let dateFrom = Date() let dateTo: Date = dateFrom.add(components: self) let components: Set<Calendar.Component> = [component] let value = cal.calendar.dateComponents(components, from: dateFrom, to: dateTo).value(for: component) return value } } // MARK: - DateComponents Private Extension extension DateComponents { /// Define a list of all calendar components as a set internal static let allComponentsSet: Set<Calendar.Component> = [.nanosecond, .second, .minute, .hour, .day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal, .weekOfMonth] /// Define a list of all calendar components as array internal static let allComponents: [Calendar.Component] = [.nanosecond, .second, .minute, .hour, .day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal, .weekOfMonth] }
gpl-3.0
9ee07dc873833014dc7a1ad8d65b5f80
34.849593
156
0.680349
3.914336
false
false
false
false
koara/koara-swift
Source/TreeState.swift
1
990
class TreeState { var nodes = [Node]() var marks = [Int]() var nodesOnStack : Int = 0; var currentMark : Int = 0; func openScope() { marks.append(currentMark) currentMark = nodesOnStack } func closeScope(_ n : Node) { let a = nodeArity() currentMark = marks.removeLast() var children = Array<Node>() for _ in 0..<a { let c = popNode() c.parent = n children.append(c) } n.children = children.reversed() pushNode(n); } func addSingleValue(_ n : Node, t : Token) { openScope() n.value = t.image as AnyObject closeScope(n) } func nodeArity() -> Int { return (nodesOnStack - currentMark) } func popNode() -> Node { nodesOnStack -= 1 return nodes.removeLast() } func pushNode(_ n : Node) { nodes.append(n) nodesOnStack += 1 } }
apache-2.0
dba1cb2f2b88a0b2c6641209f9b87a54
20.521739
48
0.49798
4.057377
false
false
false
false
mohamede1945/quran-ios
Quran/AudioFilesDownloader.swift
2
3227
// // AudioFilesDownloader.swift // Quran // // Created by Mohamed Afifi on 5/15/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import BatchDownloader import PromiseKit class AudioFilesDownloader { let audioFileList: QariAudioFileListRetrieval let downloader: DownloadManager let ayahDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse> private var response: DownloadBatchResponse? init(audioFileList: QariAudioFileListRetrieval, downloader: DownloadManager, ayahDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse>) { self.audioFileList = audioFileList self.downloader = downloader self.ayahDownloader = ayahDownloader } func cancel() { response?.cancel() response = nil } func needsToDownloadFiles(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> Bool { let files = filesForQari(qari, startAyah: startAyah, endAyah: endAyah) return !files.filter { !FileManager.documentsURL.appendingPathComponent($0.destinationPath).isReachable }.isEmpty } func getCurrentDownloadResponse() -> Promise<DownloadBatchResponse?> { if let response = response { return Promise(value: response) } else { return downloader.getOnGoingDownloads().then { batches -> DownloadBatchResponse? in let downloading = batches.first { $0.isAudio } self.createRequestWithDownloads(downloading) return self.response } } } func download(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> Promise<DownloadBatchResponse?> { return ayahDownloader .execute(AyahsAudioDownloadRequest(start: startAyah, end: endAyah, qari: qari)) .then(on: .main) { responses -> DownloadBatchResponse? in // wrap the requests self.createRequestWithDownloads(responses) return self.response } } private func createRequestWithDownloads(_ batch: DownloadBatchResponse?) { guard let batch = batch else { return } response = batch response?.promise.always { [weak self] in self?.response = nil } } func filesForQari(_ qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> [DownloadRequest] { return audioFileList.get(for: qari, startAyah: startAyah, endAyah: endAyah).map { DownloadRequest(url: $0.remote, resumePath: $0.local.stringByAppendingPath(Files.downloadResumeDataExtension), destinationPath: $0.local) } } }
gpl-3.0
ac2529cf93b59b9ef2e1f4433a15e5ca
36.964706
149
0.680508
4.91172
false
false
false
false
karloscarweber/SwiftFoundations-Examples
MyFirstApp/MyFirstApp/ScreenOne.swift
1
1531
// // ScreenOne.swift // MyFirstApp // // Created by Karl Oscar Weber on 9/14/14. // Copyright (c) 2014 Karl Oscar Weber. All rights reserved. // import UIKit class ScreenOne: UIViewController, UITextFieldDelegate { let myLabel: UILabel = { let label = UILabel() label.frame = CGRectMake(20, 40, 280, 40) label.font = UIFont(name: "Helvetica", size: 16) label.text = "Hello World" return label }() var myName = "" var nameField: UITextField = { let field = UITextField() field.frame = CGRectMake(20, 100, 280, 40) field.font = UIFont(name: "Helvetica", size: 16) field.layer.borderColor = UIColor.blackColor().CGColor field.layer.borderWidth = 1.0 return field }() override func viewDidLoad() { super.viewDidLoad() myName = "Karl" myLabel.text = "Hello \(myName). My name is dave." nameField.delegate = self self.view.addSubview(myLabel) self.view.addSubview(nameField) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField!) -> Bool { myName = textField.text myLabel.text = "Hello \(myName). My name is dave." textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField!) { } }
mit
f685e321032869359090803bfffb1a1b
25.859649
65
0.60418
4.502941
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-09/ImageMetalling-09/IMPMenuHandler.swift
1
793
// // IMPMenuHandler.swift // ImageMetalling-09 // // Created by denis svinarchuk on 16.12.15. // Copyright © 2015 IMetalling. All rights reserved. // import Cocoa typealias IMPMenuObserver = ((item:NSMenuItem)->Void) enum IMPMenuTag:Int{ case zoomFit = 3004 case zoom100 = 3005 case resetLut = 3011 } class IMPMenuHandler:NSObject { private override init() {} private var didUpdateMenuHandlers = [IMPMenuObserver]() static let sharedInstance = IMPMenuHandler() var currentMenuItem:NSMenuItem?{ didSet{ for o in self.didUpdateMenuHandlers{ o(item: currentMenuItem!) } } } func addMenuObserver(observer:IMPMenuObserver){ didUpdateMenuHandlers.append(observer) } }
mit
ecf1a851ba7fb8abfb3d20f54a3c8553
20.432432
59
0.64899
4.103627
false
false
false
false
ikorn/KornUIKit
KornUIKit/Class/Component/KUITextField.swift
1
18783
// // KUITextField.swift // KornUIKit // // Created by Sutthikorn Saengrungruangsri on 2017/01/03. // Copyright © 2017 ikorn. All rights reserved. // import UIKit @IBDesignable open class KUITextField: UITextField { public typealias UpdateHandler = (ValidationError?) -> () typealias `Self` = KUITextField @IBInspectable public var maskToBounds: Bool { get { return self.layer.masksToBounds } set { self.layer.masksToBounds = newValue } } /// Corner Radius. @IBInspectable public var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } /// Border width. @IBInspectable public var borderWidth: CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } @IBInspectable public var borderColor: UIColor? { get { return self.layer.borderColor.map(UIColor.init) } set { self.layer.borderColor = newValue?.cgColor } } @IBInspectable public var shadowColor: UIColor? { get { return self.layer.shadowColor.map(UIColor.init) } set { self.layer.shadowColor = newValue?.cgColor } } @IBInspectable public var shadowOpacity: Float { get { return self.layer.shadowOpacity } set { self.layer.shadowOpacity = newValue } } @IBInspectable public var shadowOffset: CGSize { get { return self.layer.shadowOffset } set { self.layer.shadowOffset = newValue } } @IBInspectable public var shadowRadius: CGFloat { get { return self.layer.shadowRadius } set { self.layer.shadowRadius = newValue } } /// Custom image for previous button. open static var previousButtonImage: UIImage? = nil /// Custom image for next button. open static var nextButtonImage: UIImage? = nil /// Textfield input type. open var type: InputType = .any { didSet { self.keyboardType = self.type.keyboardType() } } /// Handler for update error message. open var onUpdateHandler: UpdateHandler? /// Left image view. fileprivate var leftImageView: UIImageView? /// Right image view. fileprivate var rightImageView: UIImageView? /// Content insets. open var contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 4) /// Previous text field. open weak var previousTextField: KUITextField? /// Next text field. open weak var nextTextField: KUITextField? /// Array of validators. open var validators: [KUITextFieldValidator]? /// Validation error. open var validationError: ValidationError? /// Flag indicate that there is no value inside current text field. open var isEmpty: Bool { return self.text == nil || self.text!.isEmpty } /// Flag indicate that there is error message for current text field. open var hasErrorMessage: Bool { return self.validationError != nil } internal var cachedColors: (background: UIColor, border: UIColor, text: UIColor, placeholder: UIColor)? private lazy var previousButton: UIBarButtonItem = { if let previousButtonImage: UIImage = Self.previousButtonImage { return UIBarButtonItem(image: previousButtonImage, style: .plain, target: self, action: #selector(movePrevious(sender:))) } return UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(movePrevious(sender:))) }() private lazy var nextButton: UIBarButtonItem = { if let nextButtonImage: UIImage = Self.nextButtonImage { return UIBarButtonItem(image: nextButtonImage, style: .plain, target: self, action: #selector(moveNext(sender:))) } return UIBarButtonItem(title: ">", style: .plain, target: self, action: #selector(moveNext(sender:))) }() private lazy var keyboardToolbar: UIToolbar = { let toolbar = UIToolbar() toolbar.barStyle = .default toolbar.backgroundColor = .white toolbar.tintColor = self.tintColor let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(resignFirstResponder)) toolbar.items = [ self.previousButton, self.nextButton, flexSpace, doneButton ] toolbar.sizeToFit() return toolbar }() // MARK: - Inspectable properties. @IBInspectable open var placeholderFont: UIFont? { didSet { updatePlaceholder() } } @IBInspectable open var placeholderColor: UIColor = .lightGray { didSet { updatePlaceholder() updateAccessoryView() } } @IBInspectable open var foregroundErrorColor: UIColor = .red @IBInspectable open var backgroundErrorColor: UIColor = .mistyRose @IBInspectable open var leftImage: UIImage? { didSet { self.leftViewMode = .always updateAccessoryView() } } @IBInspectable open var rightValidImage: UIImage? { didSet { updateAccessoryView() } } @IBInspectable open var rightInvalidImage: UIImage? { didSet { updateAccessoryView() } } @IBInspectable override open var placeholder: String? { didSet { updatePlaceholder() } } // MARK: - initialize. override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open func setup(delegate: UITextFieldDelegate, value: String? = nil, type: InputType, previousTextField: KUITextField? = nil, nextTextField: KUITextField? = nil, validators: [KUITextFieldValidator]? = nil, didUpdate updateHandler: @escaping UpdateHandler) { self.delegate = delegate self.text = value self.type = type self.previousTextField = previousTextField self.nextTextField = nextTextField self.validators = validators self.onUpdateHandler = updateHandler } open func showRightView(isValid: Bool) { updateRightView(shouldShow: true, isValid: isValid) } private func setup() { self.delegate = self updateColors() } private func updateAccessoryView() { let lineHeight = self.font!.lineHeight if let leftImage = self.leftImage { if self.leftImageView == nil { self.leftImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: lineHeight, height: lineHeight)) } self.leftImageView?.contentMode = .scaleAspectFit self.leftImageView?.image = leftImage.withRenderingMode(.alwaysTemplate) self.leftImageView?.tintColor = self.placeholderColor self.leftView = self.leftImageView self.leftViewMode = .always } if let validImage = self.rightValidImage { if self.rightImageView == nil { self.rightImageView = UIImageView(frame: CGRect(size: validImage.size)) } self.rightImageView?.contentMode = .scaleAspectFit self.rightView = self.rightImageView self.rightViewMode = .never } updateRightView(shouldShow: false) } // MARK: - override functions. override open func becomeFirstResponder() -> Bool { self.previousButton.isEnabled = self.previousTextField != nil self.previousButton.tintColor = self.previousButton.isEnabled ? self.tintColor : self.tintColor.withAlphaComponent(0.5) self.nextButton.isEnabled = self.nextTextField != nil self.nextButton.tintColor = self.nextButton.isEnabled ? self.tintColor : self.tintColor.withAlphaComponent(0.5) self.validationError = nil updateColors() updateRightView(shouldShow: false) self.inputAccessoryView = self.keyboardToolbar return super.becomeFirstResponder() } override open func resignFirstResponder() -> Bool { validate() return super.resignFirstResponder() } override open func textRect(forBounds bounds: CGRect) -> CGRect { let padding = (frame.height - self.font!.lineHeight) / 2 let leftPadding = (self.leftImageView?.width ?? 0) + (2 * self.contentInsets.left) let rightPadding = (self.rightImageView?.width ?? 0) + (2 * self.contentInsets.right) return CGRect(x: bounds.origin.x + leftPadding, y: bounds.origin.y + padding, width: bounds.width - leftPadding - rightPadding, height: bounds.height - padding * 2) } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override open func leftViewRect(forBounds bounds: CGRect) -> CGRect { var textRect = super.leftViewRect(forBounds: bounds) textRect.origin.x += self.contentInsets.left return textRect } // MARK: - selectors. func movePrevious(sender: UIBarButtonItem) { if let previous = self.previousTextField { _ = self.resignFirstResponder() _ = previous.becomeFirstResponder() } } func moveNext(sender: UIBarButtonItem) { if let next = self.nextTextField { _ = self.resignFirstResponder() _ = next.becomeFirstResponder() } } } extension KUITextField: UITextFieldDelegate { public func textFieldDidBeginEditing(_ textField: UITextField) { self.validationError = nil updateColors() onUpdateHandler?(nil) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return self.resignFirstResponder() } } extension KUITextField { fileprivate func validate() { self.validationError = self.validators?.flatMap { [weak self] (validator) in validator.validate(self) }.first updateColors() updateRightView(isValid: self.validationError == nil) self.onUpdateHandler?(self.validationError) } internal func updatePlaceholder() { if let placeholder = self.placeholder, let font = self.placeholderFont ?? self.font { self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [ NSForegroundColorAttributeName: self.placeholderColor, NSFontAttributeName: font ]) } } internal func updateColors() { if self.hasErrorMessage { // cache old colors. if self.cachedColors == nil { self.cachedColors = (self.backgroundColor ?? UIColor.clear, self.borderColor ?? UIColor.clear, self.textColor ?? UIColor.darkGray, self.placeholderColor) } // apply new colors. self.backgroundColor = self.backgroundErrorColor self.borderColor = self.foregroundErrorColor self.textColor = self.foregroundErrorColor self.placeholderColor = self.foregroundErrorColor } else { // apply color from cache only if available. if let cachedColors = self.cachedColors { self.backgroundColor = cachedColors.background self.borderColor = cachedColors.border self.textColor = cachedColors.text self.placeholderColor = cachedColors.placeholder // clear caches. self.cachedColors = nil } } } fileprivate func updateRightView(shouldShow: Bool = true, isValid: Bool = false) { guard let validImage = self.rightValidImage else { self.rightViewMode = .never return } if shouldShow { if isValid { self.rightImageView?.image = validImage self.rightImageView?.tintColor = UIColor(hex: 0x22CC88)! } else if let invalidImage = self.rightInvalidImage { self.rightImageView?.image = invalidImage self.rightImageView?.tintColor = self.foregroundErrorColor } self.rightView = self.rightImageView self.rightViewMode = .always } else { self.rightViewMode = .never } } } public enum InputType { case any case alphabetic case numeric case decimal case alphanumeric case hiragana case katakana case phoneNumber case email case url var regex: String? { switch self { case .any: return nil case .alphabetic: return "^[\\p{L}|\\p{M}]+$" case .numeric: return "^[\\p{N}]+$" case .decimal: return "^\\-?\\d{1,3}(,\\d{3})*(.\\d+)$" case .alphanumeric: return "^[\\p{L}|\\p{M}|\\p{N}]+$" case .hiragana: return "^[\\p{Hiragana}  ]+$" case .katakana: return "^[\\p{Katakana}  ー-]+$" case .phoneNumber: return "^[\\p{N}]+$" case .email: return "^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,6}$" case .url: return "^(https?|ftp)(:¥/¥/[-_.!~*¥'()a-zA-Z0-9;¥/?:¥@&amp;amp;=+¥$,%#]+)$" } } func keyboardType() -> UIKeyboardType { switch self { case .any, .alphabetic, .alphanumeric, .hiragana, .katakana: return .default case .numeric: return .numberPad case .decimal: return .decimalPad case .phoneNumber: return .phonePad case .email: return .emailAddress case .url: return .URL } } } public enum KUITextFieldValidator { case notSelected case empty case invalidPattern(InputType) case exactLength(Int) case minLength(Int) case maxLength(Int) case minValue(Double) case maxValue(Double) func validate(_ textField: KUITextField?) -> ValidationError? { guard let textField: KUITextField = textField else { return nil } let length: Int = (textField.text ?? "").characters.count let value: Double? = Double(textField.text ?? "") switch self { case .notSelected: if (textField is KUIDatePicker || textField is KUIPickerView) && textField.isEmpty { return ValidationError.notSelected } case .empty: if textField.isEmpty { return ValidationError.empty } case .invalidPattern(let inputType): guard let regex: String = inputType.regex else { return nil } if ((textField.text ?? "").range(of: regex, options: .regularExpression) == nil) { return ValidationError.invalidPattern(inputType) } case .exactLength(let exactLength): if length != exactLength { return ValidationError.invalidLength(exactLength, length) } case .minLength(let minLength): if length < minLength { return ValidationError.minLength(minLength, length) } case .maxLength(let maxLenth): if length > maxLenth { return ValidationError.maxLength(maxLenth, length) } case .minValue(let minValue): if let value: Double = value, value < minValue { return ValidationError.minValue(minValue, value) } case .maxValue(let maxValue): if let value: Double = value, value > maxValue { return ValidationError.maxValue(maxValue, value) } } return nil } } extension KUITextFieldValidator: Equatable { public static func ==(lhs: KUITextFieldValidator, rhs: KUITextFieldValidator) -> Bool { switch (lhs, rhs) { case (.notSelected, .notSelected): return true case (.empty, .empty): return true case (let .invalidPattern(pattern1), let .invalidPattern(pattern2)): return pattern1 == pattern2 case (let .exactLength(length1), let .exactLength(length2)): return length1 == length2 case (let .minLength(length1), let .minLength(length2)): return length1 == length2 case (let .maxLength(length1), let .maxLength(length2)): return length1 == length2 case (let .minValue(value1), let .minValue(value2)): return value1 == value2 case (let .maxValue(value1), let .maxValue(value2)): return value1 == value2 default: return false } } } public enum ValidationError { case notSelected case empty case invalidPattern(InputType) case invalidLength(Int, Int) case minLength(Int, Int) case maxLength(Int, Int) case minValue(Double, Double) case maxValue(Double, Double) }
apache-2.0
bbcc440f8d6243112a35cb867eb2f451
38.263598
175
0.55877
5.187396
false
false
false
false
xedin/swift
benchmark/single-source/RomanNumbers.swift
22
2120
//===--- RomanNumbers.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 TestsUtils // Mini benchmark implementing roman numeral conversions to/from integers. // Measures performance of Substring.starts(with:), dropFirst and String.append // with very short string arguments. let t: [BenchmarkCategory] = [.api, .String, .algorithm] let N = 270 public let RomanNumbers = [ BenchmarkInfo( name: "RomanNumbers2", runFunction: { checkId($0, upTo: N, { $0.romanNumeral }, Int.init(romanSSsWdF:)) }, tags: t), ] @inline(__always) func checkId(_ n: Int, upTo limit: Int, _ itor: (Int) -> String, _ rtoi: (String) -> Int?) { for _ in 1...n { CheckResults( zip(1...limit, (1...limit).map(itor).map(rtoi)).allSatisfy { $0 == $1 }) } } let romanTable: KeyValuePairs<String, Int> = [ "M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100_, "XC": 90_, "L": 50_, "XL": 40_, "X": 10__, "IX": 9__, "V": 5__, "IV": 4__, "I": 1, ] extension BinaryInteger { // Imperative Style // See https://www.rosettacode.org/wiki/Roman_numerals/Encode#Swift // See https://www.rosettacode.org/wiki/Roman_numerals/Decode#Swift var romanNumeral: String { var result = "" var n = self for (numeral, value) in romanTable { while n >= value { result += numeral n -= Self(value) } } return result } init?(romanSSsWdF number: String) { self = 0 var raw = Substring(number) for (numeral, value) in romanTable { while raw.starts(with: numeral) { self += Self(value) raw = raw.dropFirst(numeral.count) } } guard raw.isEmpty else { return nil } } }
apache-2.0
72da6caa893ce447f3ef9f040dbb5e02
27.648649
80
0.586792
3.605442
false
false
false
false
PANDA-Guide/PandaGuideApp
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/TweaksViewController.swift
1
2000
// // TweaksViewController.swift // SwiftTweaks // // Created by Bryan Clark on 11/5/15. // Copyright © 2015 Khan Academy. All rights reserved. // import UIKit public protocol TweaksViewControllerDelegate: class { func tweaksViewControllerRequestsDismiss(_ tweaksViewController: TweaksViewController, completion: (() -> ())?) } /// The main UI for Tweaks. /// You can init and present TweaksViewController yourself, if you'd prefer to not use TweakWindow. public final class TweaksViewController: UIViewController { private let tweakStore: TweakStore private var navController: UINavigationController! // self required for init public unowned var delegate: TweaksViewControllerDelegate internal var floatingTweaksWindowPresenter: FloatingTweaksWindowPresenter? internal static let dismissButtonTitle = NSLocalizedString("Dismiss", comment: "Button to dismiss TweaksViewController.") public init(tweakStore: TweakStore, delegate: TweaksViewControllerDelegate) { self.tweakStore = tweakStore self.delegate = delegate super.init(nibName: nil, bundle: nil) let tweakRootVC = TweaksRootViewController(tweakStore: tweakStore, delegate: self) navController = UINavigationController(rootViewController: tweakRootVC) navController.isToolbarHidden = false view.addSubview(navController.view) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TweaksViewController: TweaksRootViewControllerDelegate { internal func tweaksRootViewControllerDidPressDismissButton(_ tweaksRootViewController: TweaksRootViewController) { delegate.tweaksViewControllerRequestsDismiss(self, completion: nil) } internal func tweaksRootViewController(_ tweaksRootViewController: TweaksRootViewController, requestsFloatingUIForTweakGroup tweakGroup: TweakGroup) { delegate.tweaksViewControllerRequestsDismiss(self) { self.floatingTweaksWindowPresenter?.presentFloatingTweaksUI(forTweakGroup: tweakGroup) } } }
gpl-3.0
0f2a44bb0180929ba42d31916d5b5c3d
35.345455
151
0.808404
4.692488
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift
27
1367
// // BinaryDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 6/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents two disposable resources that are disposed together. */ public final class BinaryDisposable : DisposeBase, Cancelable { private var _disposed: Int32 = 0 // state private var disposable1: Disposable? private var disposable2: Disposable? /** - returns: Was resource disposed. */ public var disposed: Bool { get { return _disposed > 0 } } /** Constructs new binary disposable from two disposables. - parameter disposable1: First disposable - parameter disposable2: Second disposable */ init(_ disposable1: Disposable, _ disposable2: Disposable) { self.disposable1 = disposable1 self.disposable2 = disposable2 super.init() } /** Calls the disposal action if and only if the current instance hasn't been disposed yet. After invoking disposal action, disposal action will be dereferenced. */ public func dispose() { if OSAtomicCompareAndSwap32(0, 1, &_disposed) { disposable1?.dispose() disposable2?.dispose() disposable1 = nil disposable2 = nil } } }
gpl-3.0
fbb0a3cf6eea1d8a34ae3c4bb2803778
23.428571
91
0.625457
4.796491
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleStop.swift
2
2069
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Stop symbol style: ◼ \{U+2588} struct DynamicButtonStyleStop: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let thirdSize = size / 3 let a = CGPoint(x: center.x - thirdSize, y: center.y - thirdSize) let b = CGPoint(x: center.x - thirdSize, y: center.y + thirdSize) let c = CGPoint(x: center.x + thirdSize, y: center.y + thirdSize) let d = CGPoint(x: center.x + thirdSize, y: center.y - thirdSize) let p1 = PathHelper.line(from: a, to: b) let p2 = PathHelper.line(from: b, to: c) let p3 = PathHelper.line(from: c, to: d) let p4 = PathHelper.line(from: d, to: a) pathVector = DynamicButtonPathVector(p1: p1, p2: p2, p3: p3, p4: p4) } /// "Stop" style. static var styleName: String { return "Player - Stop" } }
apache-2.0
6c7b5b0d9e32018a0cf04d719070bf77
38
80
0.713111
3.885338
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Live/View/LiveTableViewCell.swift
1
4891
// // LiveTableViewCell.swift // DereGuide // // Created by zzk on 16/7/23. // Copyright © 2016年 zzk. All rights reserved. // import UIKit import TTGTagCollectionView protocol LiveTableViewCellDelegate: class { func liveTableViewCell(_ liveTableViewCell: LiveTableViewCell, didSelect liveScene: CGSSLiveScene) func liveTableViewCell(_ liveTableViewCell: LiveTableViewCell, didSelect jacketImageView: BannerView, musicDataID: Int) } class LiveTableViewCell: ReadableWidthTableViewCell { let jacketImageView = BannerView() var nameLabel = UILabel() var typeIcon = UIImageView() let collectionView = TTGTagCollectionView() var tagViews = [SongDetailLiveDifficultyView]() private var live: CGSSLive! weak var delegate: LiveTableViewCellDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) readableContentView.addSubview(jacketImageView) jacketImageView.snp.makeConstraints { (make) in make.left.top.equalTo(10) make.width.height.equalTo(66) make.bottom.lessThanOrEqualTo(-10) } jacketImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))) readableContentView.addSubview(typeIcon) typeIcon.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.equalTo(jacketImageView.snp.right).offset(10) make.width.height.equalTo(20) } nameLabel.font = UIFont.boldSystemFont(ofSize: 18) nameLabel.adjustsFontSizeToFitWidth = true nameLabel.baselineAdjustment = .alignCenters readableContentView.addSubview(nameLabel) nameLabel.snp.makeConstraints { (make) in make.left.equalTo(typeIcon.snp.right).offset(5) make.right.lessThanOrEqualTo(-10) make.centerY.equalTo(typeIcon) } readableContentView.addSubview(collectionView) collectionView.snp.makeConstraints { (make) in make.top.equalTo(43) make.left.equalTo(jacketImageView.snp.right).offset(10) make.right.equalTo(-10) make.bottom.equalTo(-10) } collectionView.delegate = self collectionView.dataSource = self collectionView.alignment = .left collectionView.horizontalSpacing = 10 collectionView.verticalSpacing = 10 collectionView.contentInset = .zero selectionStyle = .none } func setup(live: CGSSLive) { self.live = live tagViews.removeAll() jacketImageView.sd_setImage(with: live.jacketURL) typeIcon.image = live.icon nameLabel.text = live.name nameLabel.textColor = live.color for detail in live.selectedLiveDetails { let tag = SongDetailLiveDifficultyView() tag.setup(liveDetail: detail, shouldShowText: !UserDefaults.standard.shouldHideDifficultyText) tagViews.append(tag) } collectionView.reload() } @objc func handleTapGesture(_ tap: UITapGestureRecognizer) { delegate?.liveTableViewCell(self, didSelect: jacketImageView, musicDataID: live.musicDataId) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { layoutIfNeeded() collectionView.invalidateIntrinsicContentSize() return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } } extension LiveTableViewCell: TTGTagCollectionViewDelegate, TTGTagCollectionViewDataSource { func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, sizeForTagAt index: UInt) -> CGSize { let tagView = tagViews[Int(index)] tagView.sizeToFit() return tagView.frame.size } func numberOfTags(in tagCollectionView: TTGTagCollectionView!) -> UInt { return UInt(tagViews.count) } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, tagViewFor index: UInt) -> UIView! { return tagViews[Int(index)] } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, didSelectTag tagView: UIView!, at index: UInt) { let detail = live.selectedLiveDetails[Int(index)] let scene = CGSSLiveScene(live: live, difficulty: detail.difficulty) delegate?.liveTableViewCell(self, didSelect: scene) } }
mit
67226515c6a3f6058f79baf4e3680e0d
36.6
193
0.683306
5.091667
false
false
false
false
SparrowTek/LittleManComputer
LittleManComputer/Engine/Compiler.swift
1
8927
// // Compiler.swift // LittleManComputer // // Created by Thomas J. Rademaker on 8/13/19. // Copyright © 2019 SparrowTek LLC. All rights reserved. // import Foundation enum CompileError: Error { case invalidAssemblyCode // TODO: make more specific invalid assembly code errors case intExpected case general } class Compiler { struct InterpretedAssemblyCodeLine { var opCode: String var leadingLabel: String? = nil var trailingLabel: String? = nil var value: Int? = nil } // parse the assembly code that was input by the user and load the registers with the proper value // check that the assembly code entered is valid and can compile into the memory registers func compile(_ code: String) throws -> ProgramState { do { let linesOfCode = createStringArray(from: code, seperatedBy: .newlines) let interpretedLinesOfCode = try interpretLinesOfCode(linesOfCode) return try stateFromInterpretedCode(interpretedLinesOfCode) } catch let error as CompileError { throw error } } private func stateFromInterpretedCode(_ interpretedLinesOfCode: [InterpretedAssemblyCodeLine]) throws -> ProgramState { do { let leadingLabels = trackLabels(for: interpretedLinesOfCode) let registers = try setRegistersFromInterpretedAssemblyCodeLineArray(interpretedLinesOfCode, leadingLabels: leadingLabels) return ProgramState(registers: registers) } catch let error as CompileError { throw error } } private func createStringArray(from code: String, seperatedBy characterSet: CharacterSet) -> [String] { let codeWithoutLeadingAndTrailingWhiteSpace = code.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() return codeWithoutLeadingAndTrailingWhiteSpace.components(separatedBy: characterSet) } private func interpretLinesOfCodeWith1Arg(_ args: [String]) throws -> InterpretedAssemblyCodeLine { let opCode = args[0] try testForValidCodeLine(opCode: opCode, value: nil, leadingLabel: nil) return InterpretedAssemblyCodeLine(opCode: opCode) } private func interpretLinesOfCodeWith2Args(_ args: [String]) throws -> InterpretedAssemblyCodeLine { let arg1 = args[0] let arg2 = args[1] let opCode: String var value: Int? var leadingLabel: String? var trailingLabel: String? if arg1 == "dat" { opCode = arg1 guard let argAsInt = Int(arg2) else { throw CompileError.intExpected } value = argAsInt } else if arg2 == "dat" || arg2 == "hlt" { opCode = arg2 leadingLabel = arg1 value = 0 } else { opCode = arg1 trailingLabel = arg2 } try testForValidCodeLine(opCode: opCode, value: value, leadingLabel: leadingLabel) return InterpretedAssemblyCodeLine(opCode: opCode, leadingLabel: leadingLabel, trailingLabel: trailingLabel, value: value) } private func interpretLinesOfCodeWith3Args(_ args: [String]) throws -> InterpretedAssemblyCodeLine { var value: Int? var trailingLabel: String? let leadingLabel = args[0] let opCode = args[1] if opCode == "dat" { guard let argAsInt = Int(args[2]) else { throw CompileError.intExpected } value = argAsInt } else { trailingLabel = args[2] } try testForValidCodeLine(opCode: opCode, value: value, leadingLabel: leadingLabel) return InterpretedAssemblyCodeLine(opCode: opCode, leadingLabel: leadingLabel, trailingLabel: trailingLabel, value: value) } private func testForValidCodeLine(opCode: String, value: Int?, leadingLabel: String?) throws { if opCode == "dat" && value == nil && leadingLabel == nil { throw CompileError.invalidAssemblyCode } } /** lines can have 3 parts; leading label, code, and trailing label. but each line can have only the code, or code and either a leading label or a trailing label, or have all 3 parts */ private func interpretLinesOfCode(_ linesOfCode: [String]) throws -> [InterpretedAssemblyCodeLine] { var interpretedLines = [InterpretedAssemblyCodeLine]() for line in linesOfCode { let args = createStringArray(from: line, seperatedBy: .whitespaces) switch args.count { case 1: try interpretedLines.append(interpretLinesOfCodeWith1Arg(args)) case 2: try interpretedLines.append(interpretLinesOfCodeWith2Args(args)) case 3: try interpretedLines.append(interpretLinesOfCodeWith3Args(args)) default: throw CompileError.invalidAssemblyCode } } return interpretedLines } private func trackLabels(for code: [InterpretedAssemblyCodeLine]) -> [String : Int] { var registerCount = 0 var leadingLabelDictionary = [String : Int]() for interpretedAssemblyCodeLine in code { if let leadingLabel = interpretedAssemblyCodeLine.leadingLabel { leadingLabelDictionary[leadingLabel] = registerCount } registerCount += 1 } return leadingLabelDictionary } private func convertCodeStringToOppCode(code: String) throws -> Opcode { switch code { case "add": return .add case "sub": return .subtract case "sta": return .store case "lda": return .load case "bra": return .branch case "brz": return .branchIfZero case "brp": return .branchIfPositive case "inp": return .input case "out": return .output case "hlt": return .halt default: throw CompileError.invalidAssemblyCode } } // MARK: Methods to help load registers from assembly code private func setRegistersFromInterpretedAssemblyCodeLineArray(_ interpretedLines: [InterpretedAssemblyCodeLine], leadingLabels: [String : Int]) throws -> [Register] { do { var registers = [Register](repeating: 000, count: 100) for index in 0..<interpretedLines.count { registers[index] = try getRegisterValue(for: interpretedLines[index], leadingLabels: leadingLabels) } return registers } catch let error as CompileError { throw error } } private func getRegisterValue(for assemblyCode: InterpretedAssemblyCodeLine, leadingLabels: [String : Int]) throws -> Int { guard let opCode = Opcode(rawValue: assemblyCode.opCode) else { throw CompileError.invalidAssemblyCode } if opCode == .data { if assemblyCode.leadingLabel != nil, let value = assemblyCode.value { return Int(value) } else if assemblyCode.leadingLabel != nil { return 0 } else if let value = assemblyCode.value { return Int(value) } else { throw CompileError.invalidAssemblyCode } } if opCode == .input || opCode == .output || opCode == .halt { return Int(getDigitFromOpCode(opCode)) } do { let mailbox = try setMailboxWith(trailingLabel: assemblyCode.trailingLabel, leadingLabel: leadingLabels) return Int(getDigitFromOpCode(opCode) + mailbox) } catch let error as CompileError { throw error } } private func setMailboxWith(trailingLabel: String?, leadingLabel: [String : Int]) throws -> Int { if let label = trailingLabel, let mailbox = leadingLabel[label] { return mailbox } else { throw CompileError.invalidAssemblyCode } } private func getDigitFromOpCode(_ opCode: Opcode) -> Int { switch opCode { case .add: return 100 case .subtract: return 200 case .store: return 300 case .load: return 500 case .branch: return 600 case .branchIfZero: return 700 case .branchIfPositive: return 800 case .input: return 901 case .output: return 902 case .halt, .data: return 000 } } }
mit
a2a4275e8c13935699bb73b02bb511fb
33.867188
170
0.596236
4.917906
false
false
false
false
HC1058503505/HCCardView
HCCardView/CardView/HCCardContentView.swift
1
4923
// // HCCardContentView.swift // HCCardView // // Created by UltraPower on 2017/5/23. // Copyright © 2017年 UltraPower. All rights reserved. // import Foundation import UIKit protocol HCCardContentViewDelegate:class { // 当前CollectionView的索引,以实现与headerView的联动 func cardContentView(cardContentView:HCCardContentView, currentIndex: Int) // 滑动时的起始位置以及进度,以实现渐变效果 func cardContentView(cardContentView:HCCardContentView, beginIndex:Int, toIndex:Int, progress:CGFloat) } class HCCardContentView: UIView { weak var cardContentViewDelegate:HCCardContentViewDelegate? fileprivate var originOffsetX:CGFloat = 0 fileprivate let childVCs:[UIViewController] fileprivate let parentVC:UIViewController fileprivate let contentViewStyle: HCCardViewStyle fileprivate lazy var contentCollectionV:UICollectionView = { let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = self.bounds.size flowLayout.minimumLineSpacing = 0 flowLayout.scrollDirection = UICollectionViewScrollDirection.horizontal let collectionV:UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout) collectionV.delegate = self collectionV.dataSource = self collectionV.backgroundColor = UIColor.white collectionV.isPagingEnabled = true collectionV.bounces = false collectionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Test") return collectionV }() init(frame: CGRect, childVCs:[UIViewController], parentVC:UIViewController, contentViewStyle: HCCardViewStyle) { self.childVCs = childVCs self.parentVC = parentVC self.contentViewStyle = contentViewStyle super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HCCardContentView { func setup() { addSubview(contentCollectionV) for item in childVCs { parentVC.addChildViewController(item) } } } extension HCCardContentView:UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if cardContentViewDelegate != nil && collectionView.visibleCells.count > 0{ cardContentViewDelegate?.cardContentView(cardContentView: self, currentIndex: (collectionView.indexPath(for: collectionView.visibleCells.last!)?.item)!) } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { originOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollOffsetX = scrollView.contentOffset.x let scrollWidth = scrollView.frame.width var beginIndex:Int = 0 var toIndex:Int = 0 var progress:CGFloat = 0 guard scrollOffsetX != originOffsetX && contentViewStyle.isGradient else { return } // 计算起始位置,进度 if scrollOffsetX > originOffsetX { // 左滑 beginIndex = Int(scrollOffsetX / scrollWidth) toIndex = beginIndex == childVCs.count - 1 ? beginIndex : beginIndex + 1 progress = (scrollOffsetX - CGFloat(beginIndex) * scrollWidth) / scrollWidth } else { // 右滑 toIndex = Int(scrollOffsetX / scrollWidth) beginIndex = toIndex + 1 progress = (CGFloat(beginIndex) * scrollWidth - scrollOffsetX) / scrollWidth } // 通知代理,达到联动效果 cardContentViewDelegate?.cardContentView(cardContentView: self, beginIndex: beginIndex, toIndex: toIndex, progress: progress) } } extension HCCardContentView:UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Test", for: indexPath) cell.subviews.forEach({$0.removeFromSuperview()}) cell.addSubview(childVCs[indexPath.item].view) return cell } } extension HCCardContentView:HCCardHeaderViewDelegate { func cardHeaderView(headerView: HCCardHeaderView, currentIndex: Int) { contentCollectionV.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .centeredHorizontally, animated: false) } }
mit
f9f74678aaa5b3a298cfd9966e0585d9
35.409091
164
0.696629
5.263965
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/ContiguousBytes.swift
1
4280
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 - 2020 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 // //===----------------------------------------------------------------------===// //===--- ContiguousBytes --------------------------------------------------===// /// Indicates that the conforming type is a contiguous collection of raw bytes /// whose underlying storage is directly accessible by withUnsafeBytes. public protocol ContiguousBytes { /// Calls the given closure with the contents of underlying storage. /// /// - note: Calling `withUnsafeBytes` multiple times does not guarantee that /// the same buffer pointer will be passed in every time. /// - warning: The buffer argument to the body should not be stored or used /// outside of the lifetime of the call to the closure. func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R } //===--- Collection Conformances ------------------------------------------===// // FIXME: When possible, expand conformance to `where Element : Trivial`. extension Array : ContiguousBytes where Element == UInt8 { } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension ArraySlice : ContiguousBytes where Element == UInt8 { } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension ContiguousArray : ContiguousBytes where Element == UInt8 { } //===--- Pointer Conformances ---------------------------------------------===// extension UnsafeRawBufferPointer : ContiguousBytes { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try body(self) } } extension UnsafeMutableRawBufferPointer : ContiguousBytes { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension UnsafeBufferPointer : ContiguousBytes where Element == UInt8 { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension UnsafeMutableBufferPointer : ContiguousBytes where Element == UInt8 { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension EmptyCollection : ContiguousBytes where Element == UInt8 { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try body(UnsafeRawBufferPointer(start: nil, count: 0)) } } // FIXME: When possible, expand conformance to `where Element : Trivial`. extension CollectionOfOne : ContiguousBytes where Element == UInt8 { @inlinable public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { let element = self.first! return try Swift.withUnsafeBytes(of: element) { return try body($0) } } } //===--- Conditional Conformances -----------------------------------------===// extension Slice : ContiguousBytes where Base : ContiguousBytes { public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType { let offset = base.distance(from: base.startIndex, to: self.startIndex) return try base.withUnsafeBytes { ptr in let slicePtr = ptr.baseAddress?.advanced(by: offset) let sliceBuffer = UnsafeRawBufferPointer(start: slicePtr, count: self.count) return try body(sliceBuffer) } } }
apache-2.0
fbbdfd5b08e674858e8227c58d01c1d9
41.8
123
0.646495
5.31677
false
false
false
false
Zverik/omim
iphone/Maps/Categories/UIView+Snapshot.swift
4
663
import UIKit extension UIView { var snapshot: UIView { guard let contents = layer.contents else { return snapshotView(afterScreenUpdates: true)! } let snapshot: UIView if let view = self as? UIImageView { snapshot = UIImageView(image: view.image) snapshot.bounds = view.bounds } else { snapshot = UIView(frame: frame) snapshot.layer.contents = contents snapshot.layer.bounds = layer.bounds } snapshot.layer.cornerRadius = layer.cornerRadius snapshot.layer.masksToBounds = layer.masksToBounds snapshot.contentMode = contentMode snapshot.transform = transform return snapshot } }
apache-2.0
00a1604a0fa411bf7171a5519bf66b66
27.826087
54
0.692308
4.735714
false
false
false
false
toshiapp/toshi-ios-client
Toshi/MessagesUI/ChatInputTextPanel.swift
1
7948
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit import HPGrowingTextView import SweetUIKit protocol ChatInputTextPanelDelegate: class { func inputTextPanel(_ inputTextPanel: ChatInputTextPanel, requestSendText text: String) func inputTextPanelRequestSendAttachment(_ inputTextPanel: ChatInputTextPanel) func inputTextPanelDidChangeHeight(_ height: CGFloat) } class ChatInputTextPanel: UIView { weak var delegate: ChatInputTextPanelDelegate? static let defaultHeight: CGFloat = .defaultBarHeight private let inputContainerInsets = UIEdgeInsets(top: 1, left: 41, bottom: 7, right: 0) private let maximumInputContainerHeight: CGFloat = 175 private var inputContainerHeight: CGFloat = ChatInputTextPanel.defaultHeight { didSet { if self.inputContainerHeight != oldValue { delegate?.inputTextPanelDidChangeHeight(self.inputContainerHeight) } } } private func inputContainerHeight(for textViewHeight: CGFloat) -> CGFloat { return min(maximumInputContainerHeight, max(ChatInputTextPanel.defaultHeight, textViewHeight + inputContainerInsets.top + inputContainerInsets.bottom)) } lazy var inputContainer = UIView(withAutoLayout: true) lazy var inputField: HPGrowingTextView = { let view = HPGrowingTextView(withAutoLayout: true) view.backgroundColor = Theme.chatInputFieldBackgroundColor view.clipsToBounds = true view.layer.cornerRadius = (ChatInputTextPanel.defaultHeight - (self.inputContainerInsets.top + self.inputContainerInsets.bottom)) / 2 view.layer.borderColor = Theme.borderColor.cgColor view.layer.borderWidth = .lineHeight view.delegate = self view.placeholder = Localized.chat_input_empty_placeholder view.contentInset = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 0) view.font = UIFont.systemFont(ofSize: 16) view.internalTextView.textContainerInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 5) view.internalTextView.scrollIndicatorInsets = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 5) return view }() private lazy var attachButton: UIButton = { let view = UIButton(withAutoLayout: true) view.setImage(ImageAsset.TGAttachButton.withRenderingMode(.alwaysTemplate), for: .normal) view.tintColor = Theme.tintColor view.contentMode = .center view.addTarget(self, action: #selector(attach(_:)), for: .touchUpInside) return view }() private lazy var sendButton: RoundIconButton = { let view = RoundIconButton(image: ImageAsset.send_button, circleDiameter: 27) view.isEnabled = false view.addTarget(self, action: #selector(send(_:)), for: .touchUpInside) return view }() var text: String? { get { return inputField.text } set { inputField.text = String.contentsOrEmpty(for: newValue) } } private lazy var sendButtonWidth: NSLayoutConstraint = { self.sendButton.width(0) }() required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(inputContainer) addSubview(attachButton) addSubview(inputField) addSubview(sendButton) NSLayoutConstraint.activate([ self.attachButton.leftAnchor.constraint(equalTo: self.leftAnchor), self.attachButton.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.attachButton.rightAnchor.constraint(equalTo: self.inputField.leftAnchor), self.attachButton.widthAnchor.constraint(equalToConstant: ChatInputTextPanel.defaultHeight), self.attachButton.heightAnchor.constraint(equalToConstant: ChatInputTextPanel.defaultHeight), self.inputContainer.topAnchor.constraint(equalTo: self.topAnchor), self.inputContainer.leftAnchor.constraint(equalTo: self.leftAnchor, constant: -1), self.inputContainer.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.inputContainer.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 1), self.inputField.topAnchor.constraint(equalTo: self.topAnchor, constant: self.inputContainerInsets.top), self.inputField.leftAnchor.constraint(equalTo: self.attachButton.rightAnchor), self.inputField.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -self.inputContainerInsets.bottom) ]) sendButton.leftToRight(of: inputField) sendButton.bottom(to: self, offset: -3) sendButton.right(to: self) sendButton.height(.defaultButtonHeight) sendButtonWidth.isActive = true } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if self.point(inside: point, with: event) { for subview in subviews.reversed() { let point = subview.convert(point, from: self) if let hitTestView = subview.hitTest(point, with: event) { return hitTestView } } return nil } return nil } @objc func attach(_: ActionButton) { delegate?.inputTextPanelRequestSendAttachment(self) } @objc func send(_: ActionButton) { // Resign and become first responder to accept auto-correct suggestions let temp = UITextField() temp.isHidden = true superview?.addSubview(temp) temp.becomeFirstResponder() inputField.internalTextView.becomeFirstResponder() temp.removeFromSuperview() guard let text = self.inputField.text, !text.isEmpty else { return } let string = text.trimmingCharacters(in: .whitespacesAndNewlines) if !string.isEmpty { delegate?.inputTextPanel(self, requestSendText: string) } self.text = nil sendButton.isEnabled = false } } extension ChatInputTextPanel: HPGrowingTextViewDelegate { func growingTextView(_ textView: HPGrowingTextView, willChangeHeight _: Float) { self.layoutIfNeeded() self.inputContainerHeight = self.inputContainerHeight(for: textView.frame.height) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: .easeOutFromCurrentStateWithUserInteraction, animations: { self.layoutIfNeeded() }, completion: nil) } func growingTextViewDidChange(_ textView: HPGrowingTextView) { self.layoutIfNeeded() let hasText = inputField.internalTextView.hasText self.sendButtonWidth.constant = hasText ? .defaultButtonHeight : 10 self.inputContainerHeight = self.inputContainerHeight(for: textView.frame.height) UIView.animate(withDuration: hasText ? 0.4 : 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: .easeOutFromCurrentStateWithUserInteraction, animations: { self.layoutIfNeeded() self.sendButton.isEnabled = hasText }, completion: nil) } }
gpl-3.0
c631f1df1188307e68b0ca96fd01edf1
38.152709
190
0.689859
4.939714
false
false
false
false
huonw/swift
test/DebugInfo/vector.swift
4
681
// RUN: %target-swift-frontend -emit-ir -g %s -o - -parse-stdlib | %FileCheck %s // REQUIRES: OS=macosx // CHECK: !DICompositeType(tag: DW_TAG_array_type, baseType: ![[FLOAT:[0-9]+]], size: 64, flags: DIFlagVector, elements: ![[ELTS:[0-9]+]]) // CHECK: ![[FLOAT]] = !DIBasicType(name: "$SBf32_D", size: 32, encoding: DW_ATE_float) // CHECK: ![[ELTS]] = !{![[SR:[0-9]+]]} // CHECK: ![[SR]] = !DISubrange(count: 2) import Swift public struct float2 { public var _vector: Builtin.Vec2xFPIEEE32 public subscript(index: Int) -> Float { get { let elt = Builtin.extractelement_Vec2xFPIEEE32_Int32(_vector, Int32(index)._value) return Float(elt) } } }
apache-2.0
b1093db6c7c72275e2f1bbe7907d992b
33.05
138
0.621145
3
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ResponseDetective/ResponseDetective/Sources/ResponseRepresentation.swift
1
2604
// // ResponseRepresentation.swift // // Copyright © 2016-2017 Netguru Sp. z o.o. All rights reserved. // Licensed under the MIT License. // import Foundation /// Represents a pair of `HTTPURLResponse` and `Data` instances. @objc(RDTResponseRepresentation) public final class ResponseRepresentation: NSObject { // MARK: Initializers /// Initializes the receiver. /// /// - Parameters: /// - requestIdentifier: The request's unique identifier. /// - statusCode: The status code of the response. /// - urlString: The URL string of the response. /// - headers: The HTTP headers of the response. /// - body: The raw body data of the response. /// - deserializedBody: The parsed body of the response. public init(requestIdentifier: String, statusCode: Int, urlString: String, headers: [String: String], body: Data?, deserializedBody: String?) { self.requestIdentifier = requestIdentifier self.statusCode = statusCode self.urlString = urlString self.headers = headers self.body = body self.deserializedBody = deserializedBody } /// Initializes the receiver. /// /// - Parameters: /// - requestIdentifier: The unique identifier of assocciated request. /// - response: The HTTP URL response instance. /// - body: The body that came with the response. /// - deserializedBody: The deserialized response body. public convenience init(requestIdentifier: String, response: HTTPURLResponse, body: Data?, deserializedBody: String?) { self.init( requestIdentifier: requestIdentifier, statusCode: response.statusCode, urlString: response.url?.absoluteString ?? "", headers: response.allHeaderFields as? [String: String] ?? [:], body: body, deserializedBody: deserializedBody ) } // MARK: Properties /// The request's unique identifier. public let requestIdentifier: String /// The status code of the response. public let statusCode: Int /// A verbal representation of the status code. public var statusString: String { return HTTPURLResponse.localizedString(forStatusCode: statusCode) } /// The URL string of the response (which may be different than originally /// requested because of a redirect). public let urlString: String /// The HTTP headers of the response. public let headers: [String: String] /// The content type of the response. public var contentType: String { return headers["Content-Type"] ?? "application/octet-stream" } /// The raw body data of the response. public let body: Data? /// The parsed body of the response. public let deserializedBody: String? }
mit
f1ef9fa2f3b67f80f3ef58fd801d258f
30.743902
144
0.713792
4.118671
false
false
false
false
mark644873613/Doctor-lives
Doctor lives/Doctor lives/classes/Home首页/main(主要的)/view/HomeBannerCell.swift
1
4646
// // HomeBannerCell.swift // Doctor lives // // Created by qianfeng on 16/10/26. // Copyright © 2016年 zhb. All rights reserved. // import UIKit public typealias HomeJumpClosure = (AnyObject -> Void) class HomeBannerCell: UITableViewCell { //点击跳转闭包 var jumpClosure:HomeJumpClosure? @IBOutlet weak var pageCtrl: UIPageControl! @IBOutlet weak var scrollView: UIScrollView! //显示数据 var bannerArray: Array<HomeBannerData>? { didSet { //显示数据 showData() } } //显示数据 private func showData() { //遍历添加图片 let cnt = bannerArray?.count if bannerArray?.count > 0 { //滚动视图加约束 //1.创建一个容器视图,作为滚动视图的子视图 let containerView = UIView.creatView() scrollView.addSubview(containerView) containerView.snp_makeConstraints(closure: { (make) in make.edges.equalTo(scrollView) //一定要设置高度 make.height.equalTo(scrollView) }) //2.循环设置子视图的约束,子视图是添加到容器视图里面 var lastView: UIView? = nil for i in 0..<cnt! { let model = bannerArray![i] //创建图片 let tmpImageView = UIImageView() let url = NSURL(string: model.img_url!) tmpImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) containerView.addSubview(tmpImageView) //banner图片的点击事件 tmpImageView.userInteractionEnabled=true tmpImageView.tag=200+i let g=UITapGestureRecognizer(target: self, action: #selector(btnClick(_:))) tmpImageView.addGestureRecognizer(g) //图片的约束 tmpImageView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(scrollView) if lastView == nil { make.left.equalTo(containerView) }else{ make.left.equalTo((lastView?.snp_right)!) } }) lastView = tmpImageView } //3.修改container的宽度 containerView.snp_makeConstraints(closure: { (make) in make.right.equalTo(lastView!) }) //分页控件 pageCtrl.numberOfPages = cnt! } } //banner手势点击事件 func btnClick(g:UITapGestureRecognizer){ let index=(g.view?.tag)!-200 let banner = bannerArray![index] if jumpClosure != nil && banner.url != nil { jumpClosure!(banner.url!) } } //创建cell的方法 class func createBannerCellFor(tableView: UITableView,atIndexPath indexPath:NSIndexPath,bannerArray: [HomeBannerData]?) -> HomeBannerCell { //重用标志 let cellId = "homeBannerCellid" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? HomeBannerCell if nil == cell { //IngreBannerCell.xib cell = NSBundle.mainBundle().loadNibNamed("HomeBannerCell", owner: nil, options: nil).last as? HomeBannerCell } //显示数据 cell?.bannerArray = bannerArray return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } //MARK: UIScrollView代理 extension HomeBannerCell: UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = scrollView.contentOffset.x/scrollView.bounds.size.width pageCtrl.currentPage = Int(index) } }
mit
d6702c0a11960ebe0bd49e2626430988
26.44375
166
0.516511
5.537201
false
false
false
false
recruit-lifestyle/Smile-Lock
SmileLock/Classes/PasswordContainerView.swift
2
10774
// // PasswordView.swift // // Created by rain on 4/21/16. // Copyright © 2016 Recruit Lifestyle Co., Ltd. All rights reserved. // import UIKit import LocalAuthentication public protocol PasswordInputCompleteProtocol: class { func passwordInputComplete(_ passwordContainerView: PasswordContainerView, input: String) func touchAuthenticationComplete(_ passwordContainerView: PasswordContainerView, success: Bool, error: Error?) } open class PasswordContainerView: UIView { //MARK: IBOutlet @IBOutlet open var passwordInputViews: [PasswordInputView]! @IBOutlet open weak var passwordDotView: PasswordDotView! @IBOutlet open weak var deleteButton: UIButton! @IBOutlet open weak var touchAuthenticationButton: UIButton! //MARK: Property open var deleteButtonLocalizedTitle: String = "" { didSet { deleteButton.setTitle(NSLocalizedString(deleteButtonLocalizedTitle, comment: ""), for: .normal) } } open weak var delegate: PasswordInputCompleteProtocol? fileprivate var touchIDContext = LAContext() fileprivate var inputString: String = "" { didSet { #if swift(>=3.2) passwordDotView.inputDotCount = inputString.count #else passwordDotView.inputDotCount = inputString.characters.count #endif checkInputComplete() } } open var isVibrancyEffect = false { didSet { configureVibrancyEffect() } } open override var tintColor: UIColor! { didSet { guard !isVibrancyEffect else { return } deleteButton.setTitleColor(tintColor, for: .normal) passwordDotView.strokeColor = tintColor touchAuthenticationButton.tintColor = tintColor passwordInputViews.forEach { $0.textColor = tintColor $0.borderColor = tintColor } } } open var highlightedColor: UIColor! { didSet { guard !isVibrancyEffect else { return } passwordDotView.fillColor = highlightedColor passwordInputViews.forEach { $0.highlightBackgroundColor = highlightedColor } } } open var isTouchAuthenticationAvailable: Bool { return touchIDContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } open var touchAuthenticationEnabled = false { didSet { let enable = (isTouchAuthenticationAvailable && touchAuthenticationEnabled) touchAuthenticationButton.alpha = enable ? 1.0 : 0.0 touchAuthenticationButton.isUserInteractionEnabled = enable } } open var touchAuthenticationReason = "Touch to unlock" //MARK: AutoLayout open var width: CGFloat = 0 { didSet { self.widthConstraint.constant = width } } fileprivate let kDefaultWidth: CGFloat = 288 fileprivate let kDefaultHeight: CGFloat = 410 fileprivate var widthConstraint: NSLayoutConstraint! fileprivate func configureConstraints() { let ratioConstraint = widthAnchor.constraint(equalTo: self.heightAnchor, multiplier: kDefaultWidth / kDefaultHeight) self.widthConstraint = widthAnchor.constraint(equalToConstant: kDefaultWidth) self.widthConstraint.priority = UILayoutPriority(rawValue: 999) NSLayoutConstraint.activate([ratioConstraint, widthConstraint]) } //MARK: VisualEffect open func rearrangeForVisualEffectView(in vc: UIViewController) { self.isVibrancyEffect = true self.passwordInputViews.forEach { passwordInputView in let label = passwordInputView.label label.removeFromSuperview() vc.view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.addConstraints(fromView: label, toView: passwordInputView, constraintInsets: .zero) } } //MARK: Init open class func create(withDigit digit: Int) -> PasswordContainerView { let bundle = Bundle(for: self) let nib = UINib(nibName: "PasswordContainerView", bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! PasswordContainerView view.passwordDotView.totalDotCount = digit return view } open class func create(in stackView: UIStackView, digit: Int) -> PasswordContainerView { let passwordContainerView = create(withDigit: digit) stackView.addArrangedSubview(passwordContainerView) return passwordContainerView } //MARK: Life Cycle open override func awakeFromNib() { super.awakeFromNib() configureConstraints() backgroundColor = .clear passwordInputViews.forEach { $0.delegate = self } deleteButton.titleLabel?.adjustsFontSizeToFitWidth = true deleteButton.titleLabel?.minimumScaleFactor = 0.5 touchAuthenticationEnabled = true var image = touchAuthenticationButton.imageView?.image?.withRenderingMode(.alwaysTemplate) if #available(iOS 11, *) { if touchIDContext.biometryType == .faceID { let bundle = Bundle(for: type(of: self)) image = UIImage(named: "faceid", in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } } touchAuthenticationButton.setImage(image, for: .normal) touchAuthenticationButton.tintColor = tintColor } //MARK: Input Wrong open func wrongPassword() { passwordDotView.shakeAnimationWithCompletion { self.clearInput() } } open func clearInput() { inputString = "" } //MARK: IBAction @IBAction func deleteInputString(_ sender: AnyObject) { #if swift(>=3.2) guard inputString.count > 0 && !passwordDotView.isFull else { return } inputString = String(inputString.dropLast()) #else guard inputString.characters.count > 0 && !passwordDotView.isFull else { return } inputString = String(inputString.characters.dropLast()) #endif } @IBAction func touchAuthenticationAction(_ sender: UIButton) { touchAuthentication() } open func touchAuthentication() { guard isTouchAuthenticationAvailable else { return } touchIDContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: touchAuthenticationReason) { (success, error) in DispatchQueue.main.async { if success { self.passwordDotView.inputDotCount = self.passwordDotView.totalDotCount // instantiate LAContext again for avoiding the situation that PasswordContainerView stay in memory when authenticate successfully self.touchIDContext = LAContext() } // delay delegate callback for the user can see passwordDotView input dots filled animation DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.delegate?.touchAuthenticationComplete(self, success: success, error: error) } } } } } private extension PasswordContainerView { func checkInputComplete() { #if swift(>=3.2) if inputString.count == passwordDotView.totalDotCount { delegate?.passwordInputComplete(self, input: inputString) } #else if inputString.characters.count == passwordDotView.totalDotCount { delegate?.passwordInputComplete(self, input: inputString) } #endif } func configureVibrancyEffect() { let whiteColor = UIColor.white let clearColor = UIColor.clear //delete button title color var titleColor: UIColor! //dot view stroke color var strokeColor: UIColor! //dot view fill color var fillColor: UIColor! //input view background color var circleBackgroundColor: UIColor! var highlightBackgroundColor: UIColor! var borderColor: UIColor! //input view text color var textColor: UIColor! var highlightTextColor: UIColor! if isVibrancyEffect { //delete button titleColor = whiteColor //dot view strokeColor = whiteColor fillColor = whiteColor //input view circleBackgroundColor = clearColor highlightBackgroundColor = whiteColor borderColor = clearColor textColor = whiteColor highlightTextColor = whiteColor } else { //delete button titleColor = tintColor //dot view strokeColor = tintColor fillColor = highlightedColor //input view circleBackgroundColor = whiteColor highlightBackgroundColor = highlightedColor borderColor = tintColor textColor = tintColor highlightTextColor = highlightedColor } deleteButton.setTitleColor(titleColor, for: .normal) passwordDotView.strokeColor = strokeColor passwordDotView.fillColor = fillColor touchAuthenticationButton.tintColor = strokeColor passwordInputViews.forEach { passwordInputView in passwordInputView.circleBackgroundColor = circleBackgroundColor passwordInputView.borderColor = borderColor passwordInputView.textColor = textColor passwordInputView.highlightTextColor = highlightTextColor passwordInputView.highlightBackgroundColor = highlightBackgroundColor passwordInputView.circleView.layer.borderColor = UIColor.white.cgColor //borderWidth as a flag, will recalculate in PasswordInputView.updateUI() passwordInputView.isVibrancyEffect = isVibrancyEffect } } } extension PasswordContainerView: PasswordInputViewTappedProtocol { public func passwordInputView(_ passwordInputView: PasswordInputView, tappedString: String) { #if swift(>=3.2) guard inputString.count < passwordDotView.totalDotCount else { return } #else guard inputString.characters.count < passwordDotView.totalDotCount else { return } #endif inputString += tappedString } }
apache-2.0
32fbfd129add7c6b1222da8a6fa63ee1
35.642857
150
0.636499
5.839024
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Intro/IntroScreenSyncViewV2.swift
2
7554
/* 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 UIKit import Shared import SnapKit /* The layout for update view controller. The whole is divided into two parts. Top container view and Bottom view. Top container view sits above Sign Up button and its height spans all the way from sign up button to top safe area. We then add [combined view] that contains Image, Title and Description inside [Top container view] to make it center in the top container view. |----------------|----------[Top Container View]--------- | | | |---------[Combined View] | | | Image | [Top View] | | -- Has title image view | | | | [Mid View] | Title | -- Has title | | -- Description | Description | | |---------[Combined View] | | |----------------|----------[Top Container View]--------- | | Bottom View | [Sign up] | -- Bottom View | | -- Start Browsing | Start Browsing | | | |----------------| */ class IntroScreenSyncViewV2: UIView, CardTheme { // Private vars private var fxTextThemeColour: UIColor { // For dark theme we want to show light colours and for light we want to show dark colours return theme == .dark ? .white : .black } private var fxBackgroundThemeColour: UIColor { return theme == .dark ? UIColor.Firefox.DarkGrey10 : .white } private lazy var titleImageView: UIImageView = { let imgView = UIImageView(image: #imageLiteral(resourceName: "tour-sync-v2")) imgView.contentMode = .scaleAspectFit return imgView }() private lazy var titleLabel: UILabel = { let label = UILabel() label.text = Strings.CardTitleFxASyncDevices label.textColor = fxTextThemeColour label.font = UIFont.systemFont(ofSize: 22, weight: .semibold) label.textAlignment = .center label.numberOfLines = 0 return label }() private lazy var descriptionLabel: UILabel = { let label = UILabel() label.text = Strings.CardDescriptionFxASyncDevices label.textColor = fxTextThemeColour label.font = UIFont.systemFont(ofSize: 22, weight: .regular) label.textAlignment = .center label.numberOfLines = 0 return label }() private var signUpButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold) button.layer.cornerRadius = 10 button.backgroundColor = UIColor.Photon.Blue50 button.setTitle(Strings.IntroSignUpButtonTitle, for: .normal) return button }() private lazy var startBrowsingButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold) button.backgroundColor = .clear button.setTitleColor(UIColor.Photon.Blue50, for: .normal) button.setTitle(Strings.StartBrowsingButtonTitle, for: .normal) button.titleLabel?.textAlignment = .center return button }() // Container and combined views private let topContainerView = UIView() private let combinedView = UIView() // Orientation independent screen size private let screenSize = DeviceInfo.screenSizeOrientationIndependent() // Closure delegates var signUp: (() -> Void)? var startBrowsing: (() -> Void)? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) initialViewSetup() topContainerViewSetup() bottomViewSetup() } // MARK: Initializer private func initialViewSetup() { combinedView.addSubview(titleLabel) combinedView.addSubview(descriptionLabel) combinedView.addSubview(titleImageView) topContainerView.addSubview(combinedView) addSubview(topContainerView) addSubview(signUpButton) addSubview(startBrowsingButton) } // MARK: View setup private func topContainerViewSetup() { // Background colour setup backgroundColor = fxBackgroundThemeColour // Height constants let titleLabelHeight = 100 let descriptionLabelHeight = 100 let titleImageHeight = screenSize.height > 600 ? 300 : 200 // Title label constraints titleLabel.snp.makeConstraints { make in make.left.right.equalToSuperview().inset(24) make.top.equalTo(titleImageView.snp.bottom) make.height.equalTo(titleLabelHeight) } // Description label constraints descriptionLabel.snp.makeConstraints { make in make.left.right.equalToSuperview().inset(24) make.top.equalTo(titleLabel.snp.bottom) make.height.equalTo(descriptionLabelHeight) } // Title image view constraints titleImageView.snp.makeConstraints { make in make.left.right.equalToSuperview() make.top.equalToSuperview() make.height.equalTo(titleImageHeight) } // Top container view constraints topContainerView.snp.makeConstraints { make in make.top.equalTo(safeArea.top) make.bottom.equalTo(signUpButton.snp.top) make.left.right.equalToSuperview() } // Combined view constraints combinedView.snp.makeConstraints { make in make.height.equalTo(titleLabelHeight + descriptionLabelHeight + titleImageHeight) make.centerY.equalToSuperview() make.left.right.equalToSuperview() } } private func bottomViewSetup() { // Sign-up button constraints signUpButton.snp.makeConstraints { make in make.bottom.equalTo(startBrowsingButton.snp.top).offset(-20) make.left.right.equalToSuperview().inset(24) make.height.equalTo(46) } // Start browsing button constraints startBrowsingButton.snp.makeConstraints { make in make.bottom.equalTo(safeArea.bottom) make.left.right.equalToSuperview().inset(80) make.height.equalTo(46) } // Sign-up and start browsing button action signUpButton.addTarget(self, action: #selector(signUpAction), for: .touchUpInside) startBrowsingButton.addTarget(self, action: #selector(startBrowsingAction), for: .touchUpInside) } // MARK: Button Actions @objc private func signUpAction() { LeanPlumClient.shared.track(event: .dismissedOnboardingShowSignUp, withParameters: ["dismissedOnSlide": "1"]) UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .dismissedOnboardingSignUp, extras: ["slide-num": 1]) print("Sign up") signUp?() } @objc private func startBrowsingAction() { LeanPlumClient.shared.track(event: .dismissedOnboarding, withParameters: ["dismissedOnSlide": "1"]) UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .dismissedOnboarding, extras: ["slide-num": 1]) print("Start Browsing") startBrowsing?() } }
mpl-2.0
e83ba5071e2db4c38a6301b61feee4c7
37.938144
133
0.630527
4.882999
false
false
false
false
chrisdhaan/CDMarkdownKit
Source/CDMarkdownHeader.swift
1
4662
// // CDMarkdownHeader.swift // CDMarkdownKit // // Created by Christopher de Haan on 11/7/16. // // Copyright © 2016-2022 Christopher de Haan <[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(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(macOS) import Cocoa #endif open class CDMarkdownHeader: CDMarkdownLevelElement { fileprivate static let regex = "^\\s*(#{1,%@})\\s*(.+)$\n*" fileprivate struct CDMarkdownHeadingHashes { static let one = 9 static let two = 5 static let three = 4 static let four = 3 static let five = 2 static let six = 1 static let zero = 0 } open var maxLevel: Int open var font: CDFont? open var color: CDColor? open var backgroundColor: CDColor? open var paragraphStyle: NSParagraphStyle? open var fontIncrease: Int open var regex: String { let level: String = maxLevel > 0 ? "\(maxLevel)" : "" return String(format: CDMarkdownHeader.regex, level) } public init(font: CDFont? = CDFont.boldSystemFont(ofSize: 12), maxLevel: Int = 0, fontIncrease: Int = 2, color: CDColor? = nil, backgroundColor: CDColor? = nil, paragraphStyle: NSParagraphStyle? = nil) { self.maxLevel = maxLevel self.font = font self.color = color self.backgroundColor = backgroundColor if let paragraphStyle = paragraphStyle { self.paragraphStyle = paragraphStyle } else { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.paragraphSpacing = 6 paragraphStyle.paragraphSpacingBefore = 12 self.paragraphStyle = paragraphStyle } self.fontIncrease = fontIncrease } open func formatText(_ attributedString: NSMutableAttributedString, range: NSRange, level: Int) { attributedString.deleteCharacters(in: range) let string = attributedString.mutableString if range.location - 2 > 0 && string.substring(with: NSRange(location: range.location - 2, length: 2)) == "\n\n" { string.deleteCharacters(in: NSRange(location: range.location - 1, length: 1)) } } open func attributesForLevel(_ level: Int) -> [CDAttributedStringKey: AnyObject] { var attributes = self.attributes var fontMultiplier: CGFloat switch level { case 0: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.one) case 1: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.two) case 2: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.three) case 3: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.four) case 4: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.five) case 5: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.six) case 6: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.zero) default: fontMultiplier = CGFloat(CDMarkdownHeadingHashes.four) } if let font = font { let headerFontSize: CGFloat = font.pointSize + (CGFloat(fontMultiplier) * CGFloat(fontIncrease)) let headerFont = font.withSize(headerFontSize) attributes.addFont(headerFont) } return attributes } }
mit
447dd4e36bd39a72c1ae52cac4fb1851
37.204918
108
0.63098
4.751274
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Create.swift
6
2585
// // Create.swift // RxSwift // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { // MARK: create /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(_ subscribe: @escaping (AnyObserver<Element>) -> Disposable) -> Observable<Element> { return AnonymousObservable(subscribe) } } final private class AnonymousObservableSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias Parent = AnonymousObservable<Element> // state private let _isStopped = AtomicInt(0) #if DEBUG private let _synchronizationTracker = SynchronizationTracker() #endif override init(observer: Observer, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif switch event { case .next: if load(self._isStopped) == 1 { return } self.forwardOn(event) case .error, .completed: if fetchOr(self._isStopped, 1) == 0 { self.forwardOn(event) self.dispose() } } } func run(_ parent: Parent) -> Disposable { return parent._subscribeHandler(AnyObserver(self)) } } final private class AnonymousObservable<Element>: Producer<Element> { typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable let _subscribeHandler: SubscribeHandler init(_ subscribeHandler: @escaping SubscribeHandler) { self._subscribeHandler = subscribeHandler } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = AnonymousObservableSink(observer: observer, cancel: cancel) let subscription = sink.run(self) return (sink: sink, subscription: subscription) } }
mit
f15100b74326f61931264090d75448a3
32.128205
171
0.664474
4.903226
false
false
false
false
Eonil/HomeworkApp1
Driver/HomeworkApp1/SlidePageViewController.swift
1
3394
// // SlidePageViewController.swift // HomeworkApp1 // // Created by Hoon H. on 2015/02/26. // // import Foundation import UIKit protocol SlidePageViewControllerDelegate: class { func slidePageViewControllerWillInitiateImageLoading() func slidePageViewControllerDidCompleteImageLoading() } final class SlidePageViewController: UIViewController { weak var delegate:SlidePageViewControllerDelegate? var imageURL:NSURL? { didSet { Debug.assertMainThread() assert(transmission == nil) } } override func viewDidLoad() { super.viewDidLoad() let act = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) act.setTranslatesAutoresizingMaskIntoConstraints(false) act.sizeToFit() self.view.addSubview(act) self.view.addConstraints([ NSLayoutConstraint(item: act, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0), NSLayoutConstraint(item: act, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0), ]) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(imageView) self.view.addConstraints([ NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0), NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0), NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0), ]) //// if let u = imageURL { self.delegate?.slidePageViewControllerWillInitiateImageLoading() self.transmission = Client.fetchImageAtURL(u, handler: { [weak self](image:UIImage?) -> () in dispatch_async(dispatch_get_main_queue()) { [weak self] in Debug.assertMainThread() if let me = self { me.transmission = nil if let m = image { Debug.log("SlidePageViewController downloaded image `\(m)` from URL `\(u)`.") me.imageView.image = m } else { Debug.log("SlidePageViewController couldn't download image for URL `\(u)`.") UIAlertView(title: nil, message: "Could not download image.", delegate: nil, cancelButtonTitle: "Close").show() me.imageView.image = nil } me.delegate?.slidePageViewControllerDidCompleteImageLoading() } } }) } else { imageView.image = nil } } override func viewWillDisappear(animated: Bool) { transmission?.cancel() transmission = nil } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } //// private let imageView = UIImageView() private var transmission = nil as Transmission? }
mit
4a0502f2d35b434d718a80473935f612
25.936508
195
0.74013
4.285354
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/协议/Specialized Collections /Specialized Collections - Forward-Only Traversal.playgroundpage/Contents.swift
1
3978
/*: ### Forward-Only Traversal A singly linked list is famous for a particular trait: it can only be iterated forward. You can't leap into the middle of a linked list. You can't start at the end and work backward. You can only go forward. For this reason, while our `List` collection has a `first` property, it doesn't have a `last` property. To get the last element of a list, you have to iterate all the way to the end, an `O(n)` operation. It would be misleading to provide a cute little property for the last element — a list with a million elements takes a long time to fetch the last element. A general rule of thumb for properties is probably that "they must be constant-time(-ish) operations only, unless it's incredibly obvious the operation couldn't be done in constant time." This is quite a wooly definition. "Must be constant-time operations" would be nicer, but the standard library does make some exceptions. For example, the default implementation of the `count` property is documented to be `O(n)`, though most collections will provide an overload that guarantees `O(1)`, like we did above for `List`. Functions are a different matter. Our `List` type *does* have a `reversed` operation: */ //#-hidden-code /// Private implementation detail of the List collection fileprivate enum ListNode<Element> { case end indirect case node(Element, next: ListNode<Element>) func cons(_ x: Element) -> ListNode<Element> { return .node(x, next: self) } } //#-end-hidden-code //#-hidden-code public struct ListIndex<Element>: CustomStringConvertible { fileprivate let node: ListNode<Element> fileprivate let tag: Int public var description: String { return "ListIndex(\(tag))" } } //#-end-hidden-code //#-hidden-code extension ListIndex: Comparable { public static func == <T>(lhs: ListIndex<T>, rhs: ListIndex<T>) -> Bool { return lhs.tag == rhs.tag } public static func < <T>(lhs: ListIndex<T>, rhs: ListIndex<T>) -> Bool { // startIndex has the highest tag, endIndex the lowest return lhs.tag > rhs.tag } } //#-end-hidden-code //#-hidden-code public struct List<Element>: Collection { // Index's type could be inferred, but it helps make the rest of // the code clearer: public typealias Index = ListIndex<Element> public let startIndex: Index public let endIndex: Index public subscript(position: Index) -> Element { switch position.node { case .end: fatalError("Subscript out of range") case let .node(x, _): return x } } public func index(after idx: Index) -> Index { switch idx.node { case .end: fatalError("Subscript out of range") case let .node(_, next): return Index(node: next, tag: idx.tag - 1) } } } //#-end-hidden-code //#-hidden-code extension List: ExpressibleByArrayLiteral { public init(arrayLiteral elements: Element...) { startIndex = ListIndex(node: elements.reversed().reduce(.end) { partialList, element in partialList.cons(element) }, tag: elements.count) endIndex = ListIndex(node: .end, tag: 0) } } //#-end-hidden-code //#-hidden-code extension List: CustomStringConvertible { public var description: String { let elements = self.map { String(describing: $0) } .joined(separator: ", ") return "List: (\(elements))" } } //#-end-hidden-code //#-editable-code let list: List = ["red", "green", "blue"] let reversed = list.reversed() //#-end-editable-code /*: In this case, what's being called is the `reversed` method provided by the standard library as an extension on `Sequence`, which returns the reversed elements in an array: ``` swift-example extension Sequence { /// Returns an array containing the elements of this sequence /// in reverse order. The sequence must be finite. func reversed() -> [Self.Iterator.Element] } ``` */
mit
98861a60f7e2b2b40c7286fe76116d2f
29.821705
80
0.677817
4.024291
false
false
false
false
david1mdavis/IOS-nRF-Toolbox
nRF Toolbox/Utilities/NORAppUtilities.swift
1
5235
// // NORAppUtilities.swift // nRF Toolbox // // Created by Mostafa Berg on 18/05/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. // import UIKit enum NORServiceIds : UInt8 { case uart = 0 case rsc = 1 case proximity = 2 case htm = 3 case hrm = 4 case csc = 5 case bpm = 6 case bgm = 7 case cgm = 8 case homekit = 9 } class NORAppUtilities: NSObject { static let iOSDFULibraryVersion = "3.0.6" static let uartHelpText = "This profile allows you to connect to a device that support Nordic's UART service. The service allows you to send and receive short messages of 20 bytes in total.\n\nThe main screen contains 9 programmable buttons. Use the Edit button to edit a command or an icon assigned to each button. Unused buttons may be hidden.\n\nTap the Show Log button to see the conversation or to send a custom message." static let rscHelpText = "The RSC (Running Speed and Cadence) profile allows you to connect to your activity sensor. It reads speed and cadence values from the sensor and calculates trip distance if stride length is supported. Strides count is calculated by using cadence and the time." static let proximityHelpText = "The PROXIMITY profile allows you to connect to your Proximity sensor. Later on you can find your valuables attached with Proximity tag by pressing the FindMe button on the screen or your phone by pressing relevant button on your tag. A notification will appear on your phone screen when you go away from your connected tag." static let htmHelpText = "The HTM (Health Thermometer Monitor) profile allows you to connect to your Health Thermometer sensor. It displays the temperature value in Celsius or Fahrenheit degrees." static let hrmHelpText = "The HRM (Heart Rate Monitor) profile allows you to connect and read data from your Heart Rate sensor (eg. a belt). It shows the current heart rate, location of the sensor and displays the historical data on a graph." static let cscHelpText = "The CSC (Cycling Speed and Cadence) profile allows you to connect to your bike activity sensor. It reads wheel and crank data if the sensor supports it, and calculates speed, cadence, total and trip distance and gear ratio. The default wheel size is set to 29 inches but you can set up wheel size in the Settings." static let bpmHelpText = "The BPM (Blood Pressure Monitor) profile allows you to connect to your Blood Pressure device. It supports the cuff pressure notifications and displays systolic, diastolic and mean arterial pulse values as well as the pulse after blood pressure reading is completed." static let bgmHelpText = "The BGM (BLOOD GLUCOSE MONITOR) profile allows you to connect to your glucose sensor.\nTap the Get Records button to read the history of glucose records." static let cgmHelpText = "The CGM (CONTINUOUS GLUCOSE MONITOR) profile allows you to connect to your continuous glucose sensor.\nTap the Start session button to begin reading records every minute (default frequency)" static let homeKitHelpText = "The HomeKit profile allows you to connect to your HomeKit compatible accessories.\nTap the Add Accessory button to browse new accessories or select an accessory from the ones already configured. you will be able to browse the services and characteristics for this accessory and put in OTA DFU mode." static let helpText: [NORServiceIds: String] = [.uart: uartHelpText, .rsc: rscHelpText, .proximity: proximityHelpText, .htm: htmHelpText, .hrm: hrmHelpText, .csc: cscHelpText, .bpm: bpmHelpText, .bgm: bgmHelpText, .cgm: cgmHelpText, .homekit: homeKitHelpText] static func showAlert(title aTitle : String, andMessage aMessage: String){ let alertView = UIAlertView(title: aTitle, message: aMessage, delegate: nil, cancelButtonTitle: "OK") alertView.show() } static func showBackgroundNotification(message aMessage : String){ let localNotification = UILocalNotification() localNotification.alertAction = "Show" localNotification.alertBody = aMessage localNotification.hasAction = false localNotification.fireDate = Date(timeIntervalSinceNow: 1) localNotification.timeZone = TimeZone.current localNotification.soundName = UILocalNotificationDefaultSoundName } static func isApplicationInactive() -> Bool { let appState = UIApplication.shared.applicationState return appState != UIApplicationState.active } static func getHelpTextForService(service aServiceId: NORServiceIds) -> String { return helpText[aServiceId]! } }
bsd-3-clause
1f85bab476d4949c9059f93751e3ce8a
62.060241
430
0.670424
5.052124
false
false
false
false
leo150/Pelican
Sources/Pelican/Session/Types/UserSession.swift
1
2764
// // UserChatSession.swift // party // // Created by Takanu Kyriako on 26/06/2017. // // import Foundation import Vapor /** A high-level class for managing states and information for each user that attempts to interact with your bot (and that isn't immediately blocked by the bot's blacklist). Features embedded permission lists populated by Moderator, the chat sessions the user is actively participating in and other key pieces of information. UserSession is also used to handle InlineQuery and ChosenInlineResult routes, as only UserSessions will receive inline updates. */ open class UserSession: Session { // CORE INTERNAL VARIABLES public var tag: SessionTag /// The user information associated with this session. public var info: User /// The ID of the user associated with this session. public var userID: Int /// The chat sessions the user is currently actively occupying. public var chatSessions: [ChatSession] = [] /** A user-defined type assigned by Pelican on creation, used to cleanly associate custom functionality and variables to an individual user session. */ // API REQUESTS // Shortcuts for API requests. public var answer: TGAnswer // DELEGATES / CONTROLLERS /// Handles and matches user requests to available bot functions. public var routes: RouteController /// Stores what Moderator-controlled permissions the User Session has. public var mod: SessionModerator /// Handles timeout conditions. public var timeout: Timeout /// Handles flood conditions. public var flood: Flood /// Stores a link to the schedule, that allows events to be executed at a later date. public var schedule: Schedule // TIME AND ACTIVITY public var timeStarted = Date() public var timeLastActive = Date() public var timeoutLength: Int = 0 public required init(bot: Pelican, tag: SessionTag, update: Update) { self.tag = tag self.info = update.from! self.userID = update.from!.tgID self.routes = RouteController() self.mod = SessionModerator(tag: tag, moderator: bot.mod)! self.timeout = Timeout(tag: tag, schedule: bot.schedule) self.flood = Flood() self.schedule = bot.schedule self.answer = TGAnswer(tag: tag) } open func postInit() { } /// Closes the session, deinitialising all modules and removing itself from the associated SessionBuilder. open func close() { self.timeout.close() } public func update(_ update: Update) { // Bump the timeout controller first so if flood or another process closes the Session, a new timeout event will not be added. timeout.bump(update) // This needs revising, whatever... let handled = routes.handle(update: update) // Bump the flood controller after flood.bump(update) } }
mit
5796c5e41ca5f5e716f4b8c037210c43
25.32381
128
0.730101
3.965567
false
false
false
false
ello/ello-ios
Sources/Controllers/Profile/Calculators/ProfileHeaderLinksSizeCalculator.swift
1
2669
//// /// ProfileHeaderLinksSizeCalculator.swift // import PromiseKit class ProfileHeaderLinksSizeCalculator: CellSizeCalculator { static func calculateHeight(_ externalLinks: [ExternalLink], width: CGFloat) -> CGFloat { let iconsCount = externalLinks.filter({ $0.iconURL != nil }).count let (perRow, _) = ProfileHeaderLinksSizeCalculator.calculateIconsBoxWidth( externalLinks, width: width ) let iconsRows = max(0, ceil(Double(iconsCount) / Double(perRow))) let iconsHeight = CGFloat(iconsRows) * ProfileHeaderLinksCell.Size.iconSize.height + CGFloat(max(0, iconsRows - 1)) * ProfileHeaderLinksCell.Size.iconMargins let textLinksCount = externalLinks.filter { $0.iconURL == nil && !$0.text.isEmpty }.count let linksHeight = CGFloat(textLinksCount) * ProfileHeaderLinksCell.Size.linkHeight + CGFloat(max(0, textLinksCount - 1)) * ProfileHeaderLinksCell.Size.verticalLinkMargin return ProfileHeaderLinksCell.Size.margins.tops + max(iconsHeight, linksHeight) } static func calculateIconsBoxWidth(_ externalLinks: [ExternalLink], width: CGFloat) -> ( Int, CGFloat ) { let iconsCount = externalLinks.filter({ $0.iconURL != nil }).count let textLinksCount = externalLinks.filter { $0.iconURL == nil && !$0.text.isEmpty }.count let cellWidth = max(0, width - ProfileHeaderLinksCell.Size.margins.sides) let perRow: Int let iconsBoxWidth: CGFloat if textLinksCount > 0 { perRow = 3 let maxNumberOfIconsInRow = CGFloat(min(perRow, iconsCount)) let maxIconsWidth = ProfileHeaderLinksCell.Size.iconSize.width * maxNumberOfIconsInRow let iconsMargins = ProfileHeaderLinksCell.Size.iconMargins * max(0, maxNumberOfIconsInRow - 1) iconsBoxWidth = max(0, maxIconsWidth + iconsMargins) } else { iconsBoxWidth = cellWidth perRow = Int( cellWidth / ( ProfileHeaderLinksCell.Size.iconSize.width + ProfileHeaderLinksCell.Size.iconMargins ) ) } return (perRow, iconsBoxWidth) } override func process() { guard let user = cellItem.jsonable as? User, let externalLinks = user.externalLinksList, externalLinks.count > 0 else { assignCellHeight(all: 0) return } assignCellHeight( all: ProfileHeaderLinksSizeCalculator.calculateHeight(externalLinks, width: width) ) } }
mit
783b61b464860347f3b84d7ab3ef0674
38.25
98
0.632447
4.500843
false
false
false
false
yzhou65/DSWeibo
DSWeibo/Classes/Home/PhotoBrowser/PhotoBrowserCell.swift
1
5066
// // PhotoBrowserCell.swift // DSWeibo // // Created by Yue on 9/13/16. // Copyright © 2016 fda. All rights reserved. // import UIKit import SDWebImage protocol PhotoBrowserCellDelegate: NSObjectProtocol { func photoBrowserCellDidClose(cell: PhotoBrowserCell) } class PhotoBrowserCell: UICollectionViewCell { weak var photoBrowserCellDelegate: PhotoBrowserCellDelegate? var imageURL: NSURL? { didSet { //重置属性 reset() //显示loading菊花 activity.startAnimating() //设置图片 iconView.sd_setImageWithURL(imageURL) { (image, _, _, _) in self.activity.stopAnimating() // 调整图片的尺寸和位置 self.setImageViewPosition() } } } /** 调整图片显示的位置 */ private func setImageViewPosition() { //拿到按照宽高比计算之后的图片大小 let size = self.displaySize(iconView.image!) //判断图片的高度,是否大于屏幕的高度 if size.height < UIScreen.mainScreen().bounds.height { //小于 短图 -> 设置边距,让图片居中显示 iconView.frame = CGRect(origin: CGPointZero, size: size) let y = (UIScreen.mainScreen().bounds.height - size.height) * 0.5 self.scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0) } else { //大于 长图 -> y == 0, 设置scrollView的滚动范围为图片的大小 iconView.frame = CGRect(origin: CGPointZero, size: size) scrollView.contentSize = size } } /** 重置scrollView和imageView的属性。 如果第一个图被放大,有可能拖到第三个图(重用第一个cell)会显示出问题 */ private func reset() { //这样就能重置scrollView scrollView.contentInset = UIEdgeInsetsZero scrollView.contentOffset = CGPointZero scrollView.contentSize = CGSizeZero //重置imageView iconView.transform = CGAffineTransformIdentity } /** 按照图片的宽高比计算图片显示的大小 */ private func displaySize(image: UIImage) -> CGSize { //拿到图片宽高比 let scale = image.size.height / image.size.width //根据宽高比计算高度 let width = UIScreen.mainScreen().bounds.width let height = width * scale return CGSize(width: width, height: height) } override init(frame: CGRect) { super.init(frame: frame) //初始化UI setupUI() } private func setupUI() { //添加子控件 contentView.addSubview(scrollView) scrollView.addSubview(iconView) //布局子控件 scrollView.frame = UIScreen.mainScreen().bounds // 处理缩放 scrollView.delegate = self scrollView.maximumZoomScale = 2.0 scrollView.minimumZoomScale = 0.5 //监听图片点击,达到点击图片后能关闭的效果 let tap = UITapGestureRecognizer(target: self, action: #selector(closePicture)) iconView.userInteractionEnabled = true //因为图片默认无法点击 iconView.addGestureRecognizer(tap) } //MARK: - 监听 /** 关闭照片浏览器 */ func closePicture() { photoBrowserCellDelegate?.photoBrowserCellDidClose(self) } //MARK: - 懒加载 private lazy var scrollView: UIScrollView = UIScrollView() lazy var iconView: UIImageView = UIImageView() private lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PhotoBrowserCell: UIScrollViewDelegate { /** 告诉系统需要缩放哪个控件 */ func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return iconView } /** pinch缩放图片完成后调用。此时需要重新调整配图的居中性 view:被缩放的视图 */ func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { // print("scrollViewDidEndZooming") //注意:缩放的本质是修改了transform,而修改transform不会影响到bounds,只有frame会受到影响 var offsetX = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5 var offsetY = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5 offsetX = offsetX < 0 ? 0 : offsetX offsetY = offsetY < 0 ? 0 : offsetY scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX) } }
apache-2.0
28c98fdd9de623931a7c17c8e81c4bf1
27.88961
145
0.605754
4.678233
false
false
false
false
pepaslabs/GlitchyTable
1 The Problem/GlitchyTable/GlitchyTable/GlitchyTableViewController.swift
1
1592
// // GlitchyTableViewController.swift // GlitchyTable // // Created by Jason Pepas on 9/2/15. // Copyright (c) 2015 Jason Pepas. All rights reserved. // import UIKit class GlitchyModel { func textForIndexPath(indexPath: NSIndexPath) -> String { NSThread.sleepForTimeInterval(0.1) return "\(indexPath.row)" } } class GlitchyTableCell: UITableViewCell { override func prepareForReuse() { super.prepareForReuse() textLabel?.text = "" } } class GlitchyTableViewController: UITableViewController { let model = GlitchyModel() override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: GlitchyTableCell? = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as? GlitchyTableCell if cell == nil { cell = GlitchyTableCell(style:.Default, reuseIdentifier: "reuseIdentifier") } return cell! } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cell = cell as? GlitchyTableCell { _configureCell(cell, atIndexPath: indexPath) } } private func _configureCell(cell: GlitchyTableCell, atIndexPath indexPath: NSIndexPath) { cell.textLabel?.text = model.textForIndexPath(indexPath) } }
mit
095981c34a2e62a62a893bc8930e89dd
24.677419
132
0.666457
4.780781
false
false
false
false
apple/swift
test/expr/closure/let.swift
9
516
// RUN: %target-typecheck-verify-swift func frob(x: inout Int) {} func foo() { let x: Int // expected-note* {{}} x = 0 _ = { frob(x: x) }() // expected-error{{'x' is a 'let'}} _ = { x = 0 }() // expected-error{{'x' is a 'let'}} _ = { frob(x: x); x = 0 }() // expected-error {{'x' is a 'let'}} } let a: Int { 1 } // expected-error{{'let' declarations cannot be computed properties}} let b: Int = 1 { didSet { print("didSet") } } // expected-error{{'let' declarations cannot be observing properties}}
apache-2.0
28c03d55ab0a124d50141a89e8951dbf
26.157895
101
0.565891
3.035294
false
false
false
false
tardieu/swift
benchmark/single-source/AngryPhonebook.swift
21
1927
//===--- AngryPhonebook.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is based on single-source/Phonebook, with // to test uppercase and lowercase ASCII string fast paths. import TestsUtils import Foundation var words = [ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony", "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott", "Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin", "Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter", "Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl", "Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy", "Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce", "Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan", "Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Craig"] @inline(never) public func run_AngryPhonebook(_ N: Int) { // Permute the names. for _ in 1...N { for firstname in words { for lastname in words { _ = (firstname.uppercased(), lastname.lowercased()) } } } }
apache-2.0
e4207982bab31e3f92ad44626880a990
43.813953
81
0.584328
3.282794
false
true
false
false
brentdax/swift
test/Frontend/dump-parse.swift
4
3319
// RUN: not %target-swift-frontend -dump-parse %s 2>&1 | %FileCheck %s // RUN: not %target-swift-frontend -dump-ast %s 2>&1 | %FileCheck %s -check-prefix=CHECK-AST // CHECK-LABEL: (func_decl{{.*}}"foo(_:)" // CHECK-AST-LABEL: (func_decl{{.*}}"foo(_:)" func foo(_ n: Int) -> Int { // CHECK: (brace_stmt // CHECK: (return_stmt // CHECK: (integer_literal_expr type='<null>' value=42))) // CHECK-AST: (brace_stmt // CHECK-AST: (return_stmt // CHECK-AST: (call_expr implicit type='Int' // CHECK-AST: (integer_literal_expr type='{{[^']+}}' {{.*}} value=42) return 42 } // -dump-parse should print an AST even though this code is invalid. // CHECK-LABEL: (func_decl{{.*}}"bar()" // CHECK-AST-LABEL: (func_decl{{.*}}"bar()" func bar() { // CHECK: (brace_stmt // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-AST: (brace_stmt // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo foo foo foo } // CHECK-LABEL: (enum_decl{{.*}}trailing_semi "TrailingSemi" enum TrailingSemi { // CHECK-LABEL: (enum_case_decl{{.*}}trailing_semi // CHECK-NOT: (enum_element_decl{{.*}}trailing_semi // CHECK: (enum_element_decl{{.*}}"A") // CHECK: (enum_element_decl{{.*}}"B") case A,B; // CHECK-LABEL: (subscript_decl{{.*}}trailing_semi // CHECK-NOT: (func_decl{{.*}}trailing_semi 'anonname={{.*}}' get_for=subscript(_:) // CHECK: (accessor_decl{{.*}}'anonname={{.*}}' get_for=subscript(_:) subscript(x: Int) -> Int { // CHECK-LABEL: (pattern_binding_decl{{.*}}trailing_semi // CHECK-NOT: (var_decl{{.*}}trailing_semi "y" // CHECK: (var_decl{{.*}}"y" var y = 1; // CHECK-LABEL: (sequence_expr {{.*}} trailing_semi y += 1; // CHECK-LABEL: (return_stmt{{.*}}trailing_semi return y; }; }; // The substitution map for a declref should be relatively unobtrustive. // CHECK-AST-LABEL: (func_decl{{.*}}"generic(_:)" <T : Hashable> interface type='<T where T : Hashable> (T) -> ()' access=internal captures=(<generic> ) func generic<T: Hashable>(_: T) {} // CHECK-AST: (pattern_binding_decl // CHECK-AST: (declref_expr type='(Int) -> ()' location={{.*}} range={{.*}} decl=main.(file).generic@{{.*}} [with (substitution_map generic_signature=<T where T : Hashable> (substitution T -> Int))] function_ref=unapplied)) let _: (Int) -> () = generic // Closures should be marked as escaping or not. func escaping(_: @escaping (Int) -> Int) {} escaping({ $0 }) // CHECK-AST: (declref_expr type='(@escaping (Int) -> Int) -> ()' // CHECK-AST-NEXT: (paren_expr // CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=0 escaping single-expression func nonescaping(_: (Int) -> Int) {} nonescaping({ $0 }) // CHECK-AST: (declref_expr type='((Int) -> Int) -> ()' // CHECK-AST-NEXT: (paren_expr // CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=1 single-expression
apache-2.0
9d9ae0ac5a494c298ae12b69207b70f4
42.684211
231
0.579693
3.366126
false
false
false
false
davejlin/treehouse
swift/swift3/RestaurantReviews/RestaurantReviews/YelpReview.swift
1
1109
// // YelpReview.swift // RestaurantReviews // // Created by Pasan Premaratne on 5/9/17. // Copyright © 2017 Treehouse. All rights reserved. // import Foundation class YelpReview: JSONDecodable { let url: String let text: String let rating: Int var user: YelpUser let creationTime: Date required init?(json: [String : Any]) { guard let url = json["url"] as? String, let text = json["text"] as? String, let rating = json["rating"] as? Int, let userDict = json["user"] as? [String: Any], let timeCreated = json["time_created"] as? String else { return nil } self.url = url self.text = text self.rating = rating guard let user = YelpUser(json: userDict) else { return nil } self.user = user let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" guard let creationTime = formatter.date(from: timeCreated) else { return nil } self.creationTime = creationTime } func update(_ user: YelpUser) { self.user = user } }
unlicense
e123b3e719f5640f66d0e825fed78129
28.157895
237
0.604693
3.985612
false
false
false
false
SwiftGen/templates
Pods/StencilSwiftKit/Sources/SetNode.swift
4
946
// // StencilSwiftKit // Copyright (c) 2017 SwiftGen // MIT Licence // import Stencil class SetNode: NodeType { let variableName: String let nodes: [NodeType] class func parse(_ parser: TokenParser, token: Token) throws -> NodeType { let comps = token.components() guard comps.count == 2 else { throw TemplateSyntaxError("'set' tag takes one argument, the name of the variable to set") } let variable = comps[1] let setNodes = try parser.parse(until(["endset"])) guard parser.nextToken() != nil else { throw TemplateSyntaxError("`endset` was not found.") } return SetNode(variableName: variable, nodes: setNodes) } init(variableName: String, nodes: [NodeType]) { self.variableName = variableName self.nodes = nodes } func render(_ context: Context) throws -> String { let result = try renderNodes(nodes, context) context[variableName] = result return "" } }
mit
ae29f170c0d2d443df3697102128bd12
23.25641
96
0.668076
4.185841
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/SpecialEvents/SpecialEventsViewController.swift
1
9280
// // SpecialEventsViewController.swift // WePeiYang // // Created by Allen X on 8/20/16. // Copyright © 2016 Qin Yubo. All rights reserved. // import UIKit import pop let smallPhoneWidth: CGFloat = 320 let phoneWidth = UIApplication.sharedApplication().keyWindow?.frame.size.width class SpecialEventsViewController: WebAppViewController { var saveForLaterBtn: UIButton! var notInterestedBtn: UIButton! var diveIntoDetailBtn: UIButton! //下次再看 func dismissAnimatedAndRemoveDefaults() { NSUserDefaults.standardUserDefaults().removeObjectForKey("eventsWatched") self.dismissViewControllerAnimated(true) { for fooView in (UIViewController.currentViewController().tabBarController?.view.subviews)! { if fooView.isKindOfClass(UIVisualEffectView) { fooView.removeFromSuperview() } } } let app = UIApplication.sharedApplication().delegate as? AppDelegate app?.specialEventsShouldShow = false } //不感兴趣 func dismissAnimated() { self.dismissViewControllerAnimated(true) { for fooView in (UIViewController.currentViewController().tabBarController?.view.subviews)! { if fooView.isKindOfClass(UIVisualEffectView) { fooView.removeFromSuperview() } } } let app = UIApplication.sharedApplication().delegate as? AppDelegate app?.specialEventsShouldShow = false } func expandView() { let h = UIScreen.mainScreen().bounds.size.height let w = UIScreen.mainScreen().bounds.size.width let expandAnim = POPSpringAnimation(propertyNamed: kPOPViewBounds) expandAnim.toValue = NSValue(CGRect: CGRect(x: 0, y: 0, width: w, height: h)) expandAnim.springBounciness = 10 expandAnim.completionBlock = { (_, _) in for fooView in self.view.subviews { if fooView.isKindOfClass(UIImageView) { fooView.removeFromSuperview() } } } self.view.addSubview(saveForLaterBtn) saveForLaterBtn.snp_makeConstraints { make in make.left.equalTo(self.view).offset(20) make.bottom.equalTo(self.view).offset(-20) make.width.equalTo(100) } self.view.addSubview(notInterestedBtn) notInterestedBtn.snp_makeConstraints { make in make.bottom.equalTo(self.view).offset(-20) make.right.equalTo(self.view).offset(-20) make.width.equalTo(100) } let deRoundCornoerAnim = POPBasicAnimation(propertyNamed: kPOPLayerCornerRadius) let newCornerRadius: NSNumber = 0 deRoundCornoerAnim.toValue = newCornerRadius //expandAnim.springSpeed = self.view.pop_addAnimation(expandAnim, forKey: "expandAnim") self.view.layer.pop_addAnimation(deRoundCornoerAnim, forKey: "deRound") for fooView in self.view.subviews { if !fooView.isKindOfClass(UIButton) { fooView.layer.pop_addAnimation(deRoundCornoerAnim, forKey: "deRound") } } } override func viewDidLoad() { super.viewDidLoad() NSUserDefaults.standardUserDefaults().setObject("1", forKey: "eventsWatched") diveIntoDetailBtn = UIButton(title: "我要报名", borderWidth: 2.0, borderColor: .whiteColor()) diveIntoDetailBtn.addTarget(self, action: #selector(self.expandView), forControlEvents: .TouchUpInside) saveForLaterBtn = UIButton(title: "下次再看", borderWidth: 2.0, borderColor: .whiteColor()) saveForLaterBtn.addTarget(self, action: #selector(self.dismissAnimatedAndRemoveDefaults), forControlEvents: .TouchUpInside) notInterestedBtn = UIButton(title: "不再提醒", borderWidth: 2.0, borderColor: .whiteColor()) notInterestedBtn.addTarget(self, action: #selector(self.dismissAnimated), forControlEvents: .TouchUpInside) view.layer.cornerRadius = 8 for subview in view.subviews { subview.layer.cornerRadius = 8 } let flyerView = UIImageView() flyerView.clipsToBounds = true flyerView.layer.cornerRadius = 8 let flyerImg = UIImage(named: "specialEventsFlyer") flyerView.image = flyerImg flyerView.contentMode = .ScaleAspectFill self.view.addSubview(flyerView) flyerView.snp_makeConstraints { make in make.left.equalTo(view) make.right.equalTo(view) make.top.equalTo(view) make.bottom.equalTo(view) } if phoneWidth <= smallPhoneWidth { flyerView.addSubview(diveIntoDetailBtn) diveIntoDetailBtn.snp_makeConstraints { make in make.bottom.equalTo(flyerView).offset(-40) make.right.equalTo(flyerView).offset(-10) make.width.equalTo(90) } flyerView.addSubview(notInterestedBtn) notInterestedBtn.snp_makeConstraints { make in make.bottom.equalTo(flyerView).offset(-40) make.left.equalTo(flyerView).offset(10) make.width.equalTo(90) } } else { flyerView.addSubview(diveIntoDetailBtn) diveIntoDetailBtn.snp_makeConstraints { make in make.right.equalTo(flyerView).offset(-20) make.bottom.equalTo(flyerView).offset(-40) make.width.equalTo(100) } /*self.view.addSubview(saveForLaterBtn) saveForLaterBtn.snp_makeConstraints { make in make.bottom.equalTo(flyerView).offset(-40) make.left.equalTo(flyerView).offset(20) make.width.equalTo(100) }*/ flyerView.addSubview(notInterestedBtn) notInterestedBtn.snp_makeConstraints { make in make.bottom.equalTo(flyerView).offset(-40) make.left.equalTo(flyerView).offset(20) make.width.equalTo(100) } } assignGestures(to: flyerView) //log.any(view.subviews)/ // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } /* extension SpecialEventsViewController { func computeLayout() { navigator = UIView(color: .blackColor()) self.view.addSubview(navigator) navigator.snp_makeConstraints { make in make.top.equalTo(self.view) make.width.equalTo(self.view) make.height.equalTo(44) } self.view.snp_makeConstraints { make in make.height.equalTo(self.view.frame.size.height - 44) } navigator.addSubview(saveForLaterBtn) saveForLaterBtn.snp_makeConstraints { make in make.top.equalTo(navigator).offset(20) make.left.equalTo(navigator).offset(20) make.width.equalTo(100) } navigator.addSubview(notInterestedBtn) notInterestedBtn.snp_makeConstraints { make in make.top.equalTo(navigator).offset(20) make.right.equalTo(navigator).offset(-20) make.width.equalTo(100) } } }*/ private extension SpecialEventsViewController { func assignGestures(to whichView: UIView) { whichView.userInteractionEnabled = true let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.expandView)) pinchGestureRecognizer.scale = 1.2 whichView.addGestureRecognizer(pinchGestureRecognizer) let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.dismissAnimatedAndRemoveDefaults)) swipeUp.direction = .Up whichView.addGestureRecognizer(swipeUp) } } private extension UIButton { convenience init(title: String, borderWidth: CGFloat, borderColor: UIColor) { self.init() setTitle(title, forState: .Normal) titleLabel?.sizeToFit() self.layer.cornerRadius = 8 self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.CGColor } }
mit
eb3e696586729302fbf38839b3a06e71
32.353791
131
0.601039
4.948581
false
false
false
false
bsorrentino/slidesOnTV
slides/slides/SearchFavoritesView.swift
1
9460
// // FavoritesView.swift // slides // // Created by Bartolomeo Sorrentino on 07/11/21. // Copyright © 2021 bsorrentino. All rights reserved. // import SwiftUI import Combine import TVOSToast fileprivate let Const = ( gridItemSize: CGFloat(500), Background: Color.blue ) struct FavoriteContextMenuModifier: ViewModifier { var item : FavoriteItem var delete: ( FavoriteItem ) -> Void var download: ( FavoriteItem ) -> Void @State private var confirmationShown = false #if swift(<15.0) @State private var presentSheet = false struct MenuButtonModifier: ViewModifier { var foreground: Color? var background: Color? func body(content: Content) -> some View { content .font(.headline) .padding(EdgeInsets( top: 10, leading: 120, bottom: 10, trailing: 120 )) .if( foreground != nil ) { $0.foregroundColor( foreground )} .if( background != nil ) { $0.background( background )} } } private var sheetTitle:some View { HStack { Label( "Actions", systemImage: "filemenu.and.selection") .labelStyle(.iconOnly) .font(.largeTitle) Text( "_press 'MENU' to dismiss_") .font(.callout) } } #endif func body(content: Content) -> some View { content #if swift(>=15.0) .contextMenu { Button( "MENU 􀱢") { } Button( "Download 􀈄") { download(item) } Button( "Delete 􀈓", role: .destructive ) { confirmationShown.toggle() } } .confirmationDialog( "Are you sure?", isPresented: $confirmationShown ) { Button("Yes") { withAnimation { delete(item) } } } #else .onLongPressGesture(minimumDuration: 0.5, perform: { presentSheet.toggle() }, onPressingChanged: { state in print("onPressingChanged: \(state)")}) .sheet(isPresented: $presentSheet) { VStack { sheetTitle Divider() Button( action: { presentSheet.toggle(); download(item) }, label: { Label( "Download", systemImage: "square.and.arrow.down") .modifier( MenuButtonModifier( foreground: .black, background: .white) ) }) .buttonStyle(.plain) Button( action: { confirmationShown.toggle() }, label: { Label( "Delete", systemImage: "trash.circle") .modifier( MenuButtonModifier( foreground: .white, background: .red) ) }) .buttonStyle(.plain) } .fixedSize() .padding() .alert( isPresented: $confirmationShown) { Alert( title: Text("Are you sure you want to delete this?"), message: Text("**There is no undo**"), primaryButton: .destructive(Text("Confirm")) { presentSheet.toggle() delete(item) }, secondaryButton: .cancel() ) } } #endif } } struct FavoritesView: View { @StateObject var downloadManager = DownloadManager<FavoriteItem>() @State var isItemDownloaded:Bool = false @State var selectedItem:FavoriteItem? @State private var data:[FavoriteItem] = [] private let columns:[GridItem] = Array(repeating: .init(.fixed(Const.gridItemSize)), count: 3) private var cancellable: AnyCancellable? private func download( _ item : FavoriteItem ) { self.downloadManager.downloadFavorite(item) { isItemDownloaded = $0 } } private func delete( _ item : FavoriteItem ) { NSUbiquitousKeyValueStore.default.favoriteRemove(key: item.id) selectedItem = nil data = NSUbiquitousKeyValueStore.default.favorites() } var body: some View { NavigationView { ZStack { NavigationLink(destination: PresentationView<FavoriteItem>() .environmentObject(downloadManager), isActive: $isItemDownloaded) { EmptyView() } .hidden() VStack { HStack(alignment: .center, spacing: 10 ) { Image( systemName: "bookmark.fill") .resizable() .scaledToFit() .frame( minWidth: 100, maxHeight: 70 ) Text( "Favorites" ) .font(.largeTitle.bold()) }.padding() Divider() // // @ref https://stackoverflow.com/a/67730429/521197 // // ScrollViewReader usage for dynamically scroll to tagged position // ScrollView { LazyVGrid( columns: columns ) { ForEach(data, id: \.id) { item in Button( action: { download(item) } ) { SearchCardView<FavoriteItem>( item: item, onFocusChange: setItem ) .environmentObject(downloadManager) } .buttonStyle( CardButtonStyle() ) // 'CardButtonStyle' doesn't work whether .focusable() is called .disabled( self.downloadManager.isDownloading(item: item) ) .id( item.id ) .modifier( FavoriteContextMenuModifier(item: item, delete: delete, download: download) ) } } } .padding(.horizontal) Spacer() TitleView( selectedItem: selectedItem ) } .onAppear { data = NSUbiquitousKeyValueStore.default.favorites() showToast_How_To_Open_Menu() } } .edgesIgnoringSafeArea(.bottom) } .favoritesTheme() } fileprivate func resetItem( OnFocusChange focused : Bool ) { if focused { self.selectedItem = nil } } fileprivate func setItem( item:FavoriteItem, OnFocusChange focused : Bool ) { if focused { self.selectedItem = item } else if( item == self.selectedItem ) { self.selectedItem = nil } } } // MARK: FavoriteView Toast Extension extension FavoritesView { private func showToast_How_To_Open_Menu() { guard let viewController = UIApplication.shared.windows.first!.rootViewController else {return} let style = TVOSToastStyle( position: .topRight(insets: 10), backgroundColor: UIColor.link ) let toast = TVOSToast(frame: CGRect(x: 0, y: 0, width: 600, height: 80), style: style) toast.hintText = TVOSToastHintText(element: [.stringType("'Long press' to open menu")]) viewController.presentToast(toast) } } // MARK: - Download Manager Extension extension DownloadManager where T == FavoriteItem { func downloadFavorite( _ item: FavoriteItem, completionHandler: @escaping (Bool) -> Void ) { guard let credentials = try? SlideshareApi.getCredential() else { return } let api = SlideshareApi() let parser = SlideshareItemsParser() if let query = try? api.queryById(credentials: credentials, id: item.id ) { let onCompletion = { (completion:Subscribers.Completion<Error>) in switch completion { case .failure(let error): log.error( "\(error.localizedDescription)") case .finished: log.debug("DONE!") } } query.toGenericError() .flatMap { parser.parse($0.data) } .map { SlidehareItem(data:$0) } .compactMap { FavoriteItem(item:$0) } .first() .sink( receiveCompletion: onCompletion, receiveValue: { self.download(item: $0, completionHandler: completionHandler) }) .store(in: &bag) } else { log.error( "error invoking slideshare API" ) } } } struct FavoritesView_Previews: PreviewProvider { static var previews: some View { FavoritesView() } }
mit
f132d63911145500a7c939a3daa3dad3
32.629893
130
0.480317
5.475087
false
false
false
false
totetero/fuhaha_engine
src_client/fuhahaEngine/ios/FuhahaEvent.swift
1
3940
import UIKit import CoreMotion // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- class FuhahaEvent{ // タッチ1情報 internal var t1id: Int = -1; internal var t1x: Int32 = 0; internal var t1y: Int32 = 0; internal var t1trigger: Bool = false; // タッチ2情報 internal var t2id: Int = -1; internal var t2x: Int32 = 0; internal var t2y: Int32 = 0; internal var t2trigger: Bool = false; // 加速度センサー internal let motionManager: CMMotionManager?; // ---------------------------------------------------------------- // コンストラクタ init(){ if(gameMainEventIsAcceleration()){ // 加速度センサー self.motionManager = CMMotionManager(); self.motionManager!.accelerometerUpdateInterval = 0.05; self.motionManager!.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {(data: CMAccelerometerData?, error: Error?) -> Void in if(data == nil){return;} // androidの軸方向に合わせる、最大値は知らん gameMainEventAcceleration(-data!.acceleration.x, -data!.acceleration.y, -data!.acceleration.z); }); }else{ self.motionManager = nil; } } // ---------------------------------------------------------------- func onTouch(){ if(self.t1trigger){gameMainEventTouch(0, self.t1x, self.t1y, (self.t1id >= 0))}; if(self.t2trigger){gameMainEventTouch(1, self.t2x, self.t2y, (self.t2id >= 0))}; self.t1trigger = false; self.t2trigger = false; } // タッチ開始 func touchesBegan(_ view: UIView, touches: Set<UITouch>, withEvent event: UIEvent?){ for touch: UITouch in touches{ let tid: Int = touch.hash; let point: CGPoint = touch.location(in: view); if(self.t1id < 0){ self.t1x = Int32(point.x); self.t1y = Int32(point.y); self.t1id = tid; self.t1trigger = true; }else if(self.t2id < 0){ self.t2x = Int32(point.x); self.t2y = Int32(point.y); self.t2id = tid; self.t2trigger = true; } } self.onTouch(); } // タッチ移動 func touchesMoved(_ view: UIView, touches: Set<UITouch>, withEvent event: UIEvent?){ for touch: UITouch in touches{ let tid: Int = touch.hash; let point: CGPoint = touch.location(in: view); if(self.t1id == tid){ self.t1x = Int32(point.x); self.t1y = Int32(point.y); self.t1trigger = true; }else if(self.t2id == tid){ self.t2x = Int32(point.x); self.t2y = Int32(point.y); self.t2trigger = true; } } self.onTouch(); } // タッチ完了 func touchesEnded(_ view: UIView, touches: Set<UITouch>, withEvent event: UIEvent?){ for touch: UITouch in touches{ let tid: Int = touch.hash; let point: CGPoint = touch.location(in: view); if(self.t1id == tid){ self.t1x = Int32(point.x); self.t1y = Int32(point.y); self.t1id = -1; self.t1trigger = true; }else if(self.t2id == tid){ self.t2x = Int32(point.x); self.t2y = Int32(point.y); self.t2id = -1; self.t2trigger = true; } } self.onTouch(); } // タッチ中止 func touchesCancelled(_ view: UIView, touches: Set<UITouch>!, withEvent event: UIEvent?){ for touch: UITouch in touches{ let tid: Int = touch.hash; let point: CGPoint = touch.location(in: view); if(self.t1id == tid){ self.t1x = Int32(point.x); self.t1y = Int32(point.y); self.t1id = -1; self.t1trigger = true; }else if(self.t2id == tid){ self.t2x = Int32(point.x); self.t2y = Int32(point.y); self.t2id = -1; self.t2trigger = true; } } self.onTouch(); } // ---------------------------------------------------------------- } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ----------------------------------------------------------------
mit
062deb7708d246c601c86d4f07596972
27.601504
146
0.537066
3.062802
false
false
false
false
stephentyrone/swift
test/NameLookup/scope_map-astscopelookup.swift
10
28963
// REQUIRES: enable-astscope-lookup // Note: test of the scope map. All of these tests are line- and // column-sensitive, so any additions should go at the end. struct S0 { class InnerC0 { } } extension S0 { } class C0 { } enum E0 { case C0 case C1(Int, Int) } struct GenericS0<T, U> { } func genericFunc0<T, U>(t: T, u: U, i: Int = 10) { } class ContainsGenerics0 { init<T, U>(t: T, u: U) { } deinit { } } typealias GenericAlias0<T> = [T] #if arch(unknown) struct UnknownArchStruct { } #else struct OtherArchStruct { } #endif func functionBodies1(a: Int, b: Int?) { let (x1, x2) = (a, b), (y1, y2) = (b, a) let (z1, z2) = (a, a) do { let a1 = a let a2 = a do { let b1 = b let b2 = b } } do { let b1 = b let b2 = b } func f(_ i: Int) -> Int { return i } let f2 = f(_:) struct S7 { } typealias S7Alias = S7 if let b1 = b, let b2 = b { let c1 = b } else { let c2 = b } guard let b1 = b, { $0 > 5 }(b1), let b2 = b else { let c = 5 return } while let b3 = b, let b4 = b { let c = 5 } repeat { } while true; for (x, y) in [(1, "hello"), (2, "world")] where x % 2 == 0 { } do { try throwing() } catch let mine as MyError where mine.value == 17 { } catch { } switch MyEnum.second(1) { case .second(let x) where x == 17: break; case .first: break; default: break; } for (var i = 0; i != 10; i += 1) { } } func throwing() throws { } struct MyError : Error { var value: Int } enum MyEnum { case first case second(Int) case third } struct StructContainsAbstractStorageDecls { subscript (i: Int, j: Int) -> Int { set { } get { return i + j } } var computed: Int { get { return 0 } set { } } } class ClassWithComputedProperties { var willSetProperty: Int = 0 { willSet { } } var didSetProperty: Int = 0 { didSet { } } } func funcWithComputedProperties(i: Int) { var computed: Int { set { } get { return 0 } }, var (stored1, stored2) = (1, 2), var alsoComputed: Int { return 17 } do { } } func closures() { { x, y in return { $0 + $1 }(x, y) }(1, 2) + { a, b in a * b }(3, 4) } { closures() }() func defaultArguments(i: Int = 1, j: Int = { $0 + $1 }(1, 2)) { func localWithDefaults(i: Int = 1, j: Int = { $0 + $1 }(1, 2)) { } let a = i + j { $0 }(a) } struct PatternInitializers { var (a, b) = (1, 2), (c, d) = (1.5, 2.5) } protocol ProtoWithSubscript { subscript(native: Int) -> Int { get set } } func localPatternsWithSharedType() { let i, j, k: Int } class LazyProperties { var value: Int = 17 lazy var prop: Int = self.value } // RUN: not %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded // RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded // CHECK-EXPANDED: ***Complete scope map*** // CHECK-EXPANDED-NEXT: ASTSourceFileScope {{.*}}, (uncached) [1:1 - 5{{[0-9]*}}:1] 'SOURCE_DIR{{[/]}}test{{[/]}}NameBinding{{[/]}}scope_map-astscopelookup.swift' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [5:1 - 7:1] 'S0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [5:11 - 7:1] 'S0' // CHECK-EXPANDED-NEXT: `-NominalTypeDeclScope {{.*}}, [6:3 - 6:19] 'InnerC0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0' // CHECK-EXPANDED-NEXT: |-ExtensionDeclScope {{.*}}, [9:1 - 10:1] 'S0' // CHECK-EXPANDED-NEXT: `-ExtensionBodyScope {{.*}}, [9:14 - 10:1] 'S0' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [12:1 - 13:1] 'C0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [12:10 - 13:1] 'C0' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [15:1 - 18:1] 'E0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [15:9 - 18:1] 'E0' // CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [16:8 - 16:8] // CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [17:8 - 17:19] // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [17:10 - 17:19] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [20:1 - 21:1] 'GenericS0' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 0 'T' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 1 'U' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [20:24 - 21:1] 'GenericS0' // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [23:1 - 24:1] 'genericFunc0(t:u:i:)' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 0 'T' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 1 'U' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [23:24 - 24:1] // CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [23:46 - 23:46] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [23:50 - 24:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [23:50 - 24:1] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [26:1 - 32:1] 'ContainsGenerics0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [26:25 - 32:1] 'ContainsGenerics0' // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [27:3 - 28:3] 'init(t:u:)' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 0 'T' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 1 'U' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [27:13 - 28:3] // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [27:26 - 28:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [27:26 - 28:3] // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [30:3 - 31:3] 'deinit' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [30:3 - 31:3] // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [30:10 - 31:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [30:10 - 31:3] // CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [34:1 - 34:32] <no extended nominal?!> // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [34:24 - 34:32] param 0 'T' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [39:1 - 39:26] 'OtherArchStruct' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [39:24 - 39:26] 'OtherArchStruct' // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [42:1 - 101:1] 'functionBodies1(a:b:)' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [42:21 - 101:1] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [42:39 - 101:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [42:39 - 101:1] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [43:7 - 43:23] entry 0 'x1' 'x2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [43:18 - 43:23] entry 0 'x1' 'x2' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [44:7 - 44:23] entry 1 'y1' 'y2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [44:18 - 44:23] entry 1 'y1' 'y2' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [45:7 - 45:23] entry 0 'z1' 'z2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [45:18 - 45:23] entry 0 'z1' 'z2' // CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [46:6 - 53:3] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [47:9 - 47:14] entry 0 'a1' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [47:14 - 47:14] entry 0 'a1' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [48:9 - 48:14] entry 0 'a2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [48:14 - 48:14] entry 0 'a2' // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [49:8 - 52:5] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [50:11 - 50:16] entry 0 'b1' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [50:16 - 50:16] entry 0 'b1' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [51:11 - 51:16] entry 0 'b2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [51:16 - 51:16] entry 0 'b2' // CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [54:6 - 57:3] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [55:9 - 55:14] entry 0 'b1' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [55:14 - 55:14] entry 0 'b1' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [56:9 - 56:14] entry 0 'b2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [56:14 - 56:14] entry 0 'b2' // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [58:3 - 58:38] 'f(_:)' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [58:9 - 58:38] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [58:27 - 58:38] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [58:27 - 58:38] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [59:7 - 59:16] entry 0 'f2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [59:12 - 59:16] entry 0 'f2' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [60:3 - 60:15] 'S7' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [60:13 - 60:15] 'S7' // CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [61:3 - 61:23] <no extended nominal?!> // CHECK-EXPANDED-NEXT: |-IfStmtScope {{.*}}, [63:3 - 67:3] // CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [63:6 - 65:3] index 0 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:18 - 65:3] let b1 // CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [63:18 - 65:3] index 1 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:29 - 65:3] let b2 // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [63:29 - 65:3] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [64:9 - 64:14] entry 0 'c1' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [64:14 - 64:14] entry 0 'c1' // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [65:10 - 67:3] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [66:9 - 66:14] entry 0 'c2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [66:14 - 66:14] entry 0 'c2' // CHECK-EXPANDED-NEXT: `-GuardStmtScope {{.*}}, [69:3 - 100:38] // CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [69:9 - 69:53] index 0 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:21 - 69:53] let b1 // CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:21 - 69:53] index 1 // CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [69:21 - 69:30] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [69:21 - 69:30] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [69:21 - 69:30] // CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:37 - 69:53] index 2 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:53 - 69:53] let b2 // CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [69:53 - 72:3] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [70:9 - 70:13] entry 0 'c' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [70:13 - 70:13] entry 0 'c' // CHECK-EXPANDED-NEXT: `-LookupParentDiversionScope, [72:3 - 100:38] // CHECK-EXPANDED-NEXT: |-WhileStmtScope {{.*}}, [74:3 - 76:3] // CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:9 - 76:3] index 0 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:21 - 76:3] let b3 // CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:21 - 76:3] index 1 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:32 - 76:3] let b4 // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [74:32 - 76:3] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [75:9 - 75:13] entry 0 'c' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [75:13 - 75:13] entry 0 'c' // CHECK-EXPANDED-NEXT: |-RepeatWhileScope {{.*}}, [78:3 - 78:20] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [78:10 - 78:12] // CHECK-EXPANDED-NEXT: |-ForEachStmtScope {{.*}}, [80:3 - 82:3] // CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [80:52 - 82:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [80:63 - 82:3] // CHECK-EXPANDED-NEXT: |-DoCatchStmtScope {{.*}}, [84:3 - 88:3] // CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [84:6 - 86:3] // CHECK-EXPANDED-NEXT: |-CatchStmtScope {{.*}}, [86:31 - 87:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [86:54 - 87:3] // CHECK-EXPANDED-NEXT: `-CatchStmtScope {{.*}}, [87:11 - 88:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [87:11 - 88:3] // CHECK-EXPANDED-NEXT: |-SwitchStmtScope {{.*}}, [90:3 - 99:3] // CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [91:29 - 92:10] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [92:5 - 92:10] // CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [95:5 - 95:10] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [95:5 - 95:10] // CHECK-EXPANDED-NEXT: `-CaseStmtScope {{.*}}, [98:5 - 98:10] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [98:5 - 98:10] // CHECK-EXPANDED-NEXT: `-ForEachStmtScope {{.*}}, [100:3 - 100:38] // CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [100:36 - 100:38] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [100:36 - 100:38] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [103:1 - 103:26] 'throwing()' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [103:14 - 103:26] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [103:24 - 103:26] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [103:24 - 103:26] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [105:1 - 107:1] 'MyError' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [105:24 - 107:1] 'MyError' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [106:7 - 106:14] entry 0 'value' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [109:1 - 113:1] 'MyEnum' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [109:13 - 113:1] 'MyEnum' // CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [110:8 - 110:8] // CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [111:8 - 111:18] // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [111:14 - 111:18] // CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [112:8 - 112:8] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [115:1 - 131:1] 'StructContainsAbstractStorageDecls' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [115:43 - 131:1] 'StructContainsAbstractStorageDecls' // CHECK-EXPANDED-NEXT: |-SubscriptDeclScope {{.*}}, [116:3 - 122:3] main.(file).StructContainsAbstractStorageDecls.subscript(_:_:)@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:116:3 // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [116:13 - 122:3] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [117:5 - 118:5] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [117:9 - 118:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [117:9 - 118:5] // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [119:5 - 121:5] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [119:9 - 121:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [119:9 - 121:5] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [124:21 - 130:3] entry 0 'computed' // CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [124:21 - 130:3] main.(file).StructContainsAbstractStorageDecls.computed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:124:7 // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [125:5 - 127:5] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [125:9 - 127:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [125:9 - 127:5] // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [128:5 - 129:5] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [128:9 - 129:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [128:9 - 129:5] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [133:1 - 141:1] 'ClassWithComputedProperties' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [133:35 - 141:1] 'ClassWithComputedProperties' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [134:7 - 136:3] entry 0 'willSetProperty' // CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [134:30 - 134:30] entry 0 'willSetProperty' // CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [134:32 - 136:3] main.(file).ClassWithComputedProperties.willSetProperty@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:134:7 // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [135:5 - 135:15] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [135:13 - 135:15] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [135:13 - 135:15] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [138:7 - 140:3] entry 0 'didSetProperty' // CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [138:29 - 138:29] entry 0 'didSetProperty' // CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [138:31 - 140:3] main.(file).ClassWithComputedProperties.didSetProperty@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:138:7 // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [139:5 - 139:14] '_' // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [139:12 - 139:14] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [139:12 - 139:14] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [143:1 - 156:1] 'funcWithComputedProperties(i:)' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [143:32 - 156:1] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [143:41 - 156:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [143:41 - 156:1] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [144:21 - 150:3] entry 0 'computed' // CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [144:21 - 150:3] main.(file).funcWithComputedProperties(i:).computed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:144:7 // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [145:5 - 146:5] '_' // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [145:9 - 146:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [145:9 - 146:5] // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [147:5 - 149:5] '_' // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [147:9 - 149:5] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [147:9 - 149:5] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [150:6 - 150:36] entry 1 'stored1' 'stored2' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [150:31 - 150:36] entry 1 'stored1' 'stored2' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [151:25 - 153:3] entry 2 'alsoComputed' // CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [151:25 - 153:3] main.(file).funcWithComputedProperties(i:).alsoComputed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:151:7 // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [151:25 - 153:3] '_' // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [151:25 - 153:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [151:25 - 153:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [155:6 - 155:8] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [158:1 - 163:1] 'closures()' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [158:14 - 163:1] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [158:17 - 163:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [158:17 - 163:1] // CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [159:3 - 161:3] // CHECK-EXPANDED-NEXT: `-ClosureParametersScope {{.*}}, [159:5 - 161:3] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [159:10 - 161:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [159:10 - 161:3] // CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [160:12 - 160:22] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [160:12 - 160:22] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [160:12 - 160:22] // CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [162:3 - 162:19] // CHECK-EXPANDED-NEXT: `-ClosureParametersScope {{.*}}, [162:5 - 162:19] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [162:10 - 162:19] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [162:10 - 162:19] // CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [165:1 - 195:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [165:1 - 195:1] // CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [165:1 - 165:14] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [165:1 - 165:14] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [165:1 - 165:14] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [167:1 - 176:1] 'defaultArguments(i:j:)' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [167:22 - 176:1] // CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32] // CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [168:32 - 168:48] // CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [168:32 - 168:42] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [168:32 - 168:42] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [168:32 - 168:42] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [168:51 - 176:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [168:51 - 176:1] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [170:3 - 172:3] 'localWithDefaults(i:j:)' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [170:25 - 172:3] // CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [170:35 - 170:35] // CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [171:35 - 171:51] // CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [171:35 - 171:45] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [171:35 - 171:45] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [171:35 - 171:45] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [171:54 - 172:3] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [171:54 - 172:3] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [174:7 - 175:11] entry 0 'a' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [174:11 - 175:11] entry 0 'a' // CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [175:3 - 175:8] // CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [175:3 - 175:8] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [175:3 - 175:8] // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [178:1 - 181:1] 'PatternInitializers' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [178:28 - 181:1] 'PatternInitializers' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [179:7 - 179:21] entry 0 'a' 'b' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [179:16 - 179:21] entry 0 'a' 'b' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [180:7 - 180:25] entry 1 'c' 'd' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [183:1 - 185:1] 'ProtoWithSubscript' // CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [183:29 - 185:1] param 0 'Self : ProtoWithSubscript' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [183:29 - 185:1] 'ProtoWithSubscript' // CHECK-EXPANDED-NEXT: `-SubscriptDeclScope {{.*}}, [184:3 - 184:43] main.(file).ProtoWithSubscript.subscript(_:)@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:184:3 // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [184:12 - 184:43] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [184:35 - 184:35] '_' // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [184:39 - 184:39] '_' // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [187:1 - 189:1] 'localPatternsWithSharedType()' // CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [187:33 - 189:1] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [187:36 - 189:1] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [187:36 - 189:1] // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [188:7 - 188:7] entry 0 'i' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [188:10 - 188:10] entry 1 'j' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [188:13 - 188:16] entry 2 'k' // CHECK-EXPANDED-NEXT: `-NominalTypeDeclScope {{.*}}, [191:1 - 195:1] 'LazyProperties' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [191:22 - 195:1] 'LazyProperties' // CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [192:7 - 192:20] entry 0 'value' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [192:20 - 192:20] entry 0 'value' // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [194:12 - 194:29] entry 0 'prop' // CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop' // RUN: not %target-swift-frontend -dump-scope-maps 71:8,27:20,6:18,167:32,180:18,194:26 %s 2> %t.searches // RUN: %FileCheck -check-prefix CHECK-SEARCHES %s < %t.searches // CHECK-SEARCHES: ***Scope at 71:8*** // CHECK-SEARCHES-NEXT: BraceStmtScope {{.*}}, [69:53 - 7{{[0-9]}}:3] // CHECK-SEARCHES-NEXT: Local bindings: c // CHECK-SEARCHES-NEXT: ***Scope at 27:20*** // CHECK-SEARCHES-NEXT: ParameterListScope {{.*}}, [27:13 - 28:3] // CHECK-SEARCHES-NEXT: ***Scope at 6:18*** // CHECK-SEARCHES-NEXT: NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0' // CHECK-SEARCHES-NEXT: {{.*}} Module name=main // CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift" // CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=S0 // CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=InnerC0 // CHECK-SEARCHES-NEXT: ***Scope at 167:32*** // CHECK-SEARCHES-NEXT: DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32] // CHECK-SEARCHES-NEXT: {{.*}} Module name=main // CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift" // CHECK-SEARCHES-NEXT: {{.*}} AbstractFunctionDecl name=defaultArguments(i:j:) : (Int, Int) -> () // CHECK-SEARCHES-NEXT: {{.*}} Initializer DefaultArgument index=0 // CHECK-SEARCHES-NEXT: ***Scope at 180:18*** // CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd' // CHECK-SEARCHES-NEXT: {{.*}} Module name=main // CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift" // CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=PatternInitializers // CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #1 // CHECK-SEARCHES-NEXT: ***Scope at 194:26*** // CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop' // CHECK-SEARCHES-NEXT: {{.*}} Module name=main // CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift" // CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=LazyProperties // CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #0 // CHECK-SEARCHES-NEXT: Local bindings: self // CHECK-SEARCHES-NOT: ***Complete scope map*** // REQUIRES: asserts // absence of assertions can change the "uncached" bit and cause failures
apache-2.0
2e74bd5851b6d99b704409b02ba4e465
56.352475
200
0.582018
3.563361
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Extensions/UIKit/UIView+CSVisibility.swift
1
1506
// // Created by Rene on 2018-11-22. // Copyright (c) 2018 Renetik Software. All rights reserved. // import UIKit import RenetikObjc import BlocksKit extension UIView: CSHasVisibilityProtocol { public var eventVisibilityChange: CSEvent<Bool> { associatedDictionary("UIView+eventVisibilityChange") { event() } } public var isVisible: Bool { get { !isHidden } set(value) { isHidden = !value; eventVisibilityChange.fire(value); } } } public extension UIView { @discardableResult func shown(if condition: Bool) -> Self { if condition { show() } else { hide() } return self } @discardableResult func hidden(if condition: Bool) -> Self { if condition { hide() } else { show() } return self } @discardableResult @objc open func show() -> Self { isVisible = true navigation.topViewController?.view.setNeedsLayout() superview?.setNeedsLayout() return self } @discardableResult @objc open func hide() -> Self { isVisible = false navigation.topViewController?.view.setNeedsLayout() superview?.setNeedsLayout() return self } var isVisibleThroughHierarchy: Bool { var view: UIView? = self repeat { if view!.isHidden { return false } view = view?.superview } while view.notNil return true } var isHiddenThroughHierarchy: Bool { !isVisibleThroughHierarchy } }
mit
a0b8ba33e27ebba932573052ea83730a
23.704918
76
0.62417
4.721003
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/MBarRouteTests.swift
2
4507
import XCTest import OHHTTPStubs @testable import WordPress struct MockRouter: LinkRouter { let matcher: RouteMatcher var completion: ((URL, DeepLinkSource?) -> Void)? init(routes: [Route]) { self.matcher = RouteMatcher(routes: routes) } func canHandle(url: URL) -> Bool { return true } func handle(url: URL, shouldTrack track: Bool, source: DeepLinkSource?) { completion?(url, source) } } class MBarRouteTests: XCTestCase { private var router: MockRouter! private var route: MbarRoute! private var matcher: RouteMatcher! override func setUp() { super.setUp() let requestExpectation = expectation(description: "Request made to original URL") router = MockRouter(routes: []) route = MbarRoute() matcher = RouteMatcher(routes: [route]) HTTPStubs.stubRequests(passingTest: isHost("public-api.wordpress.com")) { _ in defer { HTTPStubs.removeAllStubs() requestExpectation.fulfill() } return HTTPStubsResponse(data: Data(), statusCode: 200, headers: nil) } } func testSingleLevelPostRedirect() throws { let url = URL(string: "https://public-api.wordpress.com/mbar?redirect_to=/post")! let success = expectation(description: "Correct redirect URL found") router.completion = { url, _ in if url.lastPathComponent == "post" { success.fulfill() } } if let match = matcher.routesMatching(url).first { match.action.perform(match.values, source: nil, router: router) } waitForExpectations(timeout: 1.0) } func testSingleLevelStartRedirectWithOtherParameters() throws { let url = URL(string: "https://public-api.wordpress.com/mbar?redirect_to=/start&stat=groovemails-events&bin=wpcom_email_click")! let success = expectation(description: "Correct redirect URL found") router.completion = { url, _ in if url.lastPathComponent == "start" { success.fulfill() } } if let match = matcher.routesMatching(url).first { match.action.perform(match.values, source: nil, router: router) } waitForExpectations(timeout: 1.0) } func testMultiLevelWPLoginRedirect() throws { let url = URL(string: "https://public-api.wordpress.com/mbar/?stat=groovemails-events&bin=wpcom_email_click&redirect_to=https://wordpress.com/wp-login.php?action=immediate-login%26timestamp=1617470831%26login_reason=user_first_flow%26user_id=123456789%26token=abcdef%26login_email=test%40example.com%26login_locale=en%26redirect_to=https%3A%2F%2Fwordpress.com%2Fstart%26sr=1%26signature=abcdef%26user=123456")! let success = expectation(description: "Correct redirect URL found") router.completion = { url, _ in if url.lastPathComponent == "start" { success.fulfill() } } if let match = matcher.routesMatching(url).first { match.action.perform(match.values, source: nil, router: router) } waitForExpectations(timeout: 1.0) } func testExtractEmailCampaignFromURL() throws { let url = URL(string: "https://public-api.wordpress.com/mbar/?stat=groovemails-events&bin=wpcom_email_click&redirect_to=https://wordpress.com/wp-login.php?action=immediate-login%26timestamp=1617470831%26login_reason=user_first_flow%26user_id=123456789%26token=abcdef%26login_email=test%40example.com%26login_locale=en%26redirect_to=https%3A%2F%2Fwordpress.com%2Fstart%26sr=1%26signature=abcdef%26user=123456")! let success = expectation(description: "Email campaign found") router.completion = { url, source in if url.lastPathComponent == "start", let trackingInfo = source?.trackingInfo, trackingInfo == "user_first_flow" { success.fulfill() } } if let match = matcher.routesMatching(url).first { match.action.perform(match.values, source: nil, router: router) } waitForExpectations(timeout: 1.0) } }
gpl-2.0
331858ca2b652332e1d92a869800e78c
34.769841
418
0.605281
4.342004
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewController/RegisterDomainDetailsViewController+Cells.swift
2
3214
import UIKit extension RegisterDomainDetailsViewController { func checkMarkCell(with row: CheckMarkRow) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: WPTableViewCellDefault.defaultReuseID) as? WPTableViewCellDefault else { return UITableViewCell() } cell.textLabel?.text = row.title cell.selectionStyle = .none cell.accessoryType = (row.isSelected) ? .checkmark : .none WPStyleGuide.configureTableViewCell(cell) return cell } func addAdddressLineCell(with title: String?) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: WPTableViewCellDefault.defaultReuseID) as? WPTableViewCellDefault else { return UITableViewCell() } cell.textLabel?.text = title cell.selectionStyle = .none WPStyleGuide.configureTableViewActionCell(cell) return cell } func editableKeyValueCell(with row: EditableKeyValueRow, indexPath: IndexPath) -> UITableViewCell { func valueColor(row: EditableKeyValueRow) -> UIColor? { //we don't want to show red fonts before user taps register button return row.isValid(inContext: .serverSide) ? nil : .error } guard let cell = tableView.dequeueReusableCell(withIdentifier: InlineEditableNameValueCell.defaultReuseID) as? InlineEditableNameValueCell else { return UITableViewCell() } cell.update(with: InlineEditableNameValueCell.Model( key: row.key, value: row.value, placeholder: row.placeholder, valueColor: valueColor(row: row), accessoryType: row.accessoryType(), valueSanitizer: row.valueSanitizer )) updateStyle(of: cell, at: indexPath) cell.delegate = self return cell } private func updateStyle(of cell: InlineEditableNameValueCell, at indexPath: IndexPath) { guard let section = SectionIndex(rawValue: indexPath.section) else { return } cell.valueTextField.returnKeyType = .next switch section { case .contactInformation: guard let index = RegisterDomainDetailsViewModel.CellIndex.ContactInformation(rawValue: indexPath.row) else { return } cell.valueTextField.keyboardType = index.keyboardType cell.valueTextField.autocapitalizationType = .words case .phone: cell.valueTextField.keyboardType = .numberPad case .address: let addressField = viewModel.addressSectionIndexHelper.addressField(for: indexPath.row) switch addressField { case .postalCode: cell.valueTextField.keyboardType = .numbersAndPunctuation default: cell.valueTextField.keyboardType = .default cell.valueTextField.autocapitalizationType = .words } default: cell.valueTextField.keyboardType = .default cell.valueTextField.autocapitalizationType = .none } } }
gpl-2.0
53a65b20d949bb34a8c9e0ee67fc175d
35.522727
121
0.643746
5.658451
false
false
false
false
LYM-mg/DemoTest
其他功能/MGModalView/MGModalView/ViewController.swift
1
1418
// // ViewController.swift // MGModalView // // Created by i-Techsys.com on 17/4/7. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate lazy var normalModalView: MGModelView = MGModelView() fileprivate lazy var narrowedModalView: MGModelView = MGModelView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "ModalView" self.view.backgroundColor = UIColor.white self.normalModalView = MGModelView(size: CGSize(width: self.view.bounds.size.width, height: 300), andBaseViewController: self) self.normalModalView.contentView.backgroundColor = UIColor.yellow self.narrowedModalView = MGModelView(size: CGSize(width: self.view.bounds.size.width, height: 300), andBaseViewController: self) self.narrowedModalView.narrowedOff = true; self.narrowedModalView.contentView.backgroundColor = UIColor.red } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func model(_ sender: UIButton) { normalModalView.open() } @IBAction func narrowModel(_ sender: UIButton) { narrowedModalView.open() } }
mit
0899b5e966f16479ee084327ad6f0b88
30.444444
136
0.684099
4.594156
false
false
false
false
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-010/Smashtag/Smashtag/Twitter Swift 2.0/TwitterRequest.swift
1
9871
// // TwitterRequest.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation import Accounts import Social import CoreLocation // Simple Twitter query class // Create an instance of it using one of the initializers // Set the requestType and parameters (if not using a convenience init that sets those) // Call fetch (or fetchTweets if fetching Tweets) // The handler passed in will be called when the information comes back from Twitter // Once a successful fetch has happened, // a follow-on TwitterRequest to get more Tweets (newer or older) can be created // using the requestFor{Newer,Older} methods private var twitterAccount: ACAccount? public class TwitterRequest { public let requestType: String public let parameters: [String:String] // designated initializer public init(_ requestType: String, _ parameters: Dictionary<String, String> = [:]) { self.requestType = requestType self.parameters = parameters } // convenience initializer for creating a TwitterRequest that is a search for Tweets public convenience init(search: String, count: Int = 0, _ resultType: SearchResultType = .Mixed, _ region: CLCircularRegion? = nil) { var parameters = [TwitterKey.Query : search] if count > 0 { parameters[TwitterKey.Count] = "\(count)" } switch resultType { case .Recent: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypeRecent case .Popular: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypePopular default: break } if let geocode = region { parameters[TwitterKey.Geocode] = "\(geocode.center.latitude),\(geocode.center.longitude),\(geocode.radius/1000.0)km" } self.init(TwitterKey.SearchForTweets, parameters) } public enum SearchResultType { case Mixed case Recent case Popular } // convenience "fetch" for when self is a request that returns Tweet(s) // handler is not necessarily invoked on the main queue public func fetchTweets(handler: ([Tweet]) -> Void) { fetch { results in var tweets = [Tweet]() var tweetArray: NSArray? if let dictionary = results as? NSDictionary { if let tweets = dictionary[TwitterKey.Tweets] as? NSArray { tweetArray = tweets } else if let tweet = Tweet(data: dictionary) { tweets = [tweet] } } else if let array = results as? NSArray { tweetArray = array } if tweetArray != nil { for tweetData in tweetArray! { if let tweet = Tweet(data: tweetData as? NSDictionary) { tweets.append(tweet) } } } handler(tweets) } } public typealias PropertyList = AnyObject // send an arbitrary request off to Twitter // calls the handler (not necessarily on the main queue) // with the JSON results converted to a Property List public func fetch(handler: (results: PropertyList?) -> Void) { performTwitterRequest(SLRequestMethod.GET, handler: handler) } // generates a request for older Tweets than were returned by self // only makes sense if self has done a fetch already // only makes sense for requests for Tweets public var requestForOlder: TwitterRequest? { return min_id != nil ? modifiedRequest(parametersToChange: [TwitterKey.MaxID : min_id!]) : nil } // generates a request for newer Tweets than were returned by self // only makes sense if self has done a fetch already // only makes sense for requests for Tweets public var requestForNewer: TwitterRequest? { return (max_id != nil) ? modifiedRequest(parametersToChange: [TwitterKey.SinceID : max_id!], clearCount: true) : nil } // MARK: - Private Implementation // creates an appropriate SLRequest using the specified SLRequestMethod // then calls the other version of this method that takes an SLRequest // handler is not necessarily called on the main queue func performTwitterRequest(method: SLRequestMethod, handler: (PropertyList?) -> Void) { let jsonExtension = (self.requestType.rangeOfString(JSONExtension) == nil) ? JSONExtension : "" let request = SLRequest( forServiceType: SLServiceTypeTwitter, requestMethod: method, URL: NSURL(string: "\(TwitterURLPrefix)\(self.requestType)\(jsonExtension)"), parameters: self.parameters ) performTwitterRequest(request, handler: handler) } // sends the request to Twitter // unpackages the JSON response into a Property List // and calls handler (not necessarily on the main queue) func performTwitterRequest(request: SLRequest, handler: (PropertyList?) -> Void) { if let account = twitterAccount { request.account = account request.performRequestWithHandler { (jsonResponse, httpResponse, _) in var propertyListResponse: PropertyList? guard jsonResponse != nil else { let error = "No response from Twitter." self.log(error) propertyListResponse = error return } try! propertyListResponse = NSJSONSerialization.JSONObjectWithData( jsonResponse, options: NSJSONReadingOptions.MutableLeaves) if propertyListResponse == nil { let error = "Couldn't parse JSON response." self.log(error) propertyListResponse = error } self.synchronize { self.captureFollowonRequestInfo(propertyListResponse) } handler(propertyListResponse) } } else { let accountStore = ACAccountStore() let twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil) { (granted, _) in if granted { if let account = accountStore.accountsWithAccountType(twitterAccountType)?.last as? ACAccount { twitterAccount = account self.performTwitterRequest(request, handler: handler) } else { let error = "Couldn't discover Twitter account type." self.log(error) handler(error) } } else { let error = "Access to Twitter was not granted." self.log(error) handler(error) } } } } private var min_id: String? = nil private var max_id: String? = nil // modifies parameters in an existing request to create a new one private func modifiedRequest(parametersToChange parametersToChange: Dictionary<String,String>, clearCount: Bool = false) -> TwitterRequest { var newParameters = parameters for (key, value) in parametersToChange { newParameters[key] = value } if clearCount { newParameters[TwitterKey.Count] = nil } return TwitterRequest(requestType, newParameters) } // captures the min_id and max_id information // to support requestForNewer and requestForOlder private func captureFollowonRequestInfo(propertyListResponse: PropertyList?) { if let responseDictionary = propertyListResponse as? NSDictionary { self.max_id = responseDictionary.valueForKeyPath(TwitterKey.SearchMetadata.MaxID) as? String if let next_results = responseDictionary.valueForKeyPath(TwitterKey.SearchMetadata.NextResults) as? String { for queryTerm in next_results.componentsSeparatedByString(TwitterKey.SearchMetadata.Separator) { if queryTerm.hasPrefix("?\(TwitterKey.MaxID)=") { let next_id = queryTerm.componentsSeparatedByString("=") if next_id.count == 2 { self.min_id = next_id[1] } } } } } } // debug println with identifying prefix private func log(whatToLog: AnyObject) { debugPrint("TwitterRequest: \(whatToLog)") } // synchronizes access to self across multiple threads private func synchronize(closure: () -> Void) { objc_sync_enter(self) closure() objc_sync_exit(self) } // constants let JSONExtension = ".json" let TwitterURLPrefix = "https://api.twitter.com/1.1/" // keys in Twitter responses/queries struct TwitterKey { static let Count = "count" static let Query = "q" static let Tweets = "statuses" static let ResultType = "result_type" static let ResultTypeRecent = "recent" static let ResultTypePopular = "popular" static let Geocode = "geocode" static let SearchForTweets = "search/tweets" static let MaxID = "max_id" static let SinceID = "since_id" struct SearchMetadata { static let MaxID = "search_metadata.max_id_str" static let NextResults = "search_metadata.next_results" static let Separator = "&" } } }
apache-2.0
18049ee4762ec63ff3053fa4baf49e22
37.862205
144
0.606423
5.27861
false
false
false
false
sandsmedia/SS_Authentication
SS_Authentication/Common.swift
1
6122
// // Constants.swift // SS_Authentication // // Created by Eddie Li on 26/05/16. // Copyright © 2016 Software and Support Media GmbH. All rights reserved. // import UIKit let IOS_VERSION = (UIDevice.current.systemVersion as NSString).floatValue let IS_IPAD = (UIDevice.current.userInterfaceIdiom == .pad) let IS_LARGER_DEVICE = (UIScreen.main.bounds.height > 568) let IS_IPHONE_4S = (UIScreen.main.bounds.height < 568) // MARK: - Font let BASE_FONT_NAME = "HelveticaNeue" let BASE_FONT_NAME_BOLD = "HelveticaNeue-Bold" let FONT_SIZE_SMALL: CGFloat = ((IS_IPAD) ? 15.5 : 11.625) // 27px @ 72dpi let FONT_SIZE_MEDIUM: CGFloat = ((IS_IPAD) ? 20.0 : 15.275) // 35px @ 72dpi let FONT_SIZE_LARGE: CGFloat = ((IS_IPAD) ? 23.0 : 17.25) // 40px @ 72dpi let FONT_SIZE_XLARGE: CGFloat = ((IS_IPAD) ? 30.0 : 25.0) // 40px @ 72dpi let FONT_SMALL = UIFont(name: BASE_FONT_NAME, size: FONT_SIZE_SMALL) let FONT_MEDIUM = UIFont(name: BASE_FONT_NAME, size: FONT_SIZE_MEDIUM) let FONT_LARGE = UIFont(name: BASE_FONT_NAME, size: FONT_SIZE_LARGE) let FONT_XLARGE = UIFont(name: BASE_FONT_NAME, size: FONT_SIZE_XLARGE) let FONT_SMALL_BOLD = UIFont(name: BASE_FONT_NAME_BOLD, size: FONT_SIZE_SMALL) let FONT_MEDIUM_BOLD = UIFont(name: BASE_FONT_NAME_BOLD, size: FONT_SIZE_MEDIUM) let FONT_LARGE_BOLD = UIFont(name: BASE_FONT_NAME_BOLD, size: FONT_SIZE_LARGE) let FONT_COLOUR_BLACK = UIColor.black let FONT_COLOUR_WHITE = UIColor.white let FONT_COLOUR_LIGHT_GRAY = UIColor.lightGray let FONT_COLOUR_DARK_GRAY = UIColor.darkGray let FONT_ATTR_SMALL_WHITE = [NSFontAttributeName: FONT_SMALL!, NSForegroundColorAttributeName: FONT_COLOUR_WHITE] let FONT_ATTR_SMALL_BLACK = [NSFontAttributeName: FONT_SMALL!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_SMALL_LIGHT_GRAY = [NSFontAttributeName: FONT_SMALL!, NSForegroundColorAttributeName: FONT_COLOUR_LIGHT_GRAY] let FONT_ATTR_SMALL_DARK_GRAY = [NSFontAttributeName: FONT_SMALL!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_SMALL_DARK_GRAY_BOLD = [NSFontAttributeName: FONT_SMALL_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_MEDIUM_WHITE = [NSFontAttributeName: FONT_MEDIUM!, NSForegroundColorAttributeName:FONT_COLOUR_WHITE] let FONT_ATTR_MEDIUM_BLACK = [NSFontAttributeName: FONT_MEDIUM!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_MEDIUM_LIGHT_GRAY = [NSFontAttributeName: FONT_MEDIUM!, NSForegroundColorAttributeName: FONT_COLOUR_LIGHT_GRAY] let FONT_ATTR_MEDIUM_DARK_GRAY = [NSFontAttributeName: FONT_MEDIUM!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_MEDIUM_WHITE_BOLD = [NSFontAttributeName: FONT_MEDIUM_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_WHITE] let FONT_ATTR_MEDIUM_BLACK_BOLD = [NSFontAttributeName: FONT_MEDIUM_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_MEDIUM_LIGHT_GRAY_BOLD = [NSFontAttributeName: FONT_MEDIUM_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_LIGHT_GRAY] let FONT_ATTR_MEDIUM_DARK_GRAY_BOLD = [NSFontAttributeName: FONT_MEDIUM_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_LARGE_WHITE = [NSFontAttributeName: FONT_LARGE!, NSForegroundColorAttributeName: FONT_COLOUR_WHITE] let FONT_ATTR_LARGE_BLACK = [NSFontAttributeName: FONT_LARGE!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_LARGE_LIGHT_GRAY = [NSFontAttributeName: FONT_LARGE!, NSForegroundColorAttributeName: FONT_COLOUR_LIGHT_GRAY] let FONT_ATTR_LARGE_DARK_GRAY = [NSFontAttributeName: FONT_LARGE!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_LARGE_WHITE_BOLD = [NSFontAttributeName: FONT_LARGE_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_WHITE] let FONT_ATTR_LARGE_BLACK_BOLD = [NSFontAttributeName: FONT_LARGE_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_LARGE_LIGHT_GRAY_BOLD = [NSFontAttributeName: FONT_LARGE_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_LIGHT_GRAY] let FONT_ATTR_LARGE_DARK_GRAY_BOLD = [NSFontAttributeName: FONT_LARGE_BOLD!, NSForegroundColorAttributeName: FONT_COLOUR_DARK_GRAY] let FONT_ATTR_XLARGE_BLACK = [NSFontAttributeName: FONT_XLARGE!, NSForegroundColorAttributeName: FONT_COLOUR_BLACK] let FONT_ATTR_XLARGE_WHITE = [NSFontAttributeName: FONT_XLARGE!, NSForegroundColorAttributeName: FONT_COLOUR_WHITE] // MARK: - Keys let ADDRESS_KEY = "address" let API_KEY = "api_key" let X_TOKEN_KEY = "X-Token" let VALID_KEY = "is_valid" let USER_KEY = "user" let ID_KEY = "id" let EMAIL_KEY = "email" let PASSWORD_KEY = "password" let TOKEN_KEY = "token" let COURSES_KEY = "courses" let COURSE_ID_KEY = "course_id" let LESSON_ID_KEY = "lesson_id" let CHAPTER_ID_KEY = "chapter_id" let FAVOURITE_KEY = "favourite" let COMPLETED_KEY = "completed" let CURRENT_LESSON_KEY = "current_lesson" let CURRENT_CHAPTER_KEY = "current_chapter" let VIDEO_POSITION_KEY = "video_position" let SS_AUTHENTICATION_EMAIL_KEY = "SS_AUTHENTICATION_EMAIL" let SS_AUTHENTICATION_PASSWORD_KEY = "SS_AUTHENTICATION_PASSWORD" let SS_AUTHENTICATION_USER_ID_KEY = "SS_AUTHENTICATION_USER_ID" let SS_AUTHENTICATION_TOKEN_KEY = "SS_AUTHENTICATION_TOKEN" let PASSWORD_VALIDATION_REGEX = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$" // MARK: - General Config let GENERAL_SPACING: CGFloat = 12.0 let SMALL_SPACING = GENERAL_SPACING / 2.0 let LARGE_SPACING = 2 * GENERAL_SPACING let GENERAL_ITEM_WIDTH: CGFloat = 44.0 let GENERAL_ITEM_HEIGHT = GENERAL_ITEM_WIDTH let GENERAL_ITEM_RADIUS = GENERAL_ITEM_WIDTH / 2.0 let SMALL_ITEM_WIDTH = GENERAL_ITEM_WIDTH / 2.0 let SMALL_ITEM_HEIGHT = SMALL_ITEM_WIDTH let GENERAL_CELL_HEIGHT: CGFloat = 56.0 let NAVIGATION_BAR_HEIGHT: CGFloat = 64.0 let LOADING_DIAMETER: CGFloat = 10.0 let LOADING_RADIUS = LOADING_DIAMETER / 2.0 let TEXT_FIELD_LEFT_VIEW_FRAME = CGRect(x: 0.0, y: 0.0, width: 10.0, height: 0.0) let TEXT_FIELD_RADIUS: CGFloat = 5.0 let ANIMATION_DURATION = 0.3 // MARK: - HTTP Reuqest let TIME_OUT_INTERVAL = 120.0 let TIME_OUT_RESOURCE = 600.0 let INVALID_STATUS_CODE = 401 let NO_INTERNET_CONNECTION_STATUS_CODE = -1 let ERROR_STATUS_CODE = 0
mit
034c1d320922a38c43850f9a58772608
49.586777
135
0.764254
3.119776
false
false
false
false
squall09s/VegOresto
VegoResto/NSManagedObject/CategorieCulinaire.swift
1
1106
// // CategorieCulinaire // VegoResto // // Created by Laurent Nicolas on 16/04/2016. // Copyright © 2016 Nicolas Laurent. All rights reserved. // import Foundation import CoreData @objc(CategorieCulinaire) class CategorieCulinaire: NSManagedObject { // Insert code here to add functionality to your managed object subclass static func createCategorie(for restaurant: Restaurant, catname: String) { let entityCategorieCulinaire = NSEntityDescription.entity(forEntityName: "CategorieCulinaire", in: UserData.sharedInstance.managedContext) if let new_cat = (NSManagedObject(entity: entityCategorieCulinaire!, insertInto: UserData.sharedInstance.managedContext) as? CategorieCulinaire) { new_cat.name = catname new_cat.restaurants = NSSet() restaurant.addCategorieCulinaire(newCategorie: new_cat) new_cat.addRestaurant(restaurant: restaurant) } } func addRestaurant(restaurant: Restaurant) { let restaurants = self.mutableSetValue(forKey: "restaurants") restaurants.add(restaurant) } }
gpl-3.0
275e4ba0f71ed5538fd9f94e804ba1ef
27.333333
154
0.719457
3.946429
false
false
false
false
treejames/firefox-ios
Sync/RequestExtensions.swift
3
2296
/* 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 Alamofire import Shared extension Request { public func responseParsedJSON(partial: Bool, completionHandler: ResponseHandler) -> Self { let serializer = partial ? Request.PartialParsedJSONResponseSerializer() : Request.ParsedJSONResponseSerializer() return response(serializer: serializer, completionHandler: { (request, response, JSON, error) in completionHandler(request, response, JSON, error) }) } public func responseParsedJSON(#queue: dispatch_queue_t, partial: Bool, completionHandler: ResponseHandler) -> Self { let serializer = partial ? Request.PartialParsedJSONResponseSerializer() : Request.ParsedJSONResponseSerializer() return response(queue: queue, serializer: serializer, completionHandler: { (request, response, JSON, error) in completionHandler(request, response, JSON, error) }) } public class func PartialParsedJSONResponseSerializer() -> Serializer { return { (request, response, data) in if data == nil || data?.length == 0 { return (nil, nil) } var err: NSError? let o: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &err) if let err = err { return (nil, err) } if (o == nil) { return (nil, nil) } let json = JSON(o!) if json.isError { return (nil, json.asError) } return (json, nil) } } public class func ParsedJSONResponseSerializer() -> Serializer { return { (request, response, data) in if data == nil || data?.length == 0 { return (nil, nil) } let json = JSON(data: data!) if json.isError { return (nil, json.asError) } return (json, nil) } } }
mpl-2.0
c86577cef73012f5568fd577f618b565
34.338462
136
0.576655
5.057269
false
false
false
false
ijoshsmith/swift-tic-tac-toe
Framework/TicTacToe/Game.swift
1
2413
// // Game.swift // TicTacToe // // Created by Joshua Smith on 11/28/15. // Copyright © 2015 iJoshSmith. All rights reserved. // import Foundation /** Orchestrates gameplay between two players. */ public final class Game { public typealias CompletionHandler = Outcome -> Void public init(gameBoard: GameBoard, xStrategy: TicTacToeStrategy, oStrategy: TicTacToeStrategy) { self.gameBoard = gameBoard self.outcomeAnalyst = OutcomeAnalyst(gameBoard: gameBoard) self.playerX = Player(mark: .X, gameBoard: gameBoard, strategy: xStrategy) self.playerO = Player(mark: .O, gameBoard: gameBoard, strategy: oStrategy) } public func startPlayingWithCompletionHandler(completionHandler: CompletionHandler) { assert(self.completionHandler == nil, "Cannot start the same Game twice.") self.completionHandler = completionHandler currentPlayer = playerX } // MARK: - Non-public stored properties private var currentPlayer: Player? { didSet { currentPlayer?.choosePositionWithCompletionHandler(processChosenPosition) } } private var completionHandler: CompletionHandler! private let gameBoard: GameBoard private let outcomeAnalyst: OutcomeAnalyst private let playerO: Player private let playerX: Player } // MARK: - Private methods private extension Game { func processChosenPosition(position: GameBoard.Position) { guard let currentPlayer = currentPlayer else { assertionFailure("Why was a position chosen if there is no current player?") return } gameBoard.putMark(currentPlayer.mark, atPosition: position) log(position) if let outcome = outcomeAnalyst.checkForOutcome() { finishWithOutcome(outcome) } else { switchCurrentPlayer() } } func log(position: GameBoard.Position) { print("--- \(currentPlayer!.mark) played (\(position.row), \(position.column)) ---\n\(gameBoard.textRepresentation)\n") } func finishWithOutcome(outcome: Outcome) { completionHandler(outcome) currentPlayer = nil } func switchCurrentPlayer() { let xIsCurrent = (currentPlayer!.mark == .X) currentPlayer = xIsCurrent ? playerO : playerX } }
mit
909656fe0b13e1fdef3706c1b5f6e792
28.414634
127
0.651741
4.766798
false
false
false
false
domenicosolazzo/practice-swift
Notifications/Listening to Keyboard notifications/Listening to Keyboard notifications/ViewController.swift
1
3850
// // ViewController.swift // Listening to Keyboard notifications // // Created by Domenico Solazzo on 15/05/15. // License MIT // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textField: UITextField! @IBOutlet weak var scrollView: UIScrollView! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let center = NotificationCenter.default center.addObserver( self, selector: #selector(ViewController.handleKeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil ) center.addObserver( self, selector: #selector(ViewController.handleKeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil ) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) } func handleKeyboardWillShow(_ notification:Notification){ let userInfo = (notification as NSNotification).userInfo if let info = userInfo{ /* Get the duration of the animation of the keyboard for when it gets displayed on the screen. We will animate our contents using the same animation duration */ let animationDurationObject = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue let keyboardEndRectObject = info[UIKeyboardFrameEndUserInfoKey] as! NSValue var animationDuration = 0.0 var keyboardEndRect = CGRect.zero animationDurationObject.getValue(&animationDuration) keyboardEndRectObject.getValue(&keyboardEndRect) let window = UIApplication.shared.keyWindow /* Convert the frame from the window's coordinate system to our view's coordinate system */ keyboardEndRect = view.convert(keyboardEndRect, from: window) /* Find out how much of our view is being covered by the keyboard */ let intersectionOfKeyboardRectAndWindowRect = view.frame.intersection(keyboardEndRect); /* Scroll the scroll view up to show the full contents of our view */ UIView.animate(withDuration: animationDuration, animations: {[weak self] in self!.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: intersectionOfKeyboardRectAndWindowRect.size.height, right: 0) self!.scrollView.scrollRectToVisible(self!.textField.frame, animated: false) }) } } func handleKeyboardWillHide(_ notification: Notification){ let userInfo = (notification as NSNotification).userInfo if let info = userInfo{ let animationDurationObject = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue var animationDuration = 0.0; animationDurationObject.getValue(&animationDuration) UIView.animate(withDuration: animationDuration, animations: { [weak self] in self!.scrollView.contentInset = UIEdgeInsets.zero }) } } }
mit
d27710210c473f0621db75c29bc155f7
32.77193
87
0.589351
6.25
false
false
false
false
neonichu/NBMaterialDialogIOS
Pod/Classes/NBMaterialAlertDialog.swift
1
3865
// // NBMaterialAlertDialog.swift // NBMaterialDialogIOS // // Created by Torstein Skulbru on 02/05/15. // Copyright (c) 2015 Torstein Skulbru. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Torstein Skulbru // // 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. @objc public class NBMaterialAlertDialog : NBMaterialDialog { /** Displays an alert dialog with a simple text and buttons - parameter windowView: The window which the dialog is to be attached - parameter text: The main alert message - parameter okButtonTitle: The positive button if multiple buttons, or a dismiss action button if one button. Usually either OK or CANCEL (of only one button) - parameter action: The block you want to run when the user clicks any of the buttons. If no block is given, the standard dismiss action will be used - parameter cancelButtonTitle: The negative button when multiple buttons. */ public class func showAlertWithText(windowView: UIView, text: String, okButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialAlertDialog { return NBMaterialAlertDialog.showAlertWithTextAndTitle(windowView, text: text, title: nil, dialogHeight: nil, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle) } /** Displays an alert dialog with a simple text, title and buttons. Remember to read Material guidelines on when to include a dialog title. - parameter windowView: The window which the dialog is to be attached - parameter text: The main alert message - parameter title: The title of the alert - parameter okButtonTitle: The positive button if multiple buttons, or a dismiss action button if one button. Usually either OK or CANCEL (of only one button) - parameter action: The block you want to run when the user clicks any of the buttons. If no block is given, the standard dismiss action will be used - parameter cancelButtonTitle: The negative button when multiple buttons. */ public class func showAlertWithTextAndTitle(windowView: UIView, text: String, title: String?, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialAlertDialog { let alertLabel = UILabel() alertLabel.numberOfLines = 0 alertLabel.font = UIFont.robotoRegularOfSize(14) alertLabel.textColor = NBConfig.PrimaryTextDark alertLabel.text = text alertLabel.sizeToFit() let dialog = NBMaterialAlertDialog() dialog.showDialog(windowView, title: title, content: alertLabel, dialogHeight: dialogHeight ?? dialog.kMinimumHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle) return dialog } }
mit
3660bf844bb02dcbf474fd7877b91f21
55.852941
242
0.749288
4.759852
false
false
false
false
apple/swift-nio-http2
Sources/NIOHTTP2/HTTP2Frame.swift
1
13431
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOHTTP1 import NIOHPACK /// A representation of a single HTTP/2 frame. public struct HTTP2Frame: Sendable { /// The ID representing the stream on which this frame is sent. public var streamID: HTTP2StreamID /// The payload of this HTTP/2 frame. public var payload: FramePayload /// Stream priority data, used in PRIORITY frames and optionally in HEADERS frames. public struct StreamPriorityData: Equatable, Hashable, Sendable { public var exclusive: Bool public var dependency: HTTP2StreamID public var weight: UInt8 } /// Frame-type-specific payload data. public enum FramePayload { /// A `DATA` frame, containing raw bytes. /// /// See [RFC 7540 § 6.1](https://httpwg.org/specs/rfc7540.html#rfc.section.6.1). indirect case data(FramePayload.Data) /// A `HEADERS` frame, containing all headers or trailers associated with a request /// or response. /// /// Note that swift-nio-http2 automatically coalesces `HEADERS` and `CONTINUATION` /// frames into a single ``HTTP2Frame/FramePayload/headers(_:)`` instance. /// /// See [RFC 7540 § 6.2](https://httpwg.org/specs/rfc7540.html#rfc.section.6.2). indirect case headers(Headers) /// A `PRIORITY` frame, used to change priority and dependency ordering among /// streams. /// /// See [RFC 7540 § 6.3](https://httpwg.org/specs/rfc7540.html#rfc.section.6.3). case priority(StreamPriorityData) /// A `RST_STREAM` (reset stream) frame, sent when a stream has encountered an error /// condition and needs to be terminated as a result. /// /// See [RFC 7540 § 6.4](https://httpwg.org/specs/rfc7540.html#rfc.section.6.4). case rstStream(HTTP2ErrorCode) /// A `SETTINGS` frame, containing various connection--level settings and their /// desired values. /// /// See [RFC 7540 § 6.5](https://httpwg.org/specs/rfc7540.html#rfc.section.6.5). case settings(Settings) /// A `PUSH_PROMISE` frame, used to notify a peer in advance of streams that a sender /// intends to initiate. It performs much like a request's `HEADERS` frame, informing /// a peer that the response for a theoretical request like the one in the promise /// will arrive on a new stream. /// /// As with the `HEADERS` frame, `swift-nio-http2` will coalesce an initial `PUSH_PROMISE` /// frame with any `CONTINUATION` frames that follow, emitting a single /// ``HTTP2Frame/FramePayload/pushPromise(_:)`` instance for the complete set. /// /// See [RFC 7540 § 6.6](https://httpwg.org/specs/rfc7540.html#rfc.section.6.6). /// /// For more information on server push in HTTP/2, see /// [RFC 7540 § 8.2](https://httpwg.org/specs/rfc7540.html#rfc.section.8.2). indirect case pushPromise(PushPromise) /// A `PING` frame, used to measure round-trip time between endpoints. /// /// See [RFC 7540 § 6.7](https://httpwg.org/specs/rfc7540.html#rfc.section.6.7). case ping(HTTP2PingData, ack: Bool) /// A `GOAWAY` frame, used to request that a peer immediately cease communication with /// the sender. It contains a stream ID indicating the last stream that will be processed /// by the sender, an error code (if the shutdown was caused by an error), and optionally /// some additional diagnostic data. /// /// See [RFC 7540 § 6.8](https://httpwg.org/specs/rfc7540.html#rfc.section.6.8). indirect case goAway(lastStreamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, opaqueData: ByteBuffer?) /// A `WINDOW_UPDATE` frame. This is used to implement flow control of DATA frames, /// allowing peers to advertise and update the amount of data they are prepared to /// process at any given moment. /// /// See [RFC 7540 § 6.9](https://httpwg.org/specs/rfc7540.html#rfc.section.6.9). case windowUpdate(windowSizeIncrement: Int) /// An `ALTSVC` frame. This is sent by an HTTP server to indicate alternative origin /// locations for accessing the same resource, for instance via another protocol, /// or over TLS. It consists of an origin and a list of alternate protocols and /// the locations at which they may be addressed. /// /// See [RFC 7838 § 4](https://tools.ietf.org/html/rfc7838#section-4). /// /// - Important: ALTSVC frames are not currently supported. Any received ALTSVC frames will /// be ignored. Attempting to send an ALTSVC frame will result in a fatal error. indirect case alternativeService(origin: String?, field: ByteBuffer?) /// An `ORIGIN` frame. This allows servers which allow access to multiple origins /// via the same socket connection to identify which origins may be accessed in /// this manner. /// /// See [RFC 8336 § 2](https://tools.ietf.org/html/rfc8336#section-2). /// /// > Important: `ORIGIN` frames are not currently supported. Any received `ORIGIN` frames will /// > be ignored. Attempting to send an `ORIGIN` frame will result in a fatal error. case origin([String]) /// The payload of a `DATA` frame. public struct Data { /// The application data carried within the `DATA` frame. public var data: IOData /// The value of the `END_STREAM` flag on this frame. public var endStream: Bool /// The underlying number of padding bytes. If nil, no padding is present. internal private(set) var _paddingBytes: UInt8? /// The number of padding bytes sent in this frame. If nil, this frame was not padded. public var paddingBytes: Int? { get { return self._paddingBytes.map { Int($0) } } set { if let newValue = newValue { precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") self._paddingBytes = UInt8(newValue) } else { self._paddingBytes = nil } } } public init(data: IOData, endStream: Bool = false, paddingBytes: Int? = nil) { self.data = data self.endStream = endStream self.paddingBytes = paddingBytes } } /// The payload of a `HEADERS` frame. public struct Headers: Sendable { /// The decoded header block belonging to this `HEADERS` frame. public var headers: HPACKHeaders /// The stream priority data transmitted on this frame, if any. public var priorityData: StreamPriorityData? /// The value of the `END_STREAM` flag on this frame. public var endStream: Bool /// The underlying number of padding bytes. If nil, no padding is present. internal private(set) var _paddingBytes: UInt8? /// The number of padding bytes sent in this frame. If nil, this frame was not padded. public var paddingBytes: Int? { get { return self._paddingBytes.map { Int($0) } } set { if let newValue = newValue { precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") self._paddingBytes = UInt8(newValue) } else { self._paddingBytes = nil } } } public init(headers: HPACKHeaders, priorityData: StreamPriorityData? = nil, endStream: Bool = false, paddingBytes: Int? = nil) { self.headers = headers self.priorityData = priorityData self.endStream = endStream self.paddingBytes = paddingBytes } } /// The payload of a `SETTINGS` frame. public enum Settings: Sendable { /// This `SETTINGS` frame contains new `SETTINGS`. case settings(HTTP2Settings) /// This is a `SETTINGS` `ACK`. case ack } /// The payload of a `PUSH_PROMISE` frame. public struct PushPromise: Sendable { /// The pushed stream ID. public var pushedStreamID: HTTP2StreamID /// The decoded header block belonging to this `PUSH_PROMISE` frame. public var headers: HPACKHeaders /// The underlying number of padding bytes. If nil, no padding is present. internal private(set) var _paddingBytes: UInt8? /// The number of padding bytes sent in this frame. If nil, this frame was not padded. public var paddingBytes: Int? { get { return self._paddingBytes.map { Int($0) } } set { if let newValue = newValue { precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") self._paddingBytes = UInt8(newValue) } else { self._paddingBytes = nil } } } public init(pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, paddingBytes: Int? = nil) { self.headers = headers self.pushedStreamID = pushedStreamID self.paddingBytes = paddingBytes } } /// The one-byte identifier used to indicate the type of a frame on the wire. var code: UInt8 { switch self { case .data: return 0x0 case .headers: return 0x1 case .priority: return 0x2 case .rstStream: return 0x3 case .settings: return 0x4 case .pushPromise: return 0x5 case .ping: return 0x6 case .goAway: return 0x7 case .windowUpdate: return 0x8 case .alternativeService: return 0xa case .origin: return 0xc } } } /// Constructs a frame header for a given stream ID. public init(streamID: HTTP2StreamID, payload: HTTP2Frame.FramePayload) { self.payload = payload self.streamID = streamID } } extension HTTP2Frame.FramePayload { /// A shorthand heuristic for how many bytes we assume a frame consumes on the wire. /// /// Here we concern ourselves only with per-stream frames: that is, `HEADERS`, `DATA`, /// `WINDOW_UDPATE`, `RST_STREAM`, and I guess `PRIORITY`. As a simple heuristic we /// hard code fixed lengths for fixed length frames, use a calculated length for /// variable length frames, and just ignore encoded headers because it's not worth doing a better /// job. var estimatedFrameSize: Int { let frameHeaderSize = 9 switch self { case .data(let d): let paddingBytes = d.paddingBytes.map { $0 + 1 } ?? 0 return d.data.readableBytes + paddingBytes + frameHeaderSize case .headers(let h): let paddingBytes = h.paddingBytes.map { $0 + 1 } ?? 0 return paddingBytes + frameHeaderSize case .priority: return frameHeaderSize + 5 case .pushPromise(let p): // Like headers, this is variably size, and we just ignore the encoded headers because // it's not worth having a heuristic. let paddingBytes = p.paddingBytes.map { $0 + 1 } ?? 0 return paddingBytes + frameHeaderSize case .rstStream: return frameHeaderSize + 4 case .windowUpdate: return frameHeaderSize + 4 default: // Unknown or unexpected control frame: say 9 bytes. return frameHeaderSize } } } /// ``HTTP2Frame/FramePayload/Data`` and therefore ``HTTP2Frame/FramePayload`` and ``HTTP2Frame`` are actually **not** `Sendable`, /// because ``HTTP2Frame/FramePayload/Data/data`` stores `IOData` which is not and can not be `Sendable`. /// Marking them non-Sendable would sadly be API breaking. extension HTTP2Frame.FramePayload: @unchecked Sendable {} extension HTTP2Frame.FramePayload.Data: @unchecked Sendable {}
apache-2.0
e658b7330467287a3ef9126fbfbaf299
43.287129
140
0.577316
4.657758
false
false
false
false
garriguv/SQLiteMigrationManager.swift
Sources/SQLiteMigrationManager.swift
1
7635
import Foundation import SQLite private struct MigrationDB { static let table = Table("schema_migrations") static let version = Expression<Int64>("version") } /// Interface for managing migrations for a SQLite database accessed via `SQLite.swift`. public struct SQLiteMigrationManager { /// The `SQLite.swift` database `Connection`. fileprivate let db: Connection /// All migrations discovered by the receiver. public let migrations: [Migration] /** Creates a new migration manager. - parameters: - db: The database `Connection`. - migrations: An array of `Migration`. Defaults to `[]`. - bundle: An `NSBundle` containing SQL migrations. Defaults to `nil`. */ public init(db: Connection, migrations: [Migration] = [], bundle: Bundle? = nil) { self.db = db self.migrations = [ bundle?.migrations() ?? [], migrations ].joined().sorted { $0.version < $1.version } } /** Creates a new migration manager. - parameters: - url: The url to a database with which to initialize the migration manager. - migrations: An array of `Migration`. Defaults to `[]`. - bundle: An `NSBundle` containing SQL migrations. Defaults to `nil`. */ public init?(url: URL, migrations: [Migration] = [], bundle: Bundle? = nil) { do { let db = try Connection(url.absoluteString) self.init(db: db, migrations: migrations, bundle: bundle) } catch { return nil } } /** Creates a new migration manager. - parameters: - path: The path to a database with which to initialize the migration manager. - migrations: An array of `Migration`. Defaults to `[]`. - bundle: An `NSBundle` containing SQL migrations. Defaults to `nil`. */ public init?(path: String, migrations: [Migration] = [], bundle: Bundle? = nil) { if let url = URL(string: path) { self.init(url: url, migrations: migrations, bundle: bundle) } return nil } /** Returns a `Bool` value that indicates if the `schema_migrations` table is present in the database managed by the receiver. */ public func hasMigrationsTable() -> Bool { let sqliteMaster = Table("sqlite_master") let type = Expression<String>("type") let name = Expression<String>("name") do { let tableCount = try db.scalar(sqliteMaster.filter(type == "table" && name == "schema_migrations").count) return tableCount == 1 } catch { return false } } /** Creates the `schema_migrations` table in the database managed by the receiver. */ public func createMigrationsTable() throws { try db.run(MigrationDB.table.create(ifNotExists: true) { table in table.column(MigrationDB.version, unique: true) }) } /** The current version of the database managed by the receiver or `0` if the migrations table is not present or empty. */ public func currentVersion() -> Int64 { if !hasMigrationsTable() { return 0 } do { let version = try db.scalar(MigrationDB.table.select(MigrationDB.version.max)) return version ?? 0 } catch { return 0 } } /** The origin version of the database managed by the receiver or `0` if the migrations table is not present or empty. */ public func originVersion() -> Int64 { if !hasMigrationsTable() { return 0 } do { let version = try db.scalar(MigrationDB.table.select(MigrationDB.version.min)) return version ?? 0 } catch { return 0 } } /** An array of versions contained in the migrations table managed by the receiver. Empty if the migrations table is not present. */ public func appliedVersions() -> [Int64] { do { var versions = [Int64]() try db.prepare(MigrationDB.table.select(MigrationDB.version).order(MigrationDB.version)).forEach { versions.append($0[MigrationDB.version]) } return versions } catch { return [] } } /** A subset of `migrations` that have not yet been applied to the database managed by the receiver. */ public func pendingMigrations() -> [Migration] { if !hasMigrationsTable() { return migrations } let versions = appliedVersions() return migrations.filter { migration in !versions.contains(migration.version) } } /** Returns a `Bool` value that indicates if the database managed by the receiver is in need of migration. */ public func needsMigration() -> Bool { if !hasMigrationsTable() { return false } return pendingMigrations().count > 0 } /** Migrates the database managed by the receiver to the specified version. Each individual migration is performed within a transaction that is rolled back if any error occurs. - parameters: - toVersion: The target version to migrate the database to. Defaults to `Int64.max`. */ public func migrateDatabase(toVersion: Int64 = Int64.max) throws { try pendingMigrations().filter { $0.version <= toVersion }.forEach { migration in try db.transaction { try migration.migrateDatabase(self.db) let _ = try self.db.run(MigrationDB.table.insert(MigrationDB.version <- migration.version)) } } } } extension Bundle { fileprivate func migrations() -> [Migration] { if let urls = urls(forResourcesWithExtension: "sql", subdirectory: nil) { return urls.compactMap { FileMigration(url: $0) } } else { return [] } } } /// The `Migration` protocol is adopted in order to provide migration of SQLite databases accessed via `SQLite.swift` public protocol Migration: CustomStringConvertible { /// The numeric version of the migration. var version: Int64 { get } /// Tells the receiver to apply its changes to the given database. func migrateDatabase(_ db: Connection) throws } public extension Migration { var description: String { return "Migration(\(version))" } } /// The `FileMigration` struct is used to reference SQL file migrations. public struct FileMigration: Migration { /// The numeric version of the migration. public let version: Int64 /// The `NSURL` of the migration file. public let url: URL /// Tells the receiver to apply its changes to the given database. public func migrateDatabase(_ db: Connection) throws { let fileContents = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) try db.execute(fileContents as String) } } extension FileMigration { /** Creates a new file migration. File migrations should have filenames of the form: - `1.sql` - `2_add_new_table.sql` - `3_add-new-table.sql` - `4_add new table.sql` - returns: A file migration if the filename matches `^(\d+)_?([\w\s-]*)\.sql$`. */ public init?(url: URL) { guard let version = FileMigration.extractVersion(url.lastPathComponent) else { return nil } self.version = version self.url = url } } extension FileMigration { static fileprivate let regex = try! NSRegularExpression(pattern: "^(\\d+)_?([\\w\\s-]*)\\.sql$", options: .caseInsensitive) static fileprivate func extractVersion(_ filename: String) -> Int64? { if let result = regex.firstMatch(in: filename, options: .reportProgress, range: NSMakeRange(0, filename.distance(from: filename.startIndex, to: filename.endIndex))), result.numberOfRanges == 3 { return Int64((filename as NSString).substring(with: result.range(at: 1))) } return nil } } extension FileMigration: CustomStringConvertible { public var description: String { return "FileMigration(\(version), \(url))" } }
mit
aa314077afa63116bac01652944e238b
28.824219
198
0.666405
4.153972
false
false
false
false
Anders123fr/GrowingTextViewHandler
GrowingTextViewHandler/FormTableViewCell.swift
2
1912
// // FormTableViewCell.swift // GrowingTextViewHandler // // Created by Susmita Horrow on 08/08/16. // Copyright © 2016 hsusmita.com. All rights reserved. // import UIKit import GrowingTextViewHandler protocol FormTableViewCellDelegate { func formTableViewCell(_ formTableViewCell: FormTableViewCell, shouldChangeHeight height: CGFloat) } class FormTableViewCell: UITableViewCell { @IBOutlet weak var textView: UITextView! fileprivate var handler: GrowingTextViewHandler? var delegate: FormTableViewCellDelegate? @IBOutlet weak var heightConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() handler = GrowingTextViewHandler(textView: self.textView, heightConstraint: self.heightConstraint) handler?.minimumNumberOfLines = 2 handler?.maximumNumberOfLines = 6 handler?.setText("", animated: false) // handler?.setText("Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.", animated: false) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func textViewDidChange(_ textView: UITextView) { let oldFrame = textView.frame self.handler?.resizeTextView(true) let currentFrame = textView.frame if oldFrame.height != currentFrame.height { delegate?.formTableViewCell(self, shouldChangeHeight: textView.frame.height) } } }
mit
2006089a3c1a41b1c399621042384675
42.431818
570
0.778127
4.604819
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/DecodeUserConfiguration.swift
1
3050
// // DecodeUserConfiguration.swift // RsyncUI // // Created by Thomas Evensen on 12/02/2022. // import Foundation struct DecodeUserConfiguration: Codable { let rsyncversion3: Int? // Detailed logging let detailedlogging: Int? // Logging to logfile let minimumlogging: Int? let fulllogging: Int? // let nologging: Int? // Monitor network connection let monitornetworkconnection: Int? // local path for rsync let localrsyncpath: String? // temporary path for restore let pathforrestore: String? // days for mark days since last synchronize let marknumberofdayssince: String? // Global ssh keypath and port let sshkeypathandidentityfile: String? let sshport: Int? // Environment variable let environment: String? let environmentvalue: String? // Paths // Paths let pathrsyncosx: String? let pathrsyncosxsched: String? // Enable schedules let enableschdules: Int? enum CodingKeys: String, CodingKey { case rsyncversion3 case detailedlogging case minimumlogging case fulllogging // case nologging case monitornetworkconnection case localrsyncpath case pathforrestore case marknumberofdayssince case sshkeypathandidentityfile case sshport case environment case environmentvalue case pathrsyncosx case pathrsyncosxsched case enableschdules } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) rsyncversion3 = try values.decodeIfPresent(Int.self, forKey: .rsyncversion3) detailedlogging = try values.decodeIfPresent(Int.self, forKey: .detailedlogging) minimumlogging = try values.decodeIfPresent(Int.self, forKey: .minimumlogging) fulllogging = try values.decodeIfPresent(Int.self, forKey: .fulllogging) // nologging = try values.decodeIfPresent(Int.self, forKey: .nologging) monitornetworkconnection = try values.decodeIfPresent(Int.self, forKey: .monitornetworkconnection) localrsyncpath = try values.decodeIfPresent(String.self, forKey: .localrsyncpath) pathforrestore = try values.decodeIfPresent(String.self, forKey: .pathforrestore) marknumberofdayssince = try values.decodeIfPresent(String.self, forKey: .marknumberofdayssince) sshkeypathandidentityfile = try values.decodeIfPresent(String.self, forKey: .sshkeypathandidentityfile) sshport = try values.decodeIfPresent(Int.self, forKey: .sshport) environment = try values.decodeIfPresent(String.self, forKey: .environment) environmentvalue = try values.decodeIfPresent(String.self, forKey: .environmentvalue) pathrsyncosx = try values.decodeIfPresent(String.self, forKey: .pathrsyncosx) pathrsyncosxsched = try values.decodeIfPresent(String.self, forKey: .pathrsyncosxsched) enableschdules = try values.decodeIfPresent(Int.self, forKey: .enableschdules) } }
mit
cf8e3c483b44808c29df24f0988efd56
38.61039
111
0.711475
4.407514
false
false
false
false
Hendrik44/pi-weather-app
Pi-WeatherWatch Extension/InterfaceController.swift
1
2271
// // InterfaceController.swift // Pi-WeatherWatch Extension // // Created by Hendrik on 09/10/2016. // Copyright © 2016 JG-Bits UG (haftungsbeschränkt). All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var temperatureLabel: WKInterfaceLabel! @IBOutlet var humidityLabel: WKInterfaceLabel! @IBOutlet var pressureLabel: WKInterfaceLabel! @IBOutlet var timestampLabel: WKInterfaceLabel! var timer:Timer? override func awake(withContext context: Any?) { super.awake(withContext: context) print(#function) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() print(#function) refresh() timer = Timer.scheduledTimer(timeInterval: AppSettings.sharedInstance.refreshDataInterval, target: self, selector: #selector(refresh), userInfo: nil, repeats: true) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() print(#function) timer?.invalidate() } @objc func refresh() { APIController().liveDataForSensorType(.all) { (sensorData, timestamp, error) in if error == nil && sensorData != nil && timestamp != nil { if let temperature = sensorData?[.temperature] { self.temperatureLabel.setText("\(temperature) °C") } if let humidity = sensorData?[.humidity] { self.humidityLabel.setText("\(humidity) %") } if let pressure = sensorData?[.pressure] { self.pressureLabel.setText("\(pressure) hPa") } self.timestampLabel.setText("\(timestamp!)") } else { self.timestampLabel.setText("Fehler beim Abrufen der Messwerte") } } } }
mit
aa415f63ec5efe6656e01ab3abe34d2c
32.850746
98
0.568342
5.425837
false
false
false
false
nathawes/swift
stdlib/public/core/Integers.swift
2
140538
//===--- Integers.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //===--- Bits for the Stdlib ----------------------------------------------===// //===----------------------------------------------------------------------===// // FIXME(integers): This should go in the stdlib separately, probably. extension ExpressibleByIntegerLiteral where Self: _ExpressibleByBuiltinIntegerLiteral { @_transparent public init(integerLiteral value: Self) { self = value } } //===----------------------------------------------------------------------===// //===--- AdditiveArithmetic -----------------------------------------------===// //===----------------------------------------------------------------------===// /// A type with values that support addition and subtraction. /// /// The `AdditiveArithmetic` protocol provides a suitable basis for additive /// arithmetic on scalar values, such as integers and floating-point numbers, /// or vectors. You can write generic methods that operate on any numeric type /// in the standard library by using the `AdditiveArithmetic` protocol as a /// generic constraint. /// /// The following code declares a method that calculates the total of any /// sequence with `AdditiveArithmetic` elements. /// /// extension Sequence where Element: AdditiveArithmetic { /// func sum() -> Element { /// return reduce(.zero, +) /// } /// } /// /// The `sum()` method is now available on any sequence with values that /// conform to `AdditiveArithmetic`, whether it is an array of `Double` or a /// range of `Int`. /// /// let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum() /// // arraySum == 16.5 /// /// let rangeSum = (1..<10).sum() /// // rangeSum == 45 /// /// Conforming to the AdditiveArithmetic Protocol /// ============================================= /// /// To add `AdditiveArithmetic` protocol conformance to your own custom type, /// implement the required operators, and provide a static `zero` property /// using a type that can represent the magnitude of any value of your custom /// type. public protocol AdditiveArithmetic: Equatable { /// The zero value. /// /// Zero is the identity element for addition. For any value, /// `x + .zero == x` and `.zero + x == x`. static var zero: Self { get } /// Adds two values and produces their sum. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// 1 + 2 // 3 /// -10 + 15 // 5 /// -15 + -5 // -20 /// 21.5 + 3.25 // 24.75 /// /// You cannot use `+` with arguments of different types. To add values of /// different types, convert one of the values to the other value's type. /// /// let x: Int8 = 21 /// let y: Int = 1000000 /// Int(x) + y // 1000021 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. static func +=(lhs: inout Self, rhs: Self) /// Subtracts one value from another and produces their difference. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// 8 - 3 // 5 /// -10 - 5 // -15 /// 100 - -5 // 105 /// 10.5 - 100.0 // -89.5 /// /// You cannot use `-` with arguments of different types. To subtract values /// of different types, convert one of the values to the other value's type. /// /// let x: UInt8 = 21 /// let y: UInt = 1000000 /// y - UInt(x) // 999979 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in the /// left-hand-side variable. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. static func -=(lhs: inout Self, rhs: Self) } public extension AdditiveArithmetic { @_alwaysEmitIntoClient static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs } @_alwaysEmitIntoClient static func -=(lhs: inout Self, rhs: Self) { lhs = lhs - rhs } } public extension AdditiveArithmetic where Self: ExpressibleByIntegerLiteral { /// The zero value. /// /// Zero is the identity element for addition. For any value, /// `x + .zero == x` and `.zero + x == x`. @inlinable @inline(__always) static var zero: Self { return 0 } } //===----------------------------------------------------------------------===// //===--- Numeric ----------------------------------------------------------===// //===----------------------------------------------------------------------===// /// A type with values that support multiplication. /// /// The `Numeric` protocol provides a suitable basis for arithmetic on /// scalar values, such as integers and floating-point numbers. You can write /// generic methods that operate on any numeric type in the standard library /// by using the `Numeric` protocol as a generic constraint. /// /// The following example extends `Sequence` with a method that returns an /// array with the sequence's values multiplied by two. /// /// extension Sequence where Element: Numeric { /// func doublingAll() -> [Element] { /// return map { $0 * 2 } /// } /// } /// /// With this extension, any sequence with elements that conform to `Numeric` /// has the `doublingAll()` method. For example, you can double the elements of /// an array of doubles or a range of integers: /// /// let observations = [1.5, 2.0, 3.25, 4.875, 5.5] /// let doubledObservations = observations.doublingAll() /// // doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0] /// /// let integers = 0..<8 /// let doubledIntegers = integers.doublingAll() /// // doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14] /// /// Conforming to the Numeric Protocol /// ================================== /// /// To add `Numeric` protocol conformance to your own custom type, implement /// the required initializer and operators, and provide a `magnitude` property /// using a type that can represent the magnitude of any value of your custom /// type. public protocol Numeric: AdditiveArithmetic, ExpressibleByIntegerLiteral { /// Creates a new instance from the given integer, if it can be represented /// exactly. /// /// If the value passed as `source` is not representable exactly, the result /// is `nil`. In the following example, the constant `x` is successfully /// created from a value of `100`, while the attempt to initialize the /// constant `y` from `1_000` fails because the `Int8` type can represent /// `127` at maximum: /// /// let x = Int8(exactly: 100) /// // x == Optional(100) /// let y = Int8(exactly: 1_000) /// // y == nil /// /// - Parameter source: A value to convert to this type. init?<T: BinaryInteger>(exactly source: T) /// A type that can represent the absolute value of any possible value of the /// conforming type. associatedtype Magnitude: Comparable, Numeric /// The magnitude of this value. /// /// For any numeric value `x`, `x.magnitude` is the absolute value of `x`. /// You can use the `magnitude` property in operations that are simpler to /// implement in terms of unsigned values, such as printing the value of an /// integer, which is just printing a '-' character in front of an absolute /// value. /// /// let x = -200 /// // x.magnitude == 200 /// /// The global `abs(_:)` function provides more familiar syntax when you need /// to find an absolute value. In addition, because `abs(_:)` always returns /// a value of the same type, even in a generic context, using the function /// instead of the `magnitude` property is encouraged. var magnitude: Magnitude { get } /// Multiplies two values and produces their product. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// 2 * 3 // 6 /// 100 * 21 // 2100 /// -10 * 15 // -150 /// 3.5 * 2.25 // 7.875 /// /// You cannot use `*` with arguments of different types. To multiply values /// of different types, convert one of the values to the other value's type. /// /// let x: Int8 = 21 /// let y: Int = 1000000 /// Int(x) * y // 21000000 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. static func *=(lhs: inout Self, rhs: Self) } /// A type that can represent both positive and negative values. /// /// The `SignedNumeric` protocol extends the operations defined by the /// `Numeric` protocol to include a value's additive inverse. /// /// Conforming to the SignedNumeric Protocol /// ======================================== /// /// Because the `SignedNumeric` protocol provides default implementations of /// both of its required methods, you don't need to do anything beyond /// declaring conformance to the protocol and ensuring that the values of your /// type support negation. To customize your type's implementation, provide /// your own mutating `negate()` method. /// /// When the additive inverse of a value is unrepresentable in a conforming /// type, the operation should either trap or return an exceptional value. For /// example, using the negation operator (prefix `-`) with `Int.min` results in /// a runtime error. /// /// let x = Int.min /// let y = -x /// // Overflow error public protocol SignedNumeric: Numeric { /// Returns the additive inverse of the specified value. /// /// The negation operator (prefix `-`) returns the additive inverse of its /// argument. /// /// let x = 21 /// let y = -x /// // y == -21 /// /// The resulting value must be representable in the same type as the /// argument. In particular, negating a signed, fixed-width integer type's /// minimum results in a value that cannot be represented. /// /// let z = -Int8.min /// // Overflow error /// /// - Returns: The additive inverse of this value. static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The following example uses the `negate()` method to negate the value of /// an integer `x`: /// /// var x = 21 /// x.negate() /// // x == -21 /// /// The resulting value must be representable within the value's type. In /// particular, negating a signed, fixed-width integer type's minimum /// results in a value that cannot be represented. /// /// var y = Int8.min /// y.negate() /// // Overflow error mutating func negate() } extension SignedNumeric { /// Returns the additive inverse of the specified value. /// /// The negation operator (prefix `-`) returns the additive inverse of its /// argument. /// /// let x = 21 /// let y = -x /// // y == -21 /// /// The resulting value must be representable in the same type as the /// argument. In particular, negating a signed, fixed-width integer type's /// minimum results in a value that cannot be represented. /// /// let z = -Int8.min /// // Overflow error /// /// - Returns: The additive inverse of the argument. @_transparent public static prefix func - (_ operand: Self) -> Self { var result = operand result.negate() return result } /// Replaces this value with its additive inverse. /// /// The following example uses the `negate()` method to negate the value of /// an integer `x`: /// /// var x = 21 /// x.negate() /// // x == -21 /// /// The resulting value must be representable within the value's type. In /// particular, negating a signed, fixed-width integer type's minimum /// results in a value that cannot be represented. /// /// var y = Int8.min /// y.negate() /// // Overflow error @_transparent public mutating func negate() { self = 0 - self } } /// Returns the absolute value of the given number. /// /// The absolute value of `x` must be representable in the same type. In /// particular, the absolute value of a signed, fixed-width integer type's /// minimum cannot be represented. /// /// let x = Int8.min /// // x == -128 /// let y = abs(x) /// // Overflow error /// /// - Parameter x: A signed number. /// - Returns: The absolute value of `x`. @inlinable public func abs<T: SignedNumeric & Comparable>(_ x: T) -> T { if T.self == T.Magnitude.self { return unsafeBitCast(x.magnitude, to: T.self) } return x < (0 as T) ? -x : x } extension AdditiveArithmetic { /// Returns the given number unchanged. /// /// You can use the unary plus operator (`+`) to provide symmetry in your /// code for positive numbers when also using the unary minus operator. /// /// let x = -21 /// let y = +21 /// // x == -21 /// // y == 21 /// /// - Returns: The given argument without any changes. @_transparent public static prefix func + (x: Self) -> Self { return x } } //===----------------------------------------------------------------------===// //===--- BinaryInteger ----------------------------------------------------===// //===----------------------------------------------------------------------===// /// An integer type with a binary representation. /// /// The `BinaryInteger` protocol is the basis for all the integer types /// provided by the standard library. All of the standard library's integer /// types, such as `Int` and `UInt32`, conform to `BinaryInteger`. /// /// Converting Between Numeric Types /// ================================ /// /// You can create new instances of a type that conforms to the `BinaryInteger` /// protocol from a floating-point number or another binary integer of any /// type. The `BinaryInteger` protocol provides initializers for four /// different kinds of conversion. /// /// Range-Checked Conversion /// ------------------------ /// /// You use the default `init(_:)` initializer to create a new instance when /// you're sure that the value passed is representable in the new type. For /// example, an instance of `Int16` can represent the value `500`, so the /// first conversion in the code sample below succeeds. That same value is too /// large to represent as an `Int8` instance, so the second conversion fails, /// triggering a runtime error. /// /// let x: Int = 500 /// let y = Int16(x) /// // y == 500 /// /// let z = Int8(x) /// // Error: Not enough bits to represent... /// /// When you create a binary integer from a floating-point value using the /// default initializer, the value is rounded toward zero before the range is /// checked. In the following example, the value `127.75` is rounded to `127`, /// which is representable by the `Int8` type. `128.25` is rounded to `128`, /// which is not representable as an `Int8` instance, triggering a runtime /// error. /// /// let e = Int8(127.75) /// // e == 127 /// /// let f = Int8(128.25) /// // Error: Double value cannot be converted... /// /// /// Exact Conversion /// ---------------- /// /// Use the `init?(exactly:)` initializer to create a new instance after /// checking whether the passed value is representable. Instead of trapping on /// out-of-range values, using the failable `init?(exactly:)` /// initializer results in `nil`. /// /// let x = Int16(exactly: 500) /// // x == Optional(500) /// /// let y = Int8(exactly: 500) /// // y == nil /// /// When converting floating-point values, the `init?(exactly:)` initializer /// checks both that the passed value has no fractional part and that the /// value is representable in the resulting type. /// /// let e = Int8(exactly: 23.0) // integral value, representable /// // e == Optional(23) /// /// let f = Int8(exactly: 23.75) // fractional value, representable /// // f == nil /// /// let g = Int8(exactly: 500.0) // integral value, nonrepresentable /// // g == nil /// /// Clamping Conversion /// ------------------- /// /// Use the `init(clamping:)` initializer to create a new instance of a binary /// integer type where out-of-range values are clamped to the representable /// range of the type. For a type `T`, the resulting value is in the range /// `T.min...T.max`. /// /// let x = Int16(clamping: 500) /// // x == 500 /// /// let y = Int8(clamping: 500) /// // y == 127 /// /// let z = UInt8(clamping: -500) /// // z == 0 /// /// Bit Pattern Conversion /// ---------------------- /// /// Use the `init(truncatingIfNeeded:)` initializer to create a new instance /// with the same bit pattern as the passed value, extending or truncating the /// value's representation as necessary. Note that the value may not be /// preserved, particularly when converting between signed to unsigned integer /// types or when the destination type has a smaller bit width than the source /// type. The following example shows how extending and truncating work for /// nonnegative integers: /// /// let q: Int16 = 850 /// // q == 0b00000011_01010010 /// /// let r = Int8(truncatingIfNeeded: q) // truncate 'q' to fit in 8 bits /// // r == 82 /// // == 0b01010010 /// /// let s = Int16(truncatingIfNeeded: r) // extend 'r' to fill 16 bits /// // s == 82 /// // == 0b00000000_01010010 /// /// Any padding is performed by *sign-extending* the passed value. When /// nonnegative integers are extended, the result is padded with zeroes. When /// negative integers are extended, the result is padded with ones. This /// example shows several extending conversions of a negative value---note /// that negative values are sign-extended even when converting to an unsigned /// type. /// /// let t: Int8 = -100 /// // t == -100 /// // t's binary representation == 0b10011100 /// /// let u = UInt8(truncatingIfNeeded: t) /// // u == 156 /// // u's binary representation == 0b10011100 /// /// let v = Int16(truncatingIfNeeded: t) /// // v == -100 /// // v's binary representation == 0b11111111_10011100 /// /// let w = UInt16(truncatingIfNeeded: t) /// // w == 65436 /// // w's binary representation == 0b11111111_10011100 /// /// /// Comparing Across Integer Types /// ============================== /// /// You can use relational operators, such as the less-than and equal-to /// operators (`<` and `==`), to compare instances of different binary integer /// types. The following example compares instances of the `Int`, `UInt`, and /// `UInt8` types: /// /// let x: Int = -23 /// let y: UInt = 1_000 /// let z: UInt8 = 23 /// /// if x < y { /// print("\(x) is less than \(y).") /// } /// // Prints "-23 is less than 1000." /// /// if z > x { /// print("\(z) is greater than \(x).") /// } /// // Prints "23 is greater than -23." public protocol BinaryInteger : Hashable, Numeric, CustomStringConvertible, Strideable where Magnitude: BinaryInteger, Magnitude.Magnitude == Magnitude { /// A Boolean value indicating whether this type is a signed integer type. /// /// *Signed* integer types can represent both positive and negative values. /// *Unsigned* integer types can represent only nonnegative values. static var isSigned: Bool { get } /// Creates an integer from the given floating-point value, if it can be /// represented exactly. /// /// If the value passed as `source` is not representable exactly, the result /// is `nil`. In the following example, the constant `x` is successfully /// created from a value of `21.0`, while the attempt to initialize the /// constant `y` from `21.5` fails: /// /// let x = Int(exactly: 21.0) /// // x == Optional(21) /// let y = Int(exactly: 21.5) /// // y == nil /// /// - Parameter source: A floating-point value to convert to an integer. init?<T: BinaryFloatingPoint>(exactly source: T) /// Creates an integer from the given floating-point value, rounding toward /// zero. /// /// Any fractional part of the value passed as `source` is removed, rounding /// the value toward zero. /// /// let x = Int(21.5) /// // x == 21 /// let y = Int(-21.5) /// // y == -21 /// /// If `source` is outside the bounds of this type after rounding toward /// zero, a runtime error may occur. /// /// let z = UInt(-21.5) /// // Error: ...the result would be less than UInt.min /// /// - Parameter source: A floating-point value to convert to an integer. /// `source` must be representable in this type after rounding toward /// zero. init<T: BinaryFloatingPoint>(_ source: T) /// Creates a new instance from the given integer. /// /// If the value passed as `source` is not representable in this type, a /// runtime error may occur. /// /// let x = -500 as Int /// let y = Int32(x) /// // y == -500 /// /// // -500 is not representable as a 'UInt32' instance /// let z = UInt32(x) /// // Error /// /// - Parameter source: An integer to convert. `source` must be representable /// in this type. init<T: BinaryInteger>(_ source: T) /// Creates a new instance from the bit pattern of the given instance by /// sign-extending or truncating to fit this type. /// /// When the bit width of `T` (the type of `source`) is equal to or greater /// than this type's bit width, the result is the truncated /// least-significant bits of `source`. For example, when converting a /// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are /// used. /// /// let p: Int16 = -500 /// // 'p' has a binary representation of 11111110_00001100 /// let q = Int8(truncatingIfNeeded: p) /// // q == 12 /// // 'q' has a binary representation of 00001100 /// /// When the bit width of `T` is less than this type's bit width, the result /// is *sign-extended* to fill the remaining bits. That is, if `source` is /// negative, the result is padded with ones; otherwise, the result is /// padded with zeros. /// /// let u: Int8 = 21 /// // 'u' has a binary representation of 00010101 /// let v = Int16(truncatingIfNeeded: u) /// // v == 21 /// // 'v' has a binary representation of 00000000_00010101 /// /// let w: Int8 = -21 /// // 'w' has a binary representation of 11101011 /// let x = Int16(truncatingIfNeeded: w) /// // x == -21 /// // 'x' has a binary representation of 11111111_11101011 /// let y = UInt16(truncatingIfNeeded: w) /// // y == 65515 /// // 'y' has a binary representation of 11111111_11101011 /// /// - Parameter source: An integer to convert to this type. init<T: BinaryInteger>(truncatingIfNeeded source: T) /// Creates a new instance with the representable value that's closest to the /// given integer. /// /// If the value passed as `source` is greater than the maximum representable /// value in this type, the result is the type's `max` value. If `source` is /// less than the smallest representable value in this type, the result is /// the type's `min` value. /// /// In this example, `x` is initialized as an `Int8` instance by clamping /// `500` to the range `-128...127`, and `y` is initialized as a `UInt` /// instance by clamping `-500` to the range `0...UInt.max`. /// /// let x = Int8(clamping: 500) /// // x == 127 /// // x == Int8.max /// /// let y = UInt(clamping: -500) /// // y == 0 /// /// - Parameter source: An integer to convert to this type. init<T: BinaryInteger>(clamping source: T) /// A type that represents the words of a binary integer. /// /// The `Words` type must conform to the `RandomAccessCollection` protocol /// with an `Element` type of `UInt` and `Index` type of `Int`. associatedtype Words: RandomAccessCollection where Words.Element == UInt, Words.Index == Int /// A collection containing the words of this value's binary /// representation, in order from the least significant to most significant. /// /// Negative values are returned in two's complement representation, /// regardless of the type's underlying implementation. var words: Words { get } /// The least significant word in this value's binary representation. var _lowWord: UInt { get } /// The number of bits in the current binary representation of this value. /// /// This property is a constant for instances of fixed-width integer /// types. var bitWidth: Int { get } /// Returns the integer binary logarithm of this value. /// /// If the value is negative or zero, a runtime error will occur. func _binaryLogarithm() -> Int /// The number of trailing zeros in this value's binary representation. /// /// For example, in a fixed-width integer type with a `bitWidth` value of 8, /// the number -8 has three trailing zeros. /// /// let x = Int8(bitPattern: 0b1111_1000) /// // x == -8 /// // x.trailingZeroBitCount == 3 /// /// If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`. var trailingZeroBitCount: Int { get } /// Returns the quotient of dividing the first value by the second. /// /// For integer types, any remainder of the division is discarded. /// /// let x = 21 / 5 /// // x == 4 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. `rhs` must not be zero. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable. /// /// For integer types, any remainder of the division is discarded. /// /// var x = 21 /// x /= 5 /// // x == 4 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. `rhs` must not be zero. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of dividing the first value by the second. /// /// The result of the remainder operator (`%`) has the same sign as `lhs` and /// has a magnitude less than `rhs.magnitude`. /// /// let x = 22 % 5 /// // x == 2 /// let y = 22 % -5 /// // y == 2 /// let z = -22 % -5 /// // z == -2 /// /// For any two integers `a` and `b`, their quotient `q`, and their remainder /// `r`, `a == b * q + r`. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. `rhs` must not be zero. static func %(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the remainder in the /// left-hand-side variable. /// /// The result has the same sign as `lhs` and has a magnitude less than /// `rhs.magnitude`. /// /// var x = 22 /// x %= 5 /// // x == 2 /// /// var y = 22 /// y %= -5 /// // y == 2 /// /// var z = -22 /// z %= -5 /// // z == -2 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. `rhs` must not be zero. static func %=(lhs: inout Self, rhs: Self) /// Adds two values and produces their sum. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// 1 + 2 // 3 /// -10 + 15 // 5 /// -15 + -5 // -20 /// 21.5 + 3.25 // 24.75 /// /// You cannot use `+` with arguments of different types. To add values of /// different types, convert one of the values to the other value's type. /// /// let x: Int8 = 21 /// let y: Int = 1000000 /// Int(x) + y // 1000021 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Subtracts one value from another and produces their difference. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// 8 - 3 // 5 /// -10 - 5 // -15 /// 100 - -5 // 105 /// 10.5 - 100.0 // -89.5 /// /// You cannot use `-` with arguments of different types. To subtract values /// of different types, convert one of the values to the other value's type. /// /// let x: UInt8 = 21 /// let y: UInt = 1000000 /// y - UInt(x) // 999979 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in the /// left-hand-side variable. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// 2 * 3 // 6 /// 100 * 21 // 2100 /// -10 * 15 // -150 /// 3.5 * 2.25 // 7.875 /// /// You cannot use `*` with arguments of different types. To multiply values /// of different types, convert one of the values to the other value's type. /// /// let x: Int8 = 21 /// let y: Int = 1000000 /// Int(x) * y // 21000000 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the inverse of the bits set in the argument. /// /// The bitwise NOT operator (`~`) is a prefix operator that returns a value /// in which all the bits of its argument are flipped: Bits that are `1` in /// the argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on 0 returns a value with every bit /// set to `1`. /// /// let allOnes = ~UInt8.min // 0b11111111 /// /// - Complexity: O(1). static prefix func ~ (_ x: Self) -> Self /// Returns the result of performing a bitwise AND operation on the two given /// values. /// /// A bitwise AND operation results in a value that has each bit set to `1` /// where *both* of its arguments have that bit set to `1`. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// // z == 4 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func &(lhs: Self, rhs: Self) -> Self /// Stores the result of performing a bitwise AND operation on the two given /// values in the left-hand-side variable. /// /// A bitwise AND operation results in a value that has each bit set to `1` /// where *both* of its arguments have that bit set to `1`. For example: /// /// var x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// x &= y // 0b00000100 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func &=(lhs: inout Self, rhs: Self) /// Returns the result of performing a bitwise OR operation on the two given /// values. /// /// A bitwise OR operation results in a value that has each bit set to `1` /// where *one or both* of its arguments have that bit set to `1`. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// // z == 15 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func |(lhs: Self, rhs: Self) -> Self /// Stores the result of performing a bitwise OR operation on the two given /// values in the left-hand-side variable. /// /// A bitwise OR operation results in a value that has each bit set to `1` /// where *one or both* of its arguments have that bit set to `1`. For /// example: /// /// var x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// x |= y // 0b00001111 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func |=(lhs: inout Self, rhs: Self) /// Returns the result of performing a bitwise XOR operation on the two given /// values. /// /// A bitwise XOR operation, also known as an exclusive OR operation, results /// in a value that has each bit set to `1` where *one or the other but not /// both* of its arguments had that bit set to `1`. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// // z == 11 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func ^(lhs: Self, rhs: Self) -> Self /// Stores the result of performing a bitwise XOR operation on the two given /// values in the left-hand-side variable. /// /// A bitwise XOR operation, also known as an exclusive OR operation, results /// in a value that has each bit set to `1` where *one or the other but not /// both* of its arguments had that bit set to `1`. For example: /// /// var x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// x ^= y // 0b00001011 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. static func ^=(lhs: inout Self, rhs: Self) /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right. /// /// The `>>` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a left shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*. An overshift results in `-1` for a /// negative value of `lhs` or `0` for a nonnegative value. /// - Using any other value for `rhs` performs a right shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted right by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x >> 2 /// // y == 7 // 0b00000111 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x >> 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a left shift /// using `abs(rhs)`. /// /// let a = x >> -3 /// // a == 240 // 0b11110000 /// let b = x << 3 /// // b == 240 // 0b11110000 /// /// Right shift operations on negative values "fill in" the high bits with /// ones instead of zeros. /// /// let q: Int8 = -30 // 0b11100010 /// let r = q >> 2 /// // r == -8 // 0b11111000 /// /// let s = q >> 11 /// // s == -1 // 0b11111111 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self /// Stores the result of shifting a value's binary representation the /// specified number of digits to the right in the left-hand-side variable. /// /// The `>>=` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a left shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*. An overshift results in `-1` for a /// negative value of `lhs` or `0` for a nonnegative value. /// - Using any other value for `rhs` performs a right shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted right by two bits. /// /// var x: UInt8 = 30 // 0b00011110 /// x >>= 2 /// // x == 7 // 0b00000111 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// var y: UInt8 = 30 // 0b00011110 /// y >>= 11 /// // y == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a left shift /// using `abs(rhs)`. /// /// var a: UInt8 = 30 // 0b00011110 /// a >>= -3 /// // a == 240 // 0b11110000 /// /// var b: UInt8 = 30 // 0b00011110 /// b <<= 3 /// // b == 240 // 0b11110000 /// /// Right shift operations on negative values "fill in" the high bits with /// ones instead of zeros. /// /// var q: Int8 = -30 // 0b11100010 /// q >>= 2 /// // q == -8 // 0b11111000 /// /// var r: Int8 = -30 // 0b11100010 /// r >>= 11 /// // r == -1 // 0b11111111 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. static func >>= <RHS: BinaryInteger>(lhs: inout Self, rhs: RHS) /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left. /// /// The `<<` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a right shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*, resulting in zero. /// - Using any other value for `rhs` performs a left shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted left by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x << 2 /// // y == 120 // 0b01111000 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x << 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a right shift /// with `abs(rhs)`. /// /// let a = x << -3 /// // a == 3 // 0b00000011 /// let b = x >> 3 /// // b == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self /// Stores the result of shifting a value's binary representation the /// specified number of digits to the left in the left-hand-side variable. /// /// The `<<` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a right shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*, resulting in zero. /// - Using any other value for `rhs` performs a left shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted left by two bits. /// /// var x: UInt8 = 30 // 0b00011110 /// x <<= 2 /// // x == 120 // 0b01111000 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// var y: UInt8 = 30 // 0b00011110 /// y <<= 11 /// // y == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a right shift /// with `abs(rhs)`. /// /// var a: UInt8 = 30 // 0b00011110 /// a <<= -3 /// // a == 3 // 0b00000011 /// /// var b: UInt8 = 30 // 0b00011110 /// b >>= 3 /// // b == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. static func <<=<RHS: BinaryInteger>(lhs: inout Self, rhs: RHS) /// Returns the quotient and remainder of this value divided by the given /// value. /// /// Use this method to calculate the quotient and remainder of a division at /// the same time. /// /// let x = 1_000_000 /// let (q, r) = x.quotientAndRemainder(dividingBy: 933) /// // q == 1071 /// // r == 757 /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the quotient and remainder of this value /// divided by `rhs`. The remainder has the same sign as `lhs`. func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self) /// Returns `true` if this value is a multiple of the given value, and `false` /// otherwise. /// /// For two integers *a* and *b*, *a* is a multiple of *b* if there exists a /// third integer *q* such that _a = q*b_. For example, *6* is a multiple of /// *3* because _6 = 2*3_. Zero is a multiple of everything because _0 = 0*x_ /// for any integer *x*. /// /// Two edge cases are worth particular attention: /// - `x.isMultiple(of: 0)` is `true` if `x` is zero and `false` otherwise. /// - `T.min.isMultiple(of: -1)` is `true` for signed integer `T`, even /// though the quotient `T.min / -1` isn't representable in type `T`. /// /// - Parameter other: The value to test. func isMultiple(of other: Self) -> Bool /// Returns `-1` if this value is negative and `1` if it's positive; /// otherwise, `0`. /// /// - Returns: The sign of this number, expressed as an integer of the same /// type. func signum() -> Self } extension BinaryInteger { /// Creates a new value equal to zero. @_transparent public init() { self = 0 } /// Returns `-1` if this value is negative and `1` if it's positive; /// otherwise, `0`. /// /// - Returns: The sign of this number, expressed as an integer of the same /// type. @inlinable public func signum() -> Self { return (self > (0 as Self) ? 1 : 0) - (self < (0 as Self) ? 1 : 0) } @_transparent public var _lowWord: UInt { var it = words.makeIterator() return it.next() ?? 0 } @inlinable public func _binaryLogarithm() -> Int { _precondition(self > (0 as Self)) var (quotient, remainder) = (bitWidth &- 1).quotientAndRemainder(dividingBy: UInt.bitWidth) remainder = remainder &+ 1 var word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder)) // If, internally, a variable-width binary integer uses digits of greater // bit width than that of Magnitude.Words.Element (i.e., UInt), then it is // possible that `word` could be zero. Additionally, a signed variable-width // binary integer may have a leading word that is zero to store a clear sign // bit. while word == 0 { quotient = quotient &- 1 remainder = remainder &+ UInt.bitWidth word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder)) } // Note that the order of operations below is important to guarantee that // we won't overflow. return UInt.bitWidth &* quotient &+ (UInt.bitWidth &- (word.leadingZeroBitCount &+ 1)) } /// Returns the quotient and remainder of this value divided by the given /// value. /// /// Use this method to calculate the quotient and remainder of a division at /// the same time. /// /// let x = 1_000_000 /// let (q, r) = x.quotientAndRemainder(dividingBy: 933) /// // q == 1071 /// // r == 757 /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the quotient and remainder of this value /// divided by `rhs`. @inlinable public func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self) { return (self / rhs, self % rhs) } @inlinable public func isMultiple(of other: Self) -> Bool { // Nothing but zero is a multiple of zero. if other == 0 { return self == 0 } // Do the test in terms of magnitude, which guarantees there are no other // edge cases. If we write this as `self % other` instead, it could trap // for types that are not symmetric around zero. return self.magnitude % other.magnitude == 0 } //===----------------------------------------------------------------------===// //===--- Homogeneous ------------------------------------------------------===// //===----------------------------------------------------------------------===// /// Returns the result of performing a bitwise AND operation on the two given /// values. /// /// A bitwise AND operation results in a value that has each bit set to `1` /// where *both* of its arguments have that bit set to `1`. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// // z == 4 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. @_transparent public static func & (lhs: Self, rhs: Self) -> Self { var lhs = lhs lhs &= rhs return lhs } /// Returns the result of performing a bitwise OR operation on the two given /// values. /// /// A bitwise OR operation results in a value that has each bit set to `1` /// where *one or both* of its arguments have that bit set to `1`. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// // z == 15 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. @_transparent public static func | (lhs: Self, rhs: Self) -> Self { var lhs = lhs lhs |= rhs return lhs } /// Returns the result of performing a bitwise XOR operation on the two given /// values. /// /// A bitwise XOR operation, also known as an exclusive OR operation, results /// in a value that has each bit set to `1` where *one or the other but not /// both* of its arguments had that bit set to `1`. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// // z == 11 /// /// - Parameters: /// - lhs: An integer value. /// - rhs: Another integer value. @_transparent public static func ^ (lhs: Self, rhs: Self) -> Self { var lhs = lhs lhs ^= rhs return lhs } //===----------------------------------------------------------------------===// //===--- Heterogeneous non-masking shift in terms of shift-assignment -----===// //===----------------------------------------------------------------------===// /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right. /// /// The `>>` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a left shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*. An overshift results in `-1` for a /// negative value of `lhs` or `0` for a nonnegative value. /// - Using any other value for `rhs` performs a right shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted right by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x >> 2 /// // y == 7 // 0b00000111 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x >> 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a left shift /// using `abs(rhs)`. /// /// let a = x >> -3 /// // a == 240 // 0b11110000 /// let b = x << 3 /// // b == 240 // 0b11110000 /// /// Right shift operations on negative values "fill in" the high bits with /// ones instead of zeros. /// /// let q: Int8 = -30 // 0b11100010 /// let r = q >> 2 /// // r == -8 // 0b11111000 /// /// let s = q >> 11 /// // s == -1 // 0b11111111 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self { var r = lhs r >>= rhs return r } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left. /// /// The `<<` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a right shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*, resulting in zero. /// - Using any other value for `rhs` performs a left shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted left by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x << 2 /// // y == 120 // 0b01111000 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x << 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a right shift /// with `abs(rhs)`. /// /// let a = x << -3 /// // a == 3 // 0b00000011 /// let b = x >> 3 /// // b == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self { var r = lhs r <<= rhs return r } } //===----------------------------------------------------------------------===// //===--- CustomStringConvertible conformance ------------------------------===// //===----------------------------------------------------------------------===// extension BinaryInteger { internal func _description(radix: Int, uppercase: Bool) -> String { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") if bitWidth <= 64 { let radix_ = Int64(radix) return Self.isSigned ? _int64ToString( Int64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase) : _uint64ToString( UInt64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase) } if self == (0 as Self) { return "0" } // Bit shifting can be faster than division when `radix` is a power of two // (although not necessarily the case for builtin types). let isRadixPowerOfTwo = radix.nonzeroBitCount == 1 let radix_ = Magnitude(radix) func _quotientAndRemainder(_ value: Magnitude) -> (Magnitude, Magnitude) { return isRadixPowerOfTwo ? (value >> radix.trailingZeroBitCount, value & (radix_ - 1)) : value.quotientAndRemainder(dividingBy: radix_) } let hasLetters = radix > 10 func _ascii(_ digit: UInt8) -> UInt8 { let base: UInt8 if !hasLetters || digit < 10 { base = UInt8(("0" as Unicode.Scalar).value) } else if uppercase { base = UInt8(("A" as Unicode.Scalar).value) &- 10 } else { base = UInt8(("a" as Unicode.Scalar).value) &- 10 } return base &+ digit } let isNegative = Self.isSigned && self < (0 as Self) var value = magnitude // TODO(FIXME JIRA): All current stdlib types fit in small. Use a stack // buffer instead of an array on the heap. var result: [UInt8] = [] while value != 0 { let (quotient, remainder) = _quotientAndRemainder(value) result.append(_ascii(UInt8(truncatingIfNeeded: remainder))) value = quotient } if isNegative { result.append(UInt8(("-" as Unicode.Scalar).value)) } result.reverse() return result.withUnsafeBufferPointer { return String._fromASCII($0) } } /// A textual representation of this value. @_semantics("binaryInteger.description") public var description: String { return _description(radix: 10, uppercase: false) } } //===----------------------------------------------------------------------===// //===--- Strideable conformance -------------------------------------------===// //===----------------------------------------------------------------------===// extension BinaryInteger { /// Returns the distance from this value to the given value, expressed as a /// stride. /// /// For two values `x` and `y`, and a distance `n = x.distance(to: y)`, /// `x.advanced(by: n) == y`. /// /// - Parameter other: The value to calculate the distance to. /// - Returns: The distance from this value to `other`. @inlinable @inline(__always) public func distance(to other: Self) -> Int { if !Self.isSigned { if self > other { if let result = Int(exactly: self - other) { return -result } } else { if let result = Int(exactly: other - self) { return result } } } else { let isNegative = self < (0 as Self) if isNegative == (other < (0 as Self)) { if let result = Int(exactly: other - self) { return result } } else { if let result = Int(exactly: self.magnitude + other.magnitude) { return isNegative ? result : -result } } } _preconditionFailure("Distance is not representable in Int") } /// Returns a value that is offset the specified distance from this value. /// /// Use the `advanced(by:)` method in generic code to offset a value by a /// specified distance. If you're working directly with numeric values, use /// the addition operator (`+`) instead of this method. /// /// For a value `x`, a distance `n`, and a value `y = x.advanced(by: n)`, /// `x.distance(to: y) == n`. /// /// - Parameter n: The distance to advance this value. /// - Returns: A value that is offset from this value by `n`. @inlinable @inline(__always) public func advanced(by n: Int) -> Self { if !Self.isSigned { return n < (0 as Int) ? self - Self(-n) : self + Self(n) } if (self < (0 as Self)) == (n < (0 as Self)) { return self + Self(n) } return self.magnitude < n.magnitude ? Self(Int(self) + n) : self + Self(n) } } //===----------------------------------------------------------------------===// //===--- Heterogeneous comparison -----------------------------------------===// //===----------------------------------------------------------------------===// extension BinaryInteger { /// Returns a Boolean value indicating whether the two given values are /// equal. /// /// You can check the equality of instances of any `BinaryInteger` types /// using the equal-to operator (`==`). For example, you can test whether /// the first `UInt8` value in a string's UTF-8 encoding is equal to the /// first `UInt32` value in its Unicode scalar view: /// /// let gameName = "Red Light, Green Light" /// if let firstUTF8 = gameName.utf8.first, /// let firstScalar = gameName.unicodeScalars.first?.value { /// print("First code values are equal: \(firstUTF8 == firstScalar)") /// } /// // Prints "First code values are equal: true" /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func == < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Bool { let lhsNegative = Self.isSigned && lhs < (0 as Self) let rhsNegative = Other.isSigned && rhs < (0 as Other) if lhsNegative != rhsNegative { return false } // Here we know the values are of the same sign. // // There are a few possible scenarios from here: // // 1. Both values are negative // - If one value is strictly wider than the other, then it is safe to // convert to the wider type. // - If the values are of the same width, it does not matter which type we // choose to convert to as the values are already negative, and thus // include the sign bit if two's complement representation already. // 2. Both values are non-negative // - If one value is strictly wider than the other, then it is safe to // convert to the wider type. // - If the values are of the same width, than signedness matters, as not // unsigned types are 'wider' in a sense they don't need to 'waste' the // sign bit. Therefore it is safe to convert to the unsigned type. if lhs.bitWidth < rhs.bitWidth { return Other(truncatingIfNeeded: lhs) == rhs } if lhs.bitWidth > rhs.bitWidth { return lhs == Self(truncatingIfNeeded: rhs) } if Self.isSigned { return Other(truncatingIfNeeded: lhs) == rhs } return lhs == Self(truncatingIfNeeded: rhs) } /// Returns a Boolean value indicating whether the two given values are not /// equal. /// /// You can check the inequality of instances of any `BinaryInteger` types /// using the not-equal-to operator (`!=`). For example, you can test /// whether the first `UInt8` value in a string's UTF-8 encoding is not /// equal to the first `UInt32` value in its Unicode scalar view: /// /// let gameName = "Red Light, Green Light" /// if let firstUTF8 = gameName.utf8.first, /// let firstScalar = gameName.unicodeScalars.first?.value { /// print("First code values are different: \(firstUTF8 != firstScalar)") /// } /// // Prints "First code values are different: false" /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func != < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Bool { return !(lhs == rhs) } /// Returns a Boolean value indicating whether the value of the first /// argument is less than that of the second argument. /// /// You can compare instances of any `BinaryInteger` types using the /// less-than operator (`<`), even if the two instances are of different /// types. /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func < <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool { let lhsNegative = Self.isSigned && lhs < (0 as Self) let rhsNegative = Other.isSigned && rhs < (0 as Other) if lhsNegative != rhsNegative { return lhsNegative } if lhs == (0 as Self) && rhs == (0 as Other) { return false } // if we get here, lhs and rhs have the same sign. If they're negative, // then Self and Other are both signed types, and one of them can represent // values of the other type. Otherwise, lhs and rhs are positive, and one // of Self, Other may be signed and the other unsigned. let rhsAsSelf = Self(truncatingIfNeeded: rhs) let rhsAsSelfNegative = rhsAsSelf < (0 as Self) // Can we round-trip rhs through Other? if Other(truncatingIfNeeded: rhsAsSelf) == rhs && // This additional check covers the `Int8.max < (128 as UInt8)` case. // Since the types are of the same width, init(truncatingIfNeeded:) // will result in a simple bitcast, so that rhsAsSelf would be -128, and // `lhs < rhsAsSelf` will return false. // We basically guard against that bitcast by requiring rhs and rhsAsSelf // to be the same sign. rhsNegative == rhsAsSelfNegative { return lhs < rhsAsSelf } return Other(truncatingIfNeeded: lhs) < rhs } /// Returns a Boolean value indicating whether the value of the first /// argument is less than or equal to that of the second argument. /// /// You can compare instances of any `BinaryInteger` types using the /// less-than-or-equal-to operator (`<=`), even if the two instances are of /// different types. /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func <= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool { return !(rhs < lhs) } /// Returns a Boolean value indicating whether the value of the first /// argument is greater than or equal to that of the second argument. /// /// You can compare instances of any `BinaryInteger` types using the /// greater-than-or-equal-to operator (`>=`), even if the two instances are /// of different types. /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func >= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool { return !(lhs < rhs) } /// Returns a Boolean value indicating whether the value of the first /// argument is greater than that of the second argument. /// /// You can compare instances of any `BinaryInteger` types using the /// greater-than operator (`>`), even if the two instances are of different /// types. /// /// - Parameters: /// - lhs: An integer to compare. /// - rhs: Another integer to compare. @_transparent public static func > <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool { return rhs < lhs } } //===----------------------------------------------------------------------===// //===--- Ambiguity breakers -----------------------------------------------===// // // These two versions of the operators are not ordered with respect to one // another, but the compiler choses the second one, and that results in infinite // recursion. // // <T: Comparable>(T, T) -> Bool // <T: BinaryInteger, U: BinaryInteger>(T, U) -> Bool // // so we define: // // <T: BinaryInteger>(T, T) -> Bool // //===----------------------------------------------------------------------===// extension BinaryInteger { @_transparent public static func != (lhs: Self, rhs: Self) -> Bool { return !(lhs == rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return !(rhs < lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return !(lhs < rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs < lhs } } //===----------------------------------------------------------------------===// //===--- FixedWidthInteger ------------------------------------------------===// //===----------------------------------------------------------------------===// /// An integer type that uses a fixed size for every instance. /// /// The `FixedWidthInteger` protocol adds binary bitwise operations, bit /// shifts, and overflow handling to the operations supported by the /// `BinaryInteger` protocol. /// /// Use the `FixedWidthInteger` protocol as a constraint or extension point /// when writing operations that depend on bit shifting, performing bitwise /// operations, catching overflows, or having access to the maximum or minimum /// representable value of a type. For example, the following code provides a /// `binaryString` property on every fixed-width integer that represents the /// number's binary representation, split into 8-bit chunks. /// /// extension FixedWidthInteger { /// var binaryString: String { /// var result: [String] = [] /// for i in 0..<(Self.bitWidth / 8) { /// let byte = UInt8(truncatingIfNeeded: self >> (i * 8)) /// let byteString = String(byte, radix: 2) /// let padding = String(repeating: "0", /// count: 8 - byteString.count) /// result.append(padding + byteString) /// } /// return "0b" + result.reversed().joined(separator: "_") /// } /// } /// /// print(Int16.max.binaryString) /// // Prints "0b01111111_11111111" /// print((101 as UInt8).binaryString) /// // Prints "0b11001001" /// /// The `binaryString` implementation uses the static `bitWidth` property and /// the right shift operator (`>>`), both of which are available to any type /// that conforms to the `FixedWidthInteger` protocol. /// /// The next example declares a generic `squared` function, which accepts an /// instance `x` of any fixed-width integer type. The function uses the /// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and /// check whether the result is too large to represent in the same type. /// /// func squared<T: FixedWidthInteger>(_ x: T) -> T? { /// let (result, overflow) = x.multipliedReportingOverflow(by: x) /// if overflow { /// return nil /// } /// return result /// } /// /// let (x, y): (Int8, Int8) = (9, 123) /// print(squared(x)) /// // Prints "Optional(81)" /// print(squared(y)) /// // Prints "nil" /// /// Conforming to the FixedWidthInteger Protocol /// ============================================ /// /// To make your own custom type conform to the `FixedWidthInteger` protocol, /// declare the required initializers, properties, and methods. The required /// methods that are suffixed with `ReportingOverflow` serve as the /// customization points for arithmetic operations. When you provide just those /// methods, the standard library provides default implementations for all /// other arithmetic methods and operators. public protocol FixedWidthInteger: BinaryInteger, LosslessStringConvertible where Magnitude: FixedWidthInteger & UnsignedInteger, Stride: FixedWidthInteger & SignedInteger { /// The number of bits used for the underlying binary representation of /// values of this type. /// /// An unsigned, fixed-width integer type can represent values from 0 through /// `(2 ** bitWidth) - 1`, where `**` is exponentiation. A signed, /// fixed-width integer type can represent values from /// `-(2 ** (bitWidth - 1))` through `(2 ** (bitWidth - 1)) - 1`. For example, /// the `Int8` type has a `bitWidth` value of 8 and can store any integer in /// the range `-128...127`. static var bitWidth: Int { get } /// The maximum representable integer in this type. /// /// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where /// `**` is exponentiation. For signed integer types, this value is /// `(2 ** (bitWidth - 1)) - 1`. static var max: Self { get } /// The minimum representable integer in this type. /// /// For unsigned integer types, this value is always `0`. For signed integer /// types, this value is `-(2 ** (bitWidth - 1))`, where `**` is /// exponentiation. static var min: Self { get } /// Returns the sum of this value and the given value, along with a Boolean /// value indicating whether overflow occurred in the operation. /// /// - Parameter rhs: The value to add to this value. /// - Returns: A tuple containing the result of the addition along with a /// Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// sum. If the `overflow` component is `true`, an overflow occurred and /// the `partialValue` component contains the truncated sum of this value /// and `rhs`. func addingReportingOverflow( _ rhs: Self ) -> (partialValue: Self, overflow: Bool) /// Returns the difference obtained by subtracting the given value from this /// value, along with a Boolean value indicating whether overflow occurred in /// the operation. /// /// - Parameter rhs: The value to subtract from this value. /// - Returns: A tuple containing the result of the subtraction along with a /// Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// difference. If the `overflow` component is `true`, an overflow occurred /// and the `partialValue` component contains the truncated result of `rhs` /// subtracted from this value. func subtractingReportingOverflow( _ rhs: Self ) -> (partialValue: Self, overflow: Bool) /// Returns the product of this value and the given value, along with a /// Boolean value indicating whether overflow occurred in the operation. /// /// - Parameter rhs: The value to multiply by this value. /// - Returns: A tuple containing the result of the multiplication along with /// a Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// product. If the `overflow` component is `true`, an overflow occurred and /// the `partialValue` component contains the truncated product of this /// value and `rhs`. func multipliedReportingOverflow( by rhs: Self ) -> (partialValue: Self, overflow: Bool) /// Returns the quotient obtained by dividing this value by the given value, /// along with a Boolean value indicating whether overflow occurred in the /// operation. /// /// Dividing by zero is not an error when using this method. For a value `x`, /// the result of `x.dividedReportingOverflow(by: 0)` is `(x, true)`. /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the result of the division along with a /// Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// quotient. If the `overflow` component is `true`, an overflow occurred /// and the `partialValue` component contains either the truncated quotient /// or, if the quotient is undefined, the dividend. func dividedReportingOverflow( by rhs: Self ) -> (partialValue: Self, overflow: Bool) /// Returns the remainder after dividing this value by the given value, along /// with a Boolean value indicating whether overflow occurred during division. /// /// Dividing by zero is not an error when using this method. For a value `x`, /// the result of `x.remainderReportingOverflow(dividingBy: 0)` is /// `(x, true)`. /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the result of the operation along with a /// Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// remainder. If the `overflow` component is `true`, an overflow occurred /// during division and the `partialValue` component contains either the /// entire remainder or, if the remainder is undefined, the dividend. func remainderReportingOverflow( dividingBy rhs: Self ) -> (partialValue: Self, overflow: Bool) /// Returns a tuple containing the high and low parts of the result of /// multiplying this value by the given value. /// /// Use this method to calculate the full result of a product that would /// otherwise overflow. Unlike traditional truncating multiplication, the /// `multipliedFullWidth(by:)` method returns a tuple containing both the /// `high` and `low` parts of the product of this value and `other`. The /// following example uses this method to multiply two `Int8` values that /// normally overflow when multiplied: /// /// let x: Int8 = 48 /// let y: Int8 = -40 /// let result = x.multipliedFullWidth(by: y) /// // result.high == -8 /// // result.low == 128 /// /// The product of `x` and `y` is `-1920`, which is too large to represent in /// an `Int8` instance. The `high` and `low` compnents of the `result` value /// represent `-1920` when concatenated to form a double-width integer; that /// is, using `result.high` as the high byte and `result.low` as the low byte /// of an `Int16` instance. /// /// let z = Int16(result.high) << 8 | Int16(result.low) /// // z == -1920 /// /// - Parameter other: The value to multiply this value by. /// - Returns: A tuple containing the high and low parts of the result of /// multiplying this value and `other`. func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude) /// Returns a tuple containing the quotient and remainder obtained by dividing /// the given value by this value. /// /// The resulting quotient must be representable within the bounds of the /// type. If the quotient is too large to represent in the type, a runtime /// error may occur. /// /// The following example divides a value that is too large to be represented /// using a single `Int` instance by another `Int` value. Because the quotient /// is representable as an `Int`, the division succeeds. /// /// // 'dividend' represents the value 0x506f70652053616e74612049494949 /// let dividend = (22640526660490081, 7959093232766896457 as UInt) /// let divisor = 2241543570477705381 /// /// let (quotient, remainder) = divisor.dividingFullWidth(dividend) /// // quotient == 186319822866995413 /// // remainder == 0 /// /// - Parameter dividend: A tuple containing the high and low parts of a /// double-width integer. /// - Returns: A tuple containing the quotient and remainder obtained by /// dividing `dividend` by this value. func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude)) -> (quotient: Self, remainder: Self) init(_truncatingBits bits: UInt) /// The number of bits equal to 1 in this value's binary representation. /// /// For example, in a fixed-width integer type with a `bitWidth` value of 8, /// the number *31* has five bits equal to *1*. /// /// let x: Int8 = 0b0001_1111 /// // x == 31 /// // x.nonzeroBitCount == 5 var nonzeroBitCount: Int { get } /// The number of leading zeros in this value's binary representation. /// /// For example, in a fixed-width integer type with a `bitWidth` value of 8, /// the number *31* has three leading zeros. /// /// let x: Int8 = 0b0001_1111 /// // x == 31 /// // x.leadingZeroBitCount == 3 /// /// If the value is zero, then `leadingZeroBitCount` is equal to `bitWidth`. var leadingZeroBitCount: Int { get } /// Creates an integer from its big-endian representation, changing the byte /// order if necessary. /// /// - Parameter value: A value to use as the big-endian representation of the /// new integer. init(bigEndian value: Self) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. /// /// - Parameter value: A value to use as the little-endian representation of /// the new integer. init(littleEndian value: Self) /// The big-endian representation of this integer. /// /// If necessary, the byte order of this value is reversed from the typical /// byte order of this integer type. On a big-endian platform, for any /// integer `x`, `x == x.bigEndian`. var bigEndian: Self { get } /// The little-endian representation of this integer. /// /// If necessary, the byte order of this value is reversed from the typical /// byte order of this integer type. On a little-endian platform, for any /// integer `x`, `x == x.littleEndian`. var littleEndian: Self { get } /// A representation of this integer with the byte order swapped. var byteSwapped: Self { get } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right, masking the shift amount to the /// type's bit width. /// /// Use the masking right shift operator (`&>>`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &>> 2 /// // y == 7 // 0b00000111 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &>> 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. static func &>>(lhs: Self, rhs: Self) -> Self /// Calculates the result of shifting a value's binary representation the /// specified number of digits to the right, masking the shift amount to the /// type's bit width, and stores the result in the left-hand-side variable. /// /// The `&>>=` operator performs a *masking shift*, where the value passed as /// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The /// shift is performed using this masked value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// var x: UInt8 = 30 // 0b00011110 /// x &>>= 2 /// // x == 7 // 0b00000111 /// /// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to /// `3`, and then uses that masked value as the number of bits to shift `lhs`. /// /// var y: UInt8 = 30 // 0b00011110 /// y &>>= 19 /// // y == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. static func &>>=(lhs: inout Self, rhs: Self) /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left, masking the shift amount to the /// type's bit width. /// /// Use the masking left shift operator (`&<<`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &<< 2 /// // y == 120 // 0b01111000 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &<< 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. static func &<<(lhs: Self, rhs: Self) -> Self /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left, masking the shift amount to the /// type's bit width, and stores the result in the left-hand-side variable. /// /// The `&<<=` operator performs a *masking shift*, where the value used as /// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The /// shift is performed using this masked value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// var x: UInt8 = 30 // 0b00011110 /// x &<<= 2 /// // x == 120 // 0b01111000 /// /// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to /// `3`, and then uses that masked value as the number of bits to shift `lhs`. /// /// var y: UInt8 = 30 // 0b00011110 /// y &<<= 19 /// // y == 240 // 0b11110000 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. static func &<<=(lhs: inout Self, rhs: Self) } extension FixedWidthInteger { /// The number of bits in the binary representation of this value. @inlinable public var bitWidth: Int { return Self.bitWidth } @inlinable public func _binaryLogarithm() -> Int { _precondition(self > (0 as Self)) return Self.bitWidth &- (leadingZeroBitCount &+ 1) } /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. /// /// - Parameter value: A value to use as the little-endian representation of /// the new integer. @inlinable public init(littleEndian value: Self) { #if _endian(little) self = value #else self = value.byteSwapped #endif } /// Creates an integer from its big-endian representation, changing the byte /// order if necessary. /// /// - Parameter value: A value to use as the big-endian representation of the /// new integer. @inlinable public init(bigEndian value: Self) { #if _endian(big) self = value #else self = value.byteSwapped #endif } /// The little-endian representation of this integer. /// /// If necessary, the byte order of this value is reversed from the typical /// byte order of this integer type. On a little-endian platform, for any /// integer `x`, `x == x.littleEndian`. @inlinable public var littleEndian: Self { #if _endian(little) return self #else return byteSwapped #endif } /// The big-endian representation of this integer. /// /// If necessary, the byte order of this value is reversed from the typical /// byte order of this integer type. On a big-endian platform, for any /// integer `x`, `x == x.bigEndian`. @inlinable public var bigEndian: Self { #if _endian(big) return self #else return byteSwapped #endif } // Default implementation of multipliedFullWidth. // // This implementation is mainly intended for [U]Int64 on 32b platforms. It // will not be especially efficient for other types that do not provide their // own implementation, but neither will it be catastrophically bad. It can // surely be improved on even for Int64, but that is mostly an optimization // problem; the basic algorithm here gives the compiler all the information // that it needs to generate efficient code. @_alwaysEmitIntoClient public func multipliedFullWidth(by other: Self) -> (high: Self, low: Magnitude) { // We define a utility function for splitting an integer into high and low // halves. Note that the low part is always unsigned, while the high part // matches the signedness of the input type. Both result types are the // full width of the original number; this may be surprising at first, but // there are two reasons for it: // // - we're going to use these as inputs to a multiplication operation, and // &* is quite a bit less verbose than `multipliedFullWidth`, so it makes // the rest of the code in this function somewhat easier to read. // // - there's no "half width type" that we can get at from this generic // context, so there's not really another option anyway. // // Fortunately, the compiler is pretty good about propagating the necessary // information to optimize away unnecessary arithmetic. func split<T: FixedWidthInteger>(_ x: T) -> (high: T, low: T.Magnitude) { let n = T.bitWidth/2 return (x >> n, T.Magnitude(truncatingIfNeeded: x) & ((1 &<< n) &- 1)) } // Split `self` and `other` into high and low parts, compute the partial // products carrying high words in as we go. We use the wrapping operators // and `truncatingIfNeeded` inits purely as an optimization hint to the // compiler; none of these operations will ever wrap due to the constraints // on the arithmetic. The bounds are documented before each line for signed // types. For unsigned types, the bounds are much more well known and // easier to derive, so I haven't bothered to document them here, but they // all boil down to the fact that a*b + c + d cannot overflow a double- // width result with unsigned a, b, c, d. let (x1, x0) = split(self) let (y1, y0) = split(other) // If B is 2^bitWidth/2, x0 and y0 are in 0 ... B-1, so their product is // in 0 ... B^2-2B+1. For further analysis, we'll need the fact that // the high word is in 0 ... B-2. let p00 = x0 &* y0 // x1 is in -B/2 ... B/2-1, so the product x1*y0 is in // -(B^2-B)/2 ... (B^2-3B+2)/2; after adding the high word of p00, the // result is in -(B^2-B)/2 ... (B^2-B-2)/2. let p01 = x1 &* Self(y0) &+ Self(split(p00).high) // The previous analysis holds for this product as well, and the sum is // in -(B^2-B)/2 ... (B^2-B)/2. let p10 = Self(x0) &* y1 &+ Self(split(p01).low) // No analysis is necessary for this term, because we know the product as // a whole cannot overflow, and this term is the final high word of the // product. let p11 = x1 &* y1 &+ split(p01).high &+ split(p10).high // Now we only need to assemble the low word of the product. return (p11, split(p10).low << (bitWidth/2) | split(p00).low) } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right, masking the shift amount to the /// type's bit width. /// /// Use the masking right shift operator (`&>>`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &>> 2 /// // y == 7 // 0b00000111 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &>> 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &>> (lhs: Self, rhs: Self) -> Self { var lhs = lhs lhs &>>= rhs return lhs } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right, masking the shift amount to the /// type's bit width. /// /// Use the masking right shift operator (`&>>`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &>> 2 /// // y == 7 // 0b00000111 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &>> 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &>> < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Self { return lhs &>> Self(truncatingIfNeeded: rhs) } /// Calculates the result of shifting a value's binary representation the /// specified number of digits to the right, masking the shift amount to the /// type's bit width, and stores the result in the left-hand-side variable. /// /// The `&>>=` operator performs a *masking shift*, where the value passed as /// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The /// shift is performed using this masked value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// var x: UInt8 = 30 // 0b00011110 /// x &>>= 2 /// // x == 7 // 0b00000111 /// /// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to /// `3`, and then uses that masked value as the number of bits to shift `lhs`. /// /// var y: UInt8 = 30 // 0b00011110 /// y &>>= 19 /// // y == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &>>= < Other: BinaryInteger >(lhs: inout Self, rhs: Other) { lhs = lhs &>> rhs } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left, masking the shift amount to the /// type's bit width. /// /// Use the masking left shift operator (`&<<`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &<< 2 /// // y == 120 // 0b01111000 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &<< 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &<< (lhs: Self, rhs: Self) -> Self { var lhs = lhs lhs &<<= rhs return lhs } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left, masking the shift amount to the /// type's bit width. /// /// Use the masking left shift operator (`&<<`) when you need to perform a /// shift and are sure that the shift amount is in the range /// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator /// masks the shift to this range. The shift is performed using this masked /// value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x &<< 2 /// // y == 120 // 0b01111000 /// /// However, if you use `8` as the shift amount, the method first masks the /// shift amount to zero, and then performs the shift, resulting in no change /// to the original value. /// /// let z = x &<< 8 /// // z == 30 // 0b00011110 /// /// If the bit width of the shifted integer type is a power of two, masking /// is performed using a bitmask; otherwise, masking is performed using a /// modulo operation. /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &<< < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Self { return lhs &<< Self(truncatingIfNeeded: rhs) } /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left, masking the shift amount to the /// type's bit width, and stores the result in the left-hand-side variable. /// /// The `&<<=` operator performs a *masking shift*, where the value used as /// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The /// shift is performed using this masked value. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the shift amount requires no masking. /// /// var x: UInt8 = 30 // 0b00011110 /// x &<<= 2 /// // x == 120 // 0b01111000 /// /// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to /// `3`, and then uses that masked value as the number of bits to shift `lhs`. /// /// var y: UInt8 = 30 // 0b00011110 /// y &<<= 19 /// // y == 240 // 0b11110000 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is /// outside the range `0..<lhs.bitWidth`, it is masked to produce a /// value within that range. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func &<<= < Other: BinaryInteger >(lhs: inout Self, rhs: Other) { lhs = lhs &<< rhs } } extension FixedWidthInteger { /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate an integer within a specific range when you /// are using a custom random number generator. This example creates three /// new values in the range `1..<100`. /// /// for _ in 1...3 { /// print(Int.random(in: 1..<100, using: &myGenerator)) /// } /// // Prints "7" /// // Prints "44" /// // Prints "21" /// /// - Note: The algorithm used to create random values may change in a future /// version of Swift. If you're passing a generator that results in the /// same sequence of integer values each time you run your program, that /// sequence may change when your program is compiled using a different /// version of Swift. /// /// - Parameters: /// - range: The range in which to create a random value. /// `range` must not be empty. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: Range<Self>, using generator: inout T ) -> Self { _precondition( !range.isEmpty, "Can't get random value with an empty range" ) // Compute delta, the distance between the lower and upper bounds. This // value may not representable by the type Bound if Bound is signed, but // is always representable as Bound.Magnitude. let delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound) // The mathematical result we want is lowerBound plus a random value in // 0 ..< delta. We need to be slightly careful about how we do this // arithmetic; the Bound type cannot generally represent the random value, // so we use a wrapping addition on Bound.Magnitude. This will often // overflow, but produces the correct bit pattern for the result when // converted back to Bound. return Self(truncatingIfNeeded: Magnitude(truncatingIfNeeded: range.lowerBound) &+ generator.next(upperBound: delta) ) } /// Returns a random value within the specified range. /// /// Use this method to generate an integer within a specific range. This /// example creates three new values in the range `1..<100`. /// /// for _ in 1...3 { /// print(Int.random(in: 1..<100)) /// } /// // Prints "53" /// // Prints "64" /// // Prints "5" /// /// This method is equivalent to calling the version that takes a generator, /// passing in the system's default random generator. /// /// - Parameter range: The range in which to create a random value. /// `range` must not be empty. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: Range<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate an integer within a specific range when you /// are using a custom random number generator. This example creates three /// new values in the range `1...100`. /// /// for _ in 1...3 { /// print(Int.random(in: 1...100, using: &myGenerator)) /// } /// // Prints "7" /// // Prints "44" /// // Prints "21" /// /// - Parameters: /// - range: The range in which to create a random value. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: ClosedRange<Self>, using generator: inout T ) -> Self { // Compute delta, the distance between the lower and upper bounds. This // value may not representable by the type Bound if Bound is signed, but // is always representable as Bound.Magnitude. var delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound) // Subtle edge case: if the range is the whole set of representable values, // then adding one to delta to account for a closed range will overflow. // If we used &+ instead, the result would be zero, which isn't helpful, // so we actually need to handle this case separately. if delta == Magnitude.max { return Self(truncatingIfNeeded: generator.next() as Magnitude) } // Need to widen delta to account for the right-endpoint of a closed range. delta += 1 // The mathematical result we want is lowerBound plus a random value in // 0 ..< delta. We need to be slightly careful about how we do this // arithmetic; the Bound type cannot generally represent the random value, // so we use a wrapping addition on Bound.Magnitude. This will often // overflow, but produces the correct bit pattern for the result when // converted back to Bound. return Self(truncatingIfNeeded: Magnitude(truncatingIfNeeded: range.lowerBound) &+ generator.next(upperBound: delta) ) } /// Returns a random value within the specified range. /// /// Use this method to generate an integer within a specific range. This /// example creates three new values in the range `1...100`. /// /// for _ in 1...3 { /// print(Int.random(in: 1...100)) /// } /// // Prints "53" /// // Prints "64" /// // Prints "5" /// /// This method is equivalent to calling `random(in:using:)`, passing in the /// system's default random generator. /// /// - Parameter range: The range in which to create a random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: ClosedRange<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } } //===----------------------------------------------------------------------===// //===--- Operators on FixedWidthInteger -----------------------------------===// //===----------------------------------------------------------------------===// extension FixedWidthInteger { /// Returns the inverse of the bits set in the argument. /// /// The bitwise NOT operator (`~`) is a prefix operator that returns a value /// in which all the bits of its argument are flipped: Bits that are `1` in /// the argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on 0 returns a value with every bit /// set to `1`. /// /// let allOnes = ~UInt8.min // 0b11111111 /// /// - Complexity: O(1). @_transparent public static prefix func ~ (x: Self) -> Self { return 0 &- x &- 1 } //===----------------------------------------------------------------------===// //=== "Smart right shift", supporting overshifts and negative shifts ------===// //===----------------------------------------------------------------------===// /// Returns the result of shifting a value's binary representation the /// specified number of digits to the right. /// /// The `>>` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a left shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*. An overshift results in `-1` for a /// negative value of `lhs` or `0` for a nonnegative value. /// - Using any other value for `rhs` performs a right shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted right by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x >> 2 /// // y == 7 // 0b00000111 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x >> 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a left shift /// using `abs(rhs)`. /// /// let a = x >> -3 /// // a == 240 // 0b11110000 /// let b = x << 3 /// // b == 240 // 0b11110000 /// /// Right shift operations on negative values "fill in" the high bits with /// ones instead of zeros. /// /// let q: Int8 = -30 // 0b11100010 /// let r = q >> 2 /// // r == -8 // 0b11111000 /// /// let s = q >> 11 /// // s == -1 // 0b11111111 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the right. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func >> < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Self { var lhs = lhs _nonMaskingRightShiftGeneric(&lhs, rhs) return lhs } @_transparent @_semantics("optimize.sil.specialize.generic.partial.never") public static func >>= < Other: BinaryInteger >(lhs: inout Self, rhs: Other) { _nonMaskingRightShiftGeneric(&lhs, rhs) } @_transparent public static func _nonMaskingRightShiftGeneric < Other: BinaryInteger >(_ lhs: inout Self, _ rhs: Other) { let shift = rhs < -Self.bitWidth ? -Self.bitWidth : rhs > Self.bitWidth ? Self.bitWidth : Int(rhs) lhs = _nonMaskingRightShift(lhs, shift) } @_transparent public static func _nonMaskingRightShift(_ lhs: Self, _ rhs: Int) -> Self { let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0 let overshiftL: Self = 0 if _fastPath(rhs >= 0) { if _fastPath(rhs < Self.bitWidth) { return lhs &>> Self(truncatingIfNeeded: rhs) } return overshiftR } if _slowPath(rhs <= -Self.bitWidth) { return overshiftL } return lhs &<< -rhs } //===----------------------------------------------------------------------===// //=== "Smart left shift", supporting overshifts and negative shifts -------===// //===----------------------------------------------------------------------===// /// Returns the result of shifting a value's binary representation the /// specified number of digits to the left. /// /// The `<<` operator performs a *smart shift*, which defines a result for a /// shift of any value. /// /// - Using a negative value for `rhs` performs a right shift using /// `abs(rhs)`. /// - Using a value for `rhs` that is greater than or equal to the bit width /// of `lhs` is an *overshift*, resulting in zero. /// - Using any other value for `rhs` performs a left shift on `lhs` by that /// amount. /// /// The following example defines `x` as an instance of `UInt8`, an 8-bit, /// unsigned integer type. If you use `2` as the right-hand-side value in an /// operation on `x`, the value is shifted left by two bits. /// /// let x: UInt8 = 30 // 0b00011110 /// let y = x << 2 /// // y == 120 // 0b01111000 /// /// If you use `11` as `rhs`, `x` is overshifted such that all of its bits /// are set to zero. /// /// let z = x << 11 /// // z == 0 // 0b00000000 /// /// Using a negative value as `rhs` is the same as performing a right shift /// with `abs(rhs)`. /// /// let a = x << -3 /// // a == 3 // 0b00000011 /// let b = x >> 3 /// // b == 3 // 0b00000011 /// /// - Parameters: /// - lhs: The value to shift. /// - rhs: The number of bits to shift `lhs` to the left. @_semantics("optimize.sil.specialize.generic.partial.never") @_transparent public static func << < Other: BinaryInteger >(lhs: Self, rhs: Other) -> Self { var lhs = lhs _nonMaskingLeftShiftGeneric(&lhs, rhs) return lhs } @_transparent @_semantics("optimize.sil.specialize.generic.partial.never") public static func <<= < Other: BinaryInteger >(lhs: inout Self, rhs: Other) { _nonMaskingLeftShiftGeneric(&lhs, rhs) } @_transparent public static func _nonMaskingLeftShiftGeneric < Other: BinaryInteger >(_ lhs: inout Self, _ rhs: Other) { let shift = rhs < -Self.bitWidth ? -Self.bitWidth : rhs > Self.bitWidth ? Self.bitWidth : Int(rhs) lhs = _nonMaskingLeftShift(lhs, shift) } @_transparent public static func _nonMaskingLeftShift(_ lhs: Self, _ rhs: Int) -> Self { let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0 let overshiftL: Self = 0 if _fastPath(rhs >= 0) { if _fastPath(rhs < Self.bitWidth) { return lhs &<< Self(truncatingIfNeeded: rhs) } return overshiftL } if _slowPath(rhs <= -Self.bitWidth) { return overshiftR } return lhs &>> -rhs } } extension FixedWidthInteger { @inlinable @_semantics("optimize.sil.specialize.generic.partial.never") public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self?, exact: Bool) { guard _fastPath(!source.isZero) else { return (0, true) } guard _fastPath(source.isFinite) else { return (nil, false) } guard Self.isSigned || source > -1 else { return (nil, false) } let exponent = source.exponent if _slowPath(Self.bitWidth <= exponent) { return (nil, false) } let minBitWidth = source.significandWidth let isExact = (minBitWidth <= exponent) let bitPattern = source.significandBitPattern // `RawSignificand.bitWidth` is not available if `RawSignificand` does not // conform to `FixedWidthInteger`; we can compute this value as follows if // `source` is finite: let bitWidth = minBitWidth &+ bitPattern.trailingZeroBitCount let shift = exponent - Source.Exponent(bitWidth) // Use `Self.Magnitude` to prevent sign extension if `shift < 0`. let shiftedBitPattern = Self.Magnitude.bitWidth > bitWidth ? Self.Magnitude(truncatingIfNeeded: bitPattern) << shift : Self.Magnitude(truncatingIfNeeded: bitPattern << shift) if _slowPath(Self.isSigned && Self.bitWidth &- 1 == exponent) { return source < 0 && shiftedBitPattern == 0 ? (Self.min, isExact) : (nil, false) } let magnitude = ((1 as Self.Magnitude) << exponent) | shiftedBitPattern return ( Self.isSigned && source < 0 ? 0 &- Self(magnitude) : Self(magnitude), isExact) } /// Creates an integer from the given floating-point value, rounding toward /// zero. Any fractional part of the value passed as `source` is removed. /// /// let x = Int(21.5) /// // x == 21 /// let y = Int(-21.5) /// // y == -21 /// /// If `source` is outside the bounds of this type after rounding toward /// zero, a runtime error may occur. /// /// let z = UInt(-21.5) /// // Error: ...outside the representable range /// /// - Parameter source: A floating-point value to convert to an integer. /// `source` must be representable in this type after rounding toward /// zero. @inlinable @_semantics("optimize.sil.specialize.generic.partial.never") @inline(__always) public init<T: BinaryFloatingPoint>(_ source: T) { guard let value = Self._convert(from: source).value else { fatalError(""" \(T.self) value cannot be converted to \(Self.self) because it is \ outside the representable range """) } self = value } /// Creates an integer from the given floating-point value, if it can be /// represented exactly. /// /// If the value passed as `source` is not representable exactly, the result /// is `nil`. In the following example, the constant `x` is successfully /// created from a value of `21.0`, while the attempt to initialize the /// constant `y` from `21.5` fails: /// /// let x = Int(exactly: 21.0) /// // x == Optional(21) /// let y = Int(exactly: 21.5) /// // y == nil /// /// - Parameter source: A floating-point value to convert to an integer. @_semantics("optimize.sil.specialize.generic.partial.never") @inlinable public init?<T: BinaryFloatingPoint>(exactly source: T) { let (temporary, exact) = Self._convert(from: source) guard exact, let value = temporary else { return nil } self = value } /// Creates a new instance with the representable value that's closest to the /// given integer. /// /// If the value passed as `source` is greater than the maximum representable /// value in this type, the result is the type's `max` value. If `source` is /// less than the smallest representable value in this type, the result is /// the type's `min` value. /// /// In this example, `x` is initialized as an `Int8` instance by clamping /// `500` to the range `-128...127`, and `y` is initialized as a `UInt` /// instance by clamping `-500` to the range `0...UInt.max`. /// /// let x = Int8(clamping: 500) /// // x == 127 /// // x == Int8.max /// /// let y = UInt(clamping: -500) /// // y == 0 /// /// - Parameter source: An integer to convert to this type. @inlinable @_semantics("optimize.sil.specialize.generic.partial.never") public init<Other: BinaryInteger>(clamping source: Other) { if _slowPath(source < Self.min) { self = Self.min } else if _slowPath(source > Self.max) { self = Self.max } else { self = Self(truncatingIfNeeded: source) } } /// Creates a new instance from the bit pattern of the given instance by /// truncating or sign-extending if needed to fit this type. /// /// When the bit width of `T` (the type of `source`) is equal to or greater /// than this type's bit width, the result is the truncated /// least-significant bits of `source`. For example, when converting a /// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are /// used. /// /// let p: Int16 = -500 /// // 'p' has a binary representation of 11111110_00001100 /// let q = Int8(truncatingIfNeeded: p) /// // q == 12 /// // 'q' has a binary representation of 00001100 /// /// When the bit width of `T` is less than this type's bit width, the result /// is *sign-extended* to fill the remaining bits. That is, if `source` is /// negative, the result is padded with ones; otherwise, the result is /// padded with zeros. /// /// let u: Int8 = 21 /// // 'u' has a binary representation of 00010101 /// let v = Int16(truncatingIfNeeded: u) /// // v == 21 /// // 'v' has a binary representation of 00000000_00010101 /// /// let w: Int8 = -21 /// // 'w' has a binary representation of 11101011 /// let x = Int16(truncatingIfNeeded: w) /// // x == -21 /// // 'x' has a binary representation of 11111111_11101011 /// let y = UInt16(truncatingIfNeeded: w) /// // y == 65515 /// // 'y' has a binary representation of 11111111_11101011 /// /// - Parameter source: An integer to convert to this type. @inlinable // FIXME(inline-always) @inline(__always) public init<T: BinaryInteger>(truncatingIfNeeded source: T) { if Self.bitWidth <= Int.bitWidth { self = Self(_truncatingBits: source._lowWord) } else { let neg = source < (0 as T) var result: Self = neg ? ~0 : 0 var shift: Self = 0 let width = Self(_truncatingBits: Self.bitWidth._lowWord) for word in source.words { guard shift < width else { break } // Masking shift is OK here because we have already ensured // that shift < Self.bitWidth. Not masking results in // infinite recursion. result ^= Self(_truncatingBits: neg ? ~word : word) &<< shift shift += Self(_truncatingBits: Int.bitWidth._lowWord) } self = result } } @_transparent public // transparent static var _highBitIndex: Self { return Self.init(_truncatingBits: UInt(Self.bitWidth._value) &- 1) } /// Returns the sum of the two given values, wrapping the result in case of /// any overflow. /// /// The overflow addition operator (`&+`) discards any bits that overflow the /// fixed width of the integer type. In the following example, the sum of /// `100` and `121` is greater than the maximum representable `Int8` value, /// so the result is the partial value after discarding the overflowing /// bits. /// /// let x: Int8 = 10 &+ 21 /// // x == 31 /// let y: Int8 = 100 &+ 121 /// // y == -35 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. @_transparent public static func &+ (lhs: Self, rhs: Self) -> Self { return lhs.addingReportingOverflow(rhs).partialValue } /// Adds two values and stores the result in the left-hand-side variable, /// wrapping any overflow. /// /// The masking addition assignment operator (`&+=`) silently wraps any /// overflow that occurs during the operation. In the following example, the /// sum of `100` and `121` is greater than the maximum representable `Int8` /// value, so the result is the partial value after discarding the /// overflowing bits. /// /// var x: Int8 = 10 /// x &+= 21 /// // x == 31 /// var y: Int8 = 100 /// y &+= 121 /// // y == -35 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. @_transparent public static func &+= (lhs: inout Self, rhs: Self) { lhs = lhs &+ rhs } /// Returns the difference of the two given values, wrapping the result in /// case of any overflow. /// /// The overflow subtraction operator (`&-`) discards any bits that overflow /// the fixed width of the integer type. In the following example, the /// difference of `10` and `21` is less than zero, the minimum representable /// `UInt` value, so the result is the partial value after discarding the /// overflowing bits. /// /// let x: UInt8 = 21 &- 10 /// // x == 11 /// let y: UInt8 = 10 &- 21 /// // y == 245 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. @_transparent public static func &- (lhs: Self, rhs: Self) -> Self { return lhs.subtractingReportingOverflow(rhs).partialValue } /// Subtracts the second value from the first and stores the difference in the /// left-hand-side variable, wrapping any overflow. /// /// The masking subtraction assignment operator (`&-=`) silently wraps any /// overflow that occurs during the operation. In the following example, the /// difference of `10` and `21` is less than zero, the minimum representable /// `UInt` value, so the result is the result is the partial value after /// discarding the overflowing bits. /// /// var x: Int8 = 21 /// x &-= 10 /// // x == 11 /// var y: UInt8 = 10 /// y &-= 21 /// // y == 245 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. @_transparent public static func &-= (lhs: inout Self, rhs: Self) { lhs = lhs &- rhs } /// Returns the product of the two given values, wrapping the result in case /// of any overflow. /// /// The overflow multiplication operator (`&*`) discards any bits that /// overflow the fixed width of the integer type. In the following example, /// the product of `10` and `50` is greater than the maximum representable /// `Int8` value, so the result is the partial value after discarding the /// overflowing bits. /// /// let x: Int8 = 10 &* 5 /// // x == 50 /// let y: Int8 = 10 &* 50 /// // y == -12 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. @_transparent public static func &* (lhs: Self, rhs: Self) -> Self { return lhs.multipliedReportingOverflow(by: rhs).partialValue } /// Multiplies two values and stores the result in the left-hand-side /// variable, wrapping any overflow. /// /// The masking multiplication assignment operator (`&*=`) silently wraps /// any overflow that occurs during the operation. In the following example, /// the product of `10` and `50` is greater than the maximum representable /// `Int8` value, so the result is the partial value after discarding the /// overflowing bits. /// /// var x: Int8 = 10 /// x &*= 5 /// // x == 50 /// var y: Int8 = 10 /// y &*= 50 /// // y == -12 (after overflow) /// /// For more about arithmetic with overflow operators, see [Overflow /// Operators][overflow] in *[The Swift Programming Language][tspl]*. /// /// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37 /// [tspl]: https://docs.swift.org/swift-book/ /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. @_transparent public static func &*= (lhs: inout Self, rhs: Self) { lhs = lhs &* rhs } } extension FixedWidthInteger { @inlinable public static func _random<R: RandomNumberGenerator>( using generator: inout R ) -> Self { if bitWidth <= UInt64.bitWidth { return Self(truncatingIfNeeded: generator.next()) } let (quotient, remainder) = bitWidth.quotientAndRemainder( dividingBy: UInt64.bitWidth ) var tmp: Self = 0 for i in 0 ..< quotient + remainder.signum() { let next: UInt64 = generator.next() tmp += Self(truncatingIfNeeded: next) &<< (UInt64.bitWidth * i) } return tmp } } //===----------------------------------------------------------------------===// //===--- UnsignedInteger --------------------------------------------------===// //===----------------------------------------------------------------------===// /// An integer type that can represent only nonnegative values. public protocol UnsignedInteger: BinaryInteger { } extension UnsignedInteger { /// The magnitude of this value. /// /// Every unsigned integer is its own magnitude, so for any value `x`, /// `x == x.magnitude`. /// /// The global `abs(_:)` function provides more familiar syntax when you need /// to find an absolute value. In addition, because `abs(_:)` always returns /// a value of the same type, even in a generic context, using the function /// instead of the `magnitude` property is encouraged. @inlinable // FIXME(inline-always) public var magnitude: Self { @inline(__always) get { return self } } /// A Boolean value indicating whether this type is a signed integer type. /// /// This property is always `false` for unsigned integer types. @inlinable // FIXME(inline-always) public static var isSigned: Bool { @inline(__always) get { return false } } } extension UnsignedInteger where Self: FixedWidthInteger { /// Creates a new instance from the given integer. /// /// Use this initializer to convert from another integer type when you know /// the value is within the bounds of this type. Passing a value that can't /// be represented in this type results in a runtime error. /// /// In the following example, the constant `y` is successfully created from /// `x`, an `Int` instance with a value of `100`. Because the `Int8` type /// can represent `127` at maximum, the attempt to create `z` with a value /// of `1000` results in a runtime error. /// /// let x = 100 /// let y = Int8(x) /// // y == 100 /// let z = Int8(x * 10) /// // Error: Not enough bits to represent the given value /// /// - Parameter source: A value to convert to this type of integer. The value /// passed as `source` must be representable in this type. @_semantics("optimize.sil.specialize.generic.partial.never") @inlinable // FIXME(inline-always) @inline(__always) public init<T: BinaryInteger>(_ source: T) { // This check is potentially removable by the optimizer if T.isSigned { _precondition(source >= (0 as T), "Negative value is not representable") } // This check is potentially removable by the optimizer if source.bitWidth >= Self.bitWidth { _precondition(source <= Self.max, "Not enough bits to represent the passed value") } self.init(truncatingIfNeeded: source) } /// Creates a new instance from the given integer, if it can be represented /// exactly. /// /// If the value passed as `source` is not representable exactly, the result /// is `nil`. In the following example, the constant `x` is successfully /// created from a value of `100`, while the attempt to initialize the /// constant `y` from `1_000` fails because the `Int8` type can represent /// `127` at maximum: /// /// let x = Int8(exactly: 100) /// // x == Optional(100) /// let y = Int8(exactly: 1_000) /// // y == nil /// /// - Parameter source: A value to convert to this type of integer. @_semantics("optimize.sil.specialize.generic.partial.never") @inlinable // FIXME(inline-always) @inline(__always) public init?<T: BinaryInteger>(exactly source: T) { // This check is potentially removable by the optimizer if T.isSigned && source < (0 as T) { return nil } // The width check can be eliminated by the optimizer if source.bitWidth >= Self.bitWidth && source > Self.max { return nil } self.init(truncatingIfNeeded: source) } /// The maximum representable integer in this type. /// /// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where /// `**` is exponentiation. @_transparent public static var max: Self { return ~0 } /// The minimum representable integer in this type. /// /// For unsigned integer types, this value is always `0`. @_transparent public static var min: Self { return 0 } } //===----------------------------------------------------------------------===// //===--- SignedInteger ----------------------------------------------------===// //===----------------------------------------------------------------------===// /// An integer type that can represent both positive and negative values. public protocol SignedInteger: BinaryInteger, SignedNumeric { // These requirements are for the source code compatibility with Swift 3 static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self } extension SignedInteger { /// A Boolean value indicating whether this type is a signed integer type. /// /// This property is always `true` for signed integer types. @inlinable // FIXME(inline-always) public static var isSigned: Bool { @inline(__always) get { return true } } } extension SignedInteger where Self: FixedWidthInteger { /// Creates a new instance from the given integer. /// /// Use this initializer to convert from another integer type when you know /// the value is within the bounds of this type. Passing a value that can't /// be represented in this type results in a runtime error. /// /// In the following example, the constant `y` is successfully created from /// `x`, an `Int` instance with a value of `100`. Because the `Int8` type /// can represent `127` at maximum, the attempt to create `z` with a value /// of `1000` results in a runtime error. /// /// let x = 100 /// let y = Int8(x) /// // y == 100 /// let z = Int8(x * 10) /// // Error: Not enough bits to represent the given value /// /// - Parameter source: A value to convert to this type of integer. The value /// passed as `source` must be representable in this type. @_semantics("optimize.sil.specialize.generic.partial.never") @inlinable // FIXME(inline-always) @inline(__always) public init<T: BinaryInteger>(_ source: T) { // This check is potentially removable by the optimizer if T.isSigned && source.bitWidth > Self.bitWidth { _precondition(source >= Self.min, "Not enough bits to represent a signed value") } // This check is potentially removable by the optimizer if (source.bitWidth > Self.bitWidth) || (source.bitWidth == Self.bitWidth && !T.isSigned) { _precondition(source <= Self.max, "Not enough bits to represent the passed value") } self.init(truncatingIfNeeded: source) } /// Creates a new instance from the given integer, if it can be represented /// exactly. /// /// If the value passed as `source` is not representable exactly, the result /// is `nil`. In the following example, the constant `x` is successfully /// created from a value of `100`, while the attempt to initialize the /// constant `y` from `1_000` fails because the `Int8` type can represent /// `127` at maximum: /// /// let x = Int8(exactly: 100) /// // x == Optional(100) /// let y = Int8(exactly: 1_000) /// // y == nil /// /// - Parameter source: A value to convert to this type of integer. @_semantics("optimize.sil.specialize.generic.partial.never") @inlinable // FIXME(inline-always) @inline(__always) public init?<T: BinaryInteger>(exactly source: T) { // This check is potentially removable by the optimizer if T.isSigned && source.bitWidth > Self.bitWidth && source < Self.min { return nil } // The width check can be eliminated by the optimizer if (source.bitWidth > Self.bitWidth || (source.bitWidth == Self.bitWidth && !T.isSigned)) && source > Self.max { return nil } self.init(truncatingIfNeeded: source) } /// The maximum representable integer in this type. /// /// For signed integer types, this value is `(2 ** (bitWidth - 1)) - 1`, /// where `**` is exponentiation. @_transparent public static var max: Self { return ~min } /// The minimum representable integer in this type. /// /// For signed integer types, this value is `-(2 ** (bitWidth - 1))`, where /// `**` is exponentiation. @_transparent public static var min: Self { return (-1 as Self) &<< Self._highBitIndex } @inlinable public func isMultiple(of other: Self) -> Bool { // Nothing but zero is a multiple of zero. if other == 0 { return self == 0 } // Special case to avoid overflow on .min / -1 for signed types. if other == -1 { return true } // Having handled those special cases, this is safe. return self % other == 0 } } /// Returns the given integer as the equivalent value in a different integer /// type. /// /// Calling the `numericCast(_:)` function is equivalent to calling an /// initializer for the destination type. `numericCast(_:)` traps on overflow /// in `-O` and `-Onone` builds. /// /// - Parameter x: The integer to convert, an instance of type `T`. /// - Returns: The value of `x` converted to type `U`. @inlinable public func numericCast<T: BinaryInteger, U: BinaryInteger>(_ x: T) -> U { return U(x) } // FIXME(integers): Absence of &+ causes ambiguity in the code like the // following: // func f<T: SignedInteger>(_ x: T, _ y: T) { // var _ = (x &+ (y - 1)) < x // } // Compiler output: // error: ambiguous reference to member '-' // var _ = (x &+ (y - 1)) < x // ^ extension SignedInteger { @_transparent public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self { fatalError("Should be overridden in a more specific type") } @_transparent public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self { fatalError("Should be overridden in a more specific type") } } extension SignedInteger where Self: FixedWidthInteger { // This overload is supposed to break the ambiguity between the // implementations on SignedInteger and FixedWidthInteger @_transparent public static func &+ (lhs: Self, rhs: Self) -> Self { return _maskingAdd(lhs, rhs) } @_transparent public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self { return lhs.addingReportingOverflow(rhs).partialValue } // This overload is supposed to break the ambiguity between the // implementations on SignedInteger and FixedWidthInteger @_transparent public static func &- (lhs: Self, rhs: Self) -> Self { return _maskingSubtract(lhs, rhs) } @_transparent public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self { return lhs.subtractingReportingOverflow(rhs).partialValue } }
apache-2.0
bda24cc6920b92a9d8bd32a5000c33a1
37.262456
93
0.594202
4.068377
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Tokens/Storage/TokensDataStore.swift
1
8546
// Copyright DApps Platform Inc. All rights reserved. import Foundation import Result import APIKit import RealmSwift import BigInt import Moya import TrustCore enum TokenAction { case disable(Bool) case updateInfo } class TokensDataStore { var tokens: Results<TokenObject> { return realm.objects(TokenObject.self).filter(NSPredicate(format: "isDisabled == NO")) .sorted(byKeyPath: "order", ascending: true) } // tokens that needs balance and value update var tokensBalance: Results<TokenObject> { return realm.objects(TokenObject.self).filter(NSPredicate(format: "isDisabled == NO || rawType = \"coin\"")) .sorted(byKeyPath: "order", ascending: true) } var nonFungibleTokens: Results<CollectibleTokenCategory> { return realm.objects(CollectibleTokenCategory.self).sorted(byKeyPath: "name", ascending: true) } var tickers: Results<CoinTicker> { return realm.objects(CoinTicker.self).filter("tickersKey == %@", CoinTickerKeyMaker.makeCurrencyKey()) } let realm: Realm let account: WalletInfo var objects: [TokenObject] { return realm.objects(TokenObject.self) .sorted(byKeyPath: "order", ascending: true) .filter { !$0.contract.isEmpty } } var enabledObject: [TokenObject] { return realm.objects(TokenObject.self) .sorted(byKeyPath: "order", ascending: true) .filter { !$0.isDisabled } } init( realm: Realm, account: WalletInfo ) { self.realm = realm self.account = account self.addNativeCoins() } private func addNativeCoins() { if let token = getToken(for: EthereumAddress.zero) { try? realm.write { realm.delete(token) } } let initialCoins = nativeCoin() for token in initialCoins { if let _ = getToken(for: token.contractAddress) { } else { add(tokens: [token]) } } } func getToken(for address: Address) -> TokenObject? { return realm.object(ofType: TokenObject.self, forPrimaryKey: address.description) } func coinTicker(by contract: Address) -> CoinTicker? { return realm.object(ofType: CoinTicker.self, forPrimaryKey: CoinTickerKeyMaker.makePrimaryKey(contract: contract, currencyKey: CoinTickerKeyMaker.makeCurrencyKey())) } private func nativeCoin() -> [TokenObject] { return account.accounts.compactMap { ac in guard let coin = ac.coin else { return .none } let viewModel = CoinViewModel(coin: coin) let isDisabled: Bool = { if !account.mainWallet { return false } return coin.server.isDisabledByDefault }() return TokenObject( contract: coin.server.priceID.description, name: viewModel.name, coin: coin, type: .coin, symbol: viewModel.symbol, decimals: coin.server.decimals, value: "0", isCustom: false, isDisabled: isDisabled, order: coin.rawValue ) } } static func token(for server: RPCServer) -> TokenObject { let coin = server.coin let viewModel = CoinViewModel(coin: server.coin) return TokenObject( contract: server.priceID.description, name: viewModel.name, coin: coin, type: .coin, symbol: viewModel.symbol, decimals: server.decimals, value: "0", isCustom: false ) } static func getServer(for token: TokenObject) -> RPCServer! { return token.coin.server } func addCustom(token: ERC20Token) { let newToken = TokenObject( contract: token.contract.description, name: token.name, coin: token.coin, type: .ERC20, symbol: token.symbol, decimals: token.decimals, value: "0", isCustom: true ) add(tokens: [newToken]) } func add(tokens: [Object]) { try? realm.write { if let tokenObjects = tokens as? [TokenObject] { let tokenObjectsWithBalance = tokenObjects.map { tokenObject -> TokenObject in tokenObject.balance = self.getBalance(for: tokenObject.address, with: tokenObject.valueBigInt, and: tokenObject.decimals) return tokenObject } realm.add(tokenObjectsWithBalance, update: true) } else { realm.add(tokens, update: true) } } } func delete(tokens: [Object]) { try? realm.write { realm.delete(tokens) } } func deleteAll() { deleteAllExistingTickers() try? realm.write { realm.delete(realm.objects(TokenObject.self)) realm.delete(realm.objects(CollectibleTokenObject.self)) realm.delete(realm.objects(CollectibleTokenCategory.self)) } } //Background update of the Realm model. func update(balance: BigInt, for address: Address) { if let token = getToken(for: address) { let tokenBalance = getBalance(for: token.address, with: balance, and: token.decimals) self.realm.writeAsync(obj: token) { (realm, _ ) in let update = self.objectToUpdate(for: (address, balance), tokenBalance: tokenBalance) realm.create(TokenObject.self, value: update, update: true) } } } private func objectToUpdate(for balance: (key: Address, value: BigInt), tokenBalance: Double) -> [String: Any] { return [ "contract": balance.key.description, "value": balance.value.description, "balance": tokenBalance, ] } func update(tokens: [TokenObject], action: TokenAction) { try? realm.write { for token in tokens { switch action { case .disable(let value): token.isDisabled = value case .updateInfo: let update: [String: Any] = [ "contract": token.address.description, "name": token.name, "symbol": token.symbol, "decimals": token.decimals, "rawType": token.type.rawValue, "rawCoin": token.coin.rawValue, ] realm.create(TokenObject.self, value: update, update: true) } } } } func saveTickers(tickers: [CoinTicker]) { guard !tickers.isEmpty else { return } try? realm.write { realm.add(tickers, update: true) } } private var tickerResultsByTickersKey: Results<CoinTicker> { return realm.objects(CoinTicker.self).filter("tickersKey == %@", CoinTickerKeyMaker.makeCurrencyKey()) } func deleteAllExistingTickers() { try? realm.write { realm.delete(tickerResultsByTickersKey) } } func getBalance(for address: Address, with value: BigInt, and decimals: Int) -> Double { guard let ticker = coinTicker(by: address), let amountInDecimal = EtherNumberFormatter.full.decimal(from: value, decimals: decimals), let price = Double(ticker.price) else { return TokenObject.DEFAULT_BALANCE } return amountInDecimal.doubleValue * price } func clearBalance() { try? realm.write { let defaultBalanceTokens = tokens.map { token -> TokenObject in let tempToken = token tempToken.balance = TokenObject.DEFAULT_BALANCE return tempToken } realm.add(defaultBalanceTokens, update: true) } } } extension Coin { var server: RPCServer { switch self { case .bitcoin: return RPCServer.main //TODO case .ethereum: return RPCServer.main case .ethereumClassic: return RPCServer.classic case .gochain: return RPCServer.gochain case .callisto: return RPCServer.callisto case .poa: return RPCServer.poa } } }
gpl-3.0
7173ff68790aaa809f7ee1ec222bc17a
31.869231
173
0.567868
4.649619
false
false
false
false
praveenb-ios/PBDataTableView
PBDataTable/Classes/PBDataTableViewCell.swift
1
2370
// // PBDataTableViewCell.swift // PBDataTable // // Created by praveen b on 6/10/16. // Copyright © 2016 Praveen. All rights reserved. // import UIKit class PBDataTableViewCell: UITableViewCell { var columnWidth: CGFloat = 80 @IBOutlet var leftBorderView: UIView! @IBOutlet var rightBorderView: UIView! @IBOutlet var bottomBorderView: UIView! override func awakeFromNib() { super.awakeFromNib() // Initialization code var labelXaxis: CGFloat = 0 for i in 0..<ApplicationDelegate.numberOfColumns { let columnLbl = UILabel() //If Last Column of the Cell is Button if ApplicationDelegate.cellLastColumnButtonEnable == true && i == ApplicationDelegate.numberOfColumns-1 { let editBtn = UIButton(type: .custom) editBtn.frame = CGRect(x: labelXaxis, y: (self.frame.height-35)/2, width: 70,height: 35) editBtn.backgroundColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1.0) editBtn.tag = 100+i editBtn.setTitle("Edit", for: UIControlState()) self.contentView.addSubview(editBtn) }else { columnLbl.frame = CGRect(x: labelXaxis, y: 0, width: columnWidth,height: self.frame.height) columnLbl.textAlignment = .center columnLbl.font = UIFont(name: "Arial", size: 10) columnLbl.tag = 100+i columnLbl.adjustsFontSizeToFitWidth = true self.contentView.addSubview(columnLbl) } if i != ApplicationDelegate.numberOfColumns-1 { let innerBorderView = UIView() innerBorderView.frame = CGRect(x: columnLbl.frame.maxX-1, y: 0, width: 1, height: self.frame.height) innerBorderView.backgroundColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1.0) innerBorderView.tag = 200+i self.contentView.addSubview(innerBorderView) } labelXaxis = labelXaxis + columnWidth } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
73a9980974dfe552fc18fd714d467f65
36.015625
118
0.592655
4.6
false
false
false
false
soapyigu/LeetCode_Swift
LinkedList/ReverseLinkedList.swift
1
1076
/** * Question Link: https://leetcode.com/problems/reverse-linked-list/ * Primary idea: Use two helper nodes, traverse the linkedlist and change point direction each time * Time Complexity: O(n), Space Complexity: O(1) * * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class ReverseLinkedList { func reverseList(head: ListNode?) -> ListNode? { var temp: ListNode? var first = head while first != nil { let second = first!.next first!.next = temp temp = first first = second } return temp } func reverseList(_ head: ListNode?) -> ListNode? { guard let h = head, let next = h.next else { return head } let node = reverseList(next) next.next = h h.next = nil return node } }
mit
728e3280808358837bd331aa9c5eb9f8
22.413043
99
0.527881
4.286853
false
false
false
false
keyeMyria/edx-app-ios
Source/CourseOutlineItemView.swift
3
7663
// // CourseOutlineItemView.swift // edX // // Created by Ehmad Zubair Chughtai on 18/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit private let TitleOffsetTrailing = -10 private let SubtitleOffsetTrailing = -10 private let IconSize = CGSizeMake(25, 25) private let CellOffsetTrailing : CGFloat = -10 private let TitleOffsetCenterY = -10 private let TitleOffsetLeading = 40 private let SubtitleOffsetCenterY = 10 private let DownloadCountOffsetTrailing = -2 private let SmallIconSize : CGFloat = 15 private let IconFontSize : CGFloat = 15 public class CourseOutlineItemView: UIView { private let horizontalMargin = OEXStyles.sharedStyles().standardHorizontalMargin() private let fontStyle = OEXTextStyle(weight: .Normal, size: .Base, color : OEXStyles.sharedStyles().neutralBlack()) private let detailFontStyle = OEXTextStyle(weight: .Normal, size: .Small, color : OEXStyles.sharedStyles().neutralBase()) private let titleLabel = UILabel() private let subtitleLabel = UILabel() private let leadingImageButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton private let trailingImageButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton private let checkmark = UIImageView() private let trailingCountLabel = UILabel() var hasLeadingImageIcon :Bool { return leadingImageButton.imageForState(.Normal) != nil } public var isGraded : Bool? { get { return !checkmark.hidden } set { checkmark.hidden = !(newValue!) setNeedsUpdateConstraints() } } var leadingIconColor : UIColor? { get { return leadingImageButton.tintColor } set { leadingImageButton.tintColor = newValue } } var trailingIconColor : UIColor? { get { return trailingImageButton.tintColor } set { trailingImageButton.tintColor = newValue } } func useTrailingCount(count : Int?) { trailingCountLabel.attributedText = detailFontStyle.attributedStringWithText(count.map { "\($0)" }) if let downloadableCount = self.trailingCountLabel.text, trailingCount = count { var downloadableCountMessage : NSString = OEXLocalizedStringPlural("ACCESSIBILITY_DOWNLOADABLE_VIDEOS", Float(trailingCount), nil) downloadableCountMessage = downloadableCountMessage.oex_formatWithParameters(["video_count":downloadableCount]) trailingImageButton.accessibilityHint = downloadableCountMessage as? String } } func setTrailingIconHidden(hidden : Bool) { self.trailingImageButton.hidden = hidden setNeedsUpdateConstraints() } init(trailingImageIcon : Icon? = nil) { super.init(frame: CGRectZero) leadingImageButton.tintColor = OEXStyles.sharedStyles().primaryBaseColor() leadingImageButton.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) trailingImageButton.setImage(trailingImageIcon?.imageWithFontSize(IconFontSize), forState: .Normal) trailingImageButton.tintColor = OEXStyles.sharedStyles().neutralBase() trailingImageButton.contentEdgeInsets = UIEdgeInsetsMake(15, 10, 15, 10) trailingImageButton.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) leadingImageButton.accessibilityTraits = UIAccessibilityTraitImage trailingImageButton.accessibilityLabel = OEXLocalizedString("DOWNLOAD", nil) checkmark.image = Icon.Graded.imageWithFontSize(15) checkmark.tintColor = OEXStyles.sharedStyles().neutralBase() isGraded = false addSubviews() setAccessibility() } func addActionForTrailingIconTap(action : AnyObject -> Void) -> OEXRemovable { return trailingImageButton.oex_addAction(action, forEvents: UIControlEvents.TouchUpInside) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTitleText(title : String?) { let displayTitle = (title?.isEmpty ?? true) ? OEXLocalizedString("UNTITLED", nil) : title titleLabel.attributedText = fontStyle.attributedStringWithText(displayTitle) } func setDetailText(title : String) { subtitleLabel.attributedText = detailFontStyle.attributedStringWithText(title) setNeedsUpdateConstraints() } func setContentIcon(icon : Icon?) { leadingImageButton.setImage(icon?.imageWithFontSize(IconFontSize), forState: .Normal) setNeedsUpdateConstraints() if let accessibilityText = icon?.accessibilityText { leadingImageButton.accessibilityLabel = accessibilityText } } override public func updateConstraints() { leadingImageButton.snp_updateConstraints { (make) -> Void in make.centerY.equalTo(self) let situationalleadingOffset = hasLeadingImageIcon ? horizontalMargin : 0 if hasLeadingImageIcon { make.leading.equalTo(self).offset(horizontalMargin) } else { make.leading.equalTo(self) } make.size.equalTo(IconSize) } let shouldOffsetTitle = !(subtitleLabel.text?.isEmpty ?? true) titleLabel.snp_updateConstraints { (make) -> Void in let titleOffset = shouldOffsetTitle ? TitleOffsetCenterY : 0 make.centerY.equalTo(self).offset(titleOffset) if hasLeadingImageIcon { make.leading.equalTo(leadingImageButton.snp_trailing).offset(horizontalMargin) } else { make.leading.equalTo(self).offset(horizontalMargin) } make.trailing.equalTo(trailingImageButton.snp_leading).offset(TitleOffsetTrailing) } super.updateConstraints() } private func addSubviews() { addSubview(leadingImageButton) addSubview(trailingImageButton) addSubview(titleLabel) addSubview(subtitleLabel) addSubview(checkmark) addSubview(trailingCountLabel) // For performance only add the static constraints once subtitleLabel.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(self).offset(SubtitleOffsetCenterY).constraint make.leading.equalTo(titleLabel) } checkmark.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(subtitleLabel.snp_centerY) make.leading.equalTo(subtitleLabel.snp_trailing).offset(5) make.size.equalTo(CGSizeMake(SmallIconSize, SmallIconSize)) } trailingImageButton.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.snp_trailing).offset(CellOffsetTrailing) make.centerY.equalTo(self) } trailingCountLabel.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(trailingImageButton) make.trailing.equalTo(trailingImageButton.snp_centerX).offset(DownloadCountOffsetTrailing) make.size.equalTo(CGSizeMake(SmallIconSize, SmallIconSize)) } } public override class func requiresConstraintBasedLayout() -> Bool { return true } private func setAccessibility() { trailingCountLabel.isAccessibilityElement = false subtitleLabel.isAccessibilityElement = false } }
apache-2.0
1c9f9885b3629f2535947988eaf13eab
37.124378
142
0.669059
5.385102
false
false
false
false
itechline/bonodom_new
SlideMenuControllerSwift/MessageThreadItemView.swift
1
2165
// // MessageThreadItemView.swift // Bonodom // // Created by Attila Dan on 16/06/16. // Copyright © 2016 Itechline. All rights reserved. // import UIKit import QuartzCore import SwiftyJSON struct MessageThreadItemData { init(conv_msg: String, fromme: Int) { self.conv_msg = conv_msg self.fromme = fromme } var conv_msg: String var fromme: Int } class MessageThreadItemView: BaseTableViewCell { @IBOutlet weak var profilepic_1: UIImageView! @IBOutlet weak var msg_1: UILabel! @IBOutlet weak var profilepic_2: UIImageView! @IBOutlet weak var msg_2: UILabel! func heightForView(text:String, label: UILabel) -> CGFloat{ //let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.text = text label.sizeToFit() return label.frame.height } override func awakeFromNib() { self.msg_1.layer.masksToBounds = true self.msg_2.layer.masksToBounds = true self.msg_1.layer.cornerRadius = 6 self.msg_1.layer.backgroundColor = UIColor.init(hex: "0066cc").CGColor self.msg_2.layer.cornerRadius = 6 self.msg_2.layer.backgroundColor = UIColor.init(hex: "ffffff").CGColor //self.dataText?.font = UIFont.boldSystemFontOfSize(16) //self.dataText?.textColor = UIColor(hex: "000000") } override class func height() -> CGFloat { return 55 } override func setData(data: Any?) { if let data = data as? MessageThreadItemData { if (data.fromme == 0) { heightForView(data.conv_msg, label: self.msg_1) //self.msg_1.text = data.conv_msg self.msg_2.hidden = true self.profilepic_2.hidden = true } else { heightForView(data.conv_msg, label: self.msg_2) //self.msg_2.text = data.conv_msg self.msg_1.hidden = true self.profilepic_1.hidden = true } } } }
mit
62f886f80789a7974a454aac8405c45f
27.116883
82
0.596118
4.014842
false
false
false
false
mitchtreece/Bulletin
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UITransition/Transitions/UICoverTransition.swift
1
4268
// // UICoverTransition.swift // Espresso // // Created by Mitch Treece on 6/26/18. // import UIKit /** A covering view controller transition. */ public class UICoverTransition: UITransition { /** The covered view's alpha to animate to while transitioning; _defaults to 0.7_. */ public var coveredViewAlpha: CGFloat /** The amount to move the covered view while transitioning; _defaults to 0_. */ public var coveredViewParallaxAmount: CGFloat /** Initializes the transition with parameters. - Parameter coveredViewAlpha: The covered view's alpha to animate to while transitioning; _defaults to 0.7_. - Parameter coveredViewParallaxAmount: The amount to move the covered view while transitioning; _defaults to 0_. */ public init(coveredViewAlpha: CGFloat = 0.7, coveredViewParallaxAmount: CGFloat = 0) { self.coveredViewAlpha = coveredViewAlpha self.coveredViewParallaxAmount = coveredViewParallaxAmount } override public func transitionController(for transitionType: TransitionType, info: Info) -> UITransitionController { let isPresentation = (transitionType == .presentation) let settings = self.settings(for: transitionType) return isPresentation ? _present(with: info, settings: settings) : _dismiss(with: info, settings: settings) } private func _present(with info: Info, settings: Settings) -> UITransitionController { let sourceVC = info.sourceViewController let destinationVC = info.destinationViewController let container = info.transitionContainerView let context = info.context return UITransitionController(setup: { destinationVC.view.transform = self.boundsTransform( in: container, direction: settings.direction.reversed() ) container.addSubview(destinationVC.view) }, animations: { UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), { sourceVC.view.alpha = self.coveredViewAlpha sourceVC.view.transform = self.translation( self.coveredViewParallaxAmount, direction: settings.direction ) destinationVC.view.transform = .identity }) }, completion: { sourceVC.view.alpha = 1 sourceVC.view.transform = .identity context.completeTransition(!context.transitionWasCancelled) }) } private func _dismiss(with info: Info, settings: Settings) -> UITransitionController { let sourceVC = info.sourceViewController let destinationVC = info.destinationViewController let container = info.transitionContainerView let context = info.context return UITransitionController(setup: { destinationVC.view.frame = context.finalFrame(for: destinationVC) destinationVC.view.alpha = self.coveredViewAlpha destinationVC.view.transform = self.translation( self.coveredViewParallaxAmount, direction: settings.direction.reversed() ) container.insertSubview(destinationVC.view, belowSubview: sourceVC.view) }, animations: { UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), { sourceVC.view.transform = self.boundsTransform( in: container, direction: settings.direction ) destinationVC.view.alpha = 1 destinationVC.view.transform = .identity }) }, completion: { sourceVC.view.alpha = 1 sourceVC.view.transform = .identity context.completeTransition(!context.transitionWasCancelled) }) } }
mit
5afa27fd6bd2d4d192607497c03431f1
33.144
121
0.581303
5.705882
false
false
false
false
wortman/stroll_safe_ios
Stroll Safe/Passcode.swift
1
1845
// // Passcode.swift // Stroll Safe // // Created by Noah Prince on 3/25/15. // Copyright (c) 2015 Stroll Safe. All rights reserved. // import Foundation import CoreData import UIKit public class Passcode: NSManagedObject { enum PasscodeError: ErrorType { case NoResultsFound } @NSManaged var passcode: String /** Gets the stored passcode for the given managed object context :param: managedObjectContext the managed object context */ class func get(managedObjectContext: NSManagedObjectContext) throws -> String { let fetchRequest = NSFetchRequest(entityName: "Passcode") var fetchResults: [Passcode] do { fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Passcode] } catch let fetchError as NSError { print("fetch Passcode error: \(fetchError.localizedDescription)") throw fetchError } if let result = fetchResults.first { return result.passcode } else { throw PasscodeError.NoResultsFound } } /** Sets the stored passcode for the given managed object context :param: password the passcode :param: managedObjectContext the managed object context */ class func set(passcode: String, managedObjectContext: NSManagedObjectContext) { // Store the password let newItem = NSEntityDescription.insertNewObjectForEntityForName("Passcode", inManagedObjectContext: managedObjectContext) as! Passcode do { try managedObjectContext.save() } catch let error as NSError { NSLog("Unresolved error while storing password \(error), \(error.userInfo)") abort() } newItem.passcode = passcode } }
apache-2.0
f3965f0f6452c412e16198557e53cb5e
29.245902
144
0.646612
5.607903
false
false
false
false
nanoxd/Bourne
Sources/JSON/JSON+String.swift
1
522
import Foundation extension JSON { public var string: String? { guard let object = object else { return nil } var value: String? = nil switch object { case is String: value = object as? String case is NSDecimalNumber: value = (object as? NSDecimalNumber)?.stringValue case is NSNumber: value = (object as? NSNumber)?.stringValue default: break } return value } }
mit
bbb3d6b5389ff6ef978870d08a8e27dd
21.695652
61
0.521073
5.381443
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Utilities/JSONParseHelper.swift
1
12916
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class JSONParseHelper: NSObject { /** This method takes the response data from Worklight and creates and returns a Swifty JSON Object - parameter response: the response data from Worklight - returns: The swift JSON objects created */ class func createJSONObject(response: WLResponse!) -> JSON{ let responseJson = response.getResponseJson() if(responseJson != nil){ if let resultString = responseJson["result"] as? NSString{ let dataFromString = resultString.dataUsingEncoding(NSUTF8StringEncoding) return JSON(data: dataFromString!); } else{ let resultString = "bad json" let dataFromString = resultString.dataUsingEncoding(NSUTF8StringEncoding) return JSON(data: dataFromString!); } } else{ let resultString = "bad json" let dataFromString = resultString.dataUsingEncoding(NSUTF8StringEncoding) return JSON(data: dataFromString!); } } /** This method is called by the HomeViewMetadataManager class. It calls the parseJSON method to get respective ItemMetaDataObject arrays based on the key it provides to this method. It then creates a dictionary with keys that correspeond to the ItemMetaDataObject arrays. - parameter json: the json received from the Worklight call. - returns: a dictionary with keys, featured, recommended, and all that correspond to ItemMetaDataObject arrays for those respective collectionviews. */ class func parseHomeViewMetadataJSON(response: WLResponse!) -> Dictionary<String, [ItemMetaDataObject]> { let json = createJSONObject(response) var parsedDictionary = Dictionary<String, [ItemMetaDataObject]>() let featuredItemsArray : [ItemMetaDataObject] = parseHomeJSON(json, key: "featured") let recommendedItemsArray : [ItemMetaDataObject] = parseHomeJSON(json, key: "recommended") let allItemsArray : [ItemMetaDataObject] = parseHomeJSON(json, key: "all") parsedDictionary["featured"] = featuredItemsArray parsedDictionary["recommended"] = recommendedItemsArray parsedDictionary["all"] = allItemsArray return parsedDictionary } /** This method parses the json received from a Worklight call. It uses the SwiftyJSON framework to help with the parsing of the json. After it is finished parsing the json it returns an array of ItemMetaDataObject objects to be used as data for the featured carousel collection view of the browse view controller. - parameter json: the swifyy json object created by the method that called this method - returns: an array of ItemMetaDataObject objects parsed from the received json */ class func parseHomeJSON(json: JSON, key : NSString) -> [ItemMetaDataObject]{ var itemsArray = [ItemMetaDataObject]() if let jSONArray = json["\(key)"].array { for item in jSONArray{ itemsArray.append(self.createItemMetaDataObject(item)) } } return itemsArray } /** This method creates an ItemMetaDataObject based on the json parameter it recieves. This method is called from the parseJSON method. - parameter item: a parse json item from the parseJSON method. - returns: an ItemMetaDataObject created from the item json parameter */ class private func createItemMetaDataObject(item : JSON) -> ItemMetaDataObject{ let itemMetaDataObject = ItemMetaDataObject() if let id = item["_id"].string{ itemMetaDataObject.id = id } if let rev = item["rev"].string{ itemMetaDataObject.rev = rev } if let type = item["type"].string { itemMetaDataObject.type = type } if let imageUrl = item["imageUrl"].string { itemMetaDataObject.determineImageUrl(imageUrl) } return itemMetaDataObject } /** This method is used to massage the data received from Worklight to prepare it for the format of json that the hybrid view is expecting - parameter response: the response from Worklight - returns: the massaged json that the hybrid view is expecting */ class func massageProductDetailJSON(response: WLResponse!) -> JSON{ //parse departmentName var json = createJSONObject(response) if let departmentName = json["departmentObj"]["title"].string { json["location"] = JSON(departmentName) } //parse imageUrl var path : NSString! if let imagePath = json["imageUrl"].string { path = imagePath let imageUrl = WLProcedureCaller.createImageUrl(path) json["imageUrl"] = JSON(imageUrl) } //parse price let currencySymbol = NSLocalizedString("$", comment: "Currency Symbol, for example $") if let priceRaw = json["priceRaw"].double { let price = "\(currencySymbol)\(priceRaw)" json["price"] = JSON(price) } //parse salePrice if let salePriceRaw = json["salePriceRaw"].double { let salePrice = "\(currencySymbol)\(salePriceRaw)" json["salePrice"] = JSON(salePrice) } //parse colorOptions if let colorOptionsArray = json["colorOptions"].array { let numberOfColorOptions = colorOptionsArray.count for(var i : Int = 0; i<numberOfColorOptions; i++){ if let path = json["colorOptions"][i]["url"].string{ let imageUrl = WLProcedureCaller.createImageUrl(path) json["colorOptions"][i]["url"] = JSON(imageUrl) } } json["option"]["name"] = JSON("Size") } return json } /** This method parses the json that represents the default lists received from Worklight. It first calls the createJSON object to create a swifty json object, it then loops through and parses each list in the json by calling the parseList method. - parameter response: the response json received from Worklight */ class func parseDefaultListJSON(response: WLResponse!){ let json = createJSONObject(response) if let listArray = json.array { for listJSON in listArray{ parseList(listJSON) } } } /** This method parses a swifty json object that represents a list that has products. It first parses the name of the list and adds a list with this name to Realm by calling the createList method of RealmHelper. It then goes through each product of the list and calls the parseProduct method to create a realm product object from the product swifty json. It then adds this realm product object to the Realm list object. - parameter listJSON: the json representing the list being parsed. */ class private func parseList(listJSON : JSON){ if let name = listJSON["name"].string{ if(RealmHelper.createList(name) == true){ let list = RealmHelper.getListWithName(name) if let productsArray = listJSON["products"].array{ for productJSON in productsArray{ let product = parseProduct(productJSON) RealmHelper.addProductToList(list, product: product) } } } } } /** This method takes a switfy json object that represents a product and parses this json into a Realm product object - parameter productJSON: the swifty json that represents a product - returns: the Realm product object parsed from the switfy json */ class func parseProduct(productJSON : JSON) -> Product{ let product : Product = Product() if let id = productJSON["_id"].string{ product.id = id } if let name = productJSON["name"].string{ product.name = name } if let rev = productJSON["rating"].int { product.rev = String(rev) } if let imageUrl = productJSON["imageUrl"].string { product.determineImageUrl(imageUrl) } if let price = productJSON["priceRaw"].double { product.price = price } if let salePrice = productJSON["salePriceRaw"].double { product.salePrice = salePrice } if let departmentName = productJSON["departmentObj"]["title"].string { product.departmentName = departmentName } if let departmentId = productJSON["departmentObj"]["_id"].string { product.departmentId = departmentId } return product } /** This method parses the response json received from Worklight and returns an array of department id's - parameter response: the response json received from Worklight - returns: an array of department id's parsed from the response json */ class func parseAllDepartments(response: WLResponse!)->Array<String> { var json = createJSONObject(response) var departmentArray : Array<String> = Array<String>() if let departmentCount = json.array?.count { for(var i = 0; i<departmentCount; i++){ if let departmentId = json[i]["_id"].string{ departmentArray.append(departmentId) } } } return departmentArray } /** This method parses the response json received from Worklight and returns a Bool representing if a product is available or not - parameter response: the response json received - returns: a Bool representing if a product is available or not */ class func parseAvailabilityJSON(response: WLResponse!) -> Int{ let responseJson = response.getResponseJson() as Dictionary //0 false, 1 true if let resultString = responseJson["result"]?.integerValue { return resultString } else{ return 2 //if there is no information about availability } } /** This method takes in response Json receieved from the "submitAuthentication" Worklight procedure call when the call succeeded and parses the userId from the response json and then returns this userId as a string - parameter response: - returns: */ class func parseUserId(response : WLResponse) -> String{ let responseJson = response.getResponseJson() as NSDictionary if let userId = responseJson["result"] as? String{ return userId } else{ return NSLocalizedString("userId", comment:"") } } /** This method parses the response JSON recieved from the "submitAuthentication" Worklight procedure call when the call failed and then parses this response to figure out why the call failed. It returns a string representing an error message. - parameter response: - returns: */ class func parseLoginFailureResponse(response : WLResponse!) -> String{ response.getResponseJson() let responseJson = response.getResponseJson() if(responseJson != nil){ if let onAuthRequired = responseJson["onAuthRequired"] as? NSDictionary { if let errorMessage = onAuthRequired["errorMessage"] as? NSString { return errorMessage as String } else{ return NSLocalizedString("Server error", comment:"") } } else{ return NSLocalizedString("Server error", comment:"") } } else{ return NSLocalizedString("Server error", comment:"") } } }
epl-1.0
859d15ffb33bd1cbc652a2c19d7178fd
32.545455
419
0.589779
5.550064
false
false
false
false
shaoyihe/100-Days-of-IOS
07 - PASSING DATA TO ANOTHER VIEW/PROJECT 07 - PASSING DATA TO ANOTHER VIEW/FirstViewController.swift
1
816
// // ViewController.swift // PROJECT 07 - PASSING DATA TO ANOTHER VIEW // // Created by heshaoyi on 3/6/16. // Copyright © 2016 heshaoyi. All rights reserved. // import UIKit class FirstViewController: UIViewController { @IBOutlet var textView: UITextView! override func loadView() { super.loadView() automaticallyAdjustsScrollViewInsets = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "SecondView" { let secondVC = segue.destinationViewController as! SecondViewController secondVC.text = textView.text } } }
mit
da7017eef28ba3221196330b9ce1022b
23.69697
82
0.660123
4.909639
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Common/UI/VIews/BorderedLabel.swift
2
1112
// // BorderedLabel.swift // SmartReceipts // // Created by Bogdan Evsenev on 15/08/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import UIKit class BorderedLabel: UILabel { var textInsets: UIEdgeInsets = .init(top: 4, left: 8, bottom: 4, right: 8) { didSet { setNeedsDisplay() } } override func drawText(in rect: CGRect) { guard text?.isEmpty == false else { super.drawText(in: rect); return } super.drawText(in: rect.inset(by: textInsets)) } override func sizeThatFits(_ size: CGSize) -> CGSize { var superSize = super.sizeThatFits(size) superSize.height += textInsets.top + textInsets.bottom superSize.width += textInsets.left + textInsets.right return superSize } override var intrinsicContentSize: CGSize { guard text?.isEmpty == false else { return super.intrinsicContentSize } var size = super.intrinsicContentSize size.height += textInsets.top + textInsets.bottom size.width += textInsets.left + textInsets.right return size } }
agpl-3.0
313883e53ca7fbb7191770da9bdea305
28.236842
80
0.645365
4.497976
false
false
false
false
shshalom/FayeSwift
Sources/WebsocketTransport.swift
1
2081
// // WebsocketTransport.swift // Pods // // Created by Haris Amin on 2/20/16. // // import Foundation import Starscream internal class WebsocketTransport: Transport, WebSocketDelegate, WebSocketPongDelegate { var urlString:String? var webSocket:WebSocket? internal weak var delegate:TransportDelegate? convenience required internal init(url: String) { self.init() self.urlString = url } func openConnection() { self.closeConnection() self.webSocket = WebSocket(url: NSURL(string:self.urlString!)!) if let webSocket = self.webSocket { webSocket.delegate = self webSocket.pongDelegate = self webSocket.connect() print("Faye: Opening connection") } } func closeConnection() { print("Faye: Closing connection") if let webSocket = self.webSocket { webSocket.delegate = nil webSocket.disconnect(forceTimeout: 0) self.webSocket = nil } } func writeString(aString:String) { self.webSocket?.writeString(aString) } func sendPing(data: NSData, completion: (() -> ())? = nil) { self.webSocket?.writePing(data, completion: completion) } func isConnected() -> (Bool) { return self.webSocket?.isConnected ?? false } // MARK: Websocket Delegate internal func websocketDidConnect(socket: WebSocket) { self.delegate?.didConnect() } internal func websocketDidDisconnect(socket: WebSocket, error: NSError?) { if error == nil { self.delegate?.didDisconnect(NSError(error: .LostConnection)) } else { self.delegate?.didFailConnection(error) } } internal func websocketDidReceiveMessage(socket: WebSocket, text: String) { self.delegate?.didReceiveMessage(text) } // MARK: TODO internal func websocketDidReceiveData(socket: WebSocket, data: NSData) { print("Faye: Received data: \(data.length)") //self.socket.writeData(data) } // MARK: WebSocket Pong Delegate internal func websocketDidReceivePong(socket: WebSocket) { self.delegate?.didReceivePong() } }
mit
8f1678607e9d12b663c55c4c5e5ed15e
23.494118
88
0.676598
4.456103
false
false
false
false
mauryat/firefox-ios
ClientTests/MockProfile.swift
1
6946
/* 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/. */ @testable import Client import Foundation import Account import ReadingList import Shared import Storage import Sync import XCTest import Deferred open class MockSyncManager: SyncManager { open var isSyncing = false open var lastSyncFinishTime: Timestamp? open var syncDisplayState: SyncDisplayState? open func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return deferMaybe(true) } private func completedWithStats(collection: String) -> Deferred<Maybe<SyncStatus>> { return deferMaybe(SyncStatus.completed(SyncEngineStatsSession(collection: collection))) } open func syncClients() -> SyncResult { return completedWithStats(collection: "mock_clients") } open func syncClientsThenTabs() -> SyncResult { return completedWithStats(collection: "mock_clientsandtabs") } open func syncHistory() -> SyncResult { return completedWithStats(collection: "mock_history") } open func syncLogins() -> SyncResult { return completedWithStats(collection: "mock_logins") } open func syncEverything(why: SyncReason) -> Success { return succeed() } open func syncNamedCollections(why: SyncReason, names: [String]) -> Success { return succeed() } open func beginTimedSyncs() {} open func endTimedSyncs() {} open func applicationDidBecomeActive() { self.beginTimedSyncs() } open func applicationDidEnterBackground() { self.endTimedSyncs() } open func onNewProfile() { } open func onAddedAccount() -> Success { return succeed() } open func onRemovedAccount(_ account: FirefoxAccount?) -> Success { return succeed() } open func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return deferMaybe(true) } } open class MockTabQueue: TabQueue { open func addToQueue(_ tab: ShareItem) -> Success { return succeed() } open func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> { return deferMaybe(ArrayCursor<ShareItem>(data: [])) } open func clearQueuedTabs() -> Success { return succeed() } } open class MockPanelDataObservers: PanelDataObservers { override init(profile: Profile) { super.init(profile: profile) self.activityStream = MockActivityStreamDataObserver(profile: profile) } } open class MockActivityStreamDataObserver: DataObserver { public var profile: Profile public weak var delegate: DataObserverDelegate? init(profile: Profile) { self.profile = profile } public func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topsites: Bool) { } } open class MockProfile: Profile { // Read/Writeable properties for mocking public var recommendations: HistoryRecommendations public var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations public var files: FileAccessor public var history: BrowserHistory & SyncableHistory & ResettableSyncStorage public var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage public var syncManager: SyncManager! public lazy var panelDataObservers: PanelDataObservers = { return MockPanelDataObservers(profile: self) }() var db: BrowserDB fileprivate let name: String = "mockaccount" init() { files = MockFiles() syncManager = MockSyncManager() logins = MockLogins(files: files) db = BrowserDB(filename: "mock.db", files: files) places = SQLiteHistory(db: self.db, prefs: MockProfilePrefs()) recommendations = places history = places } public func localName() -> String { return name } public func reopen() { } public func shutdown() { } public var isShutdown: Bool = false public var favicons: Favicons { return self.places } lazy public var queue: TabQueue = { return MockTabQueue() }() lazy public var metadata: Metadata = { return SQLiteMetadata(db: self.db) }() lazy public var isChinaEdition: Bool = { return Locale.current.identifier == "zh_CN" }() lazy public var certStore: CertStore = { return CertStore() }() lazy public var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & SyncableBookmarks & LocalItemSource & MirrorItemSource & ShareToDestination = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. let p = self.places return MergedSQLiteBookmarks(db: self.db) }() lazy public var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs, files: self.files) }() lazy public var prefs: Prefs = { return MockProfilePrefs() }() lazy public var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() lazy public var recentlyClosedTabs: ClosedTabsStore = { return ClosedTabsStore(prefs: self.prefs) }() internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() fileprivate lazy var syncCommands: SyncCommands = { return SQLiteRemoteClientsAndTabs(db: self.db) }() public let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() var account: FirefoxAccount? public func hasAccount() -> Bool { return account != nil } public func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.none } public func getAccount() -> FirefoxAccount? { return account } public func setAccount(_ account: FirefoxAccount) { self.account = account self.syncManager.onAddedAccount() } public func flushAccount() {} public func removeAccount() { let old = self.account self.account = nil self.syncManager.onRemovedAccount(old) } public func getClients() -> Deferred<Maybe<[RemoteClient]>> { return deferMaybe([]) } public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return deferMaybe([]) } public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return deferMaybe([]) } public func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return deferMaybe(0) } public func sendItems(_ items: [ShareItem], toClients clients: [RemoteClient]) -> Deferred<Maybe<SyncStatus>> { return deferMaybe(SyncStatus.notStarted(.offline)) } }
mpl-2.0
923f0fc27dd9b06e3f5ed8fe69513618
28.683761
162
0.675641
5.107353
false
false
false
false
liushuaikobe/fargo
fargo/TcnFargoTask.swift
1
1314
// // TcnFargoTask.swift // fargo // // Created by Shuai Liu on 16/1/8. // Copyright © 2016年 vars.me. All rights reserved. // import Foundation public class TcnFargoTask: FargoTask { let api_key: String public init(_ apiKey: String) { api_key = apiKey } override func apiURL() -> String { return "http://api.t.sina.com.cn/short_url/shorten.json" } override func httpMethod() -> FargoHTTPMethod { return .GET } override func getParams(url: String?) -> [String : String]? { if let param = url { return ["source": api_key, "url_long": param] } return nil } override func parseResult(data: NSData?) -> String? { if let result = data { do { if let json = try NSJSONSerialization.JSONObjectWithData(result, options: []) as? [[String: AnyObject]] { if let firstResult = json.first { return firstResult["url_short"] as? String } else { return nil } } else { return nil } } catch { return nil } } return nil } }
gpl-3.0
1570173d1b8fe6a4d466cbc038586d6c
23.754717
121
0.478261
4.552083
false
false
false
false
eggswift/ESTabBarController
ESTabBarControllerExample/ESTabBarControllerExample/ExampleProvider.swift
1
30657
// // ExampleProvider.swift // ESTabBarControllerExample // // Created by lihao on 2017/2/9. // Copyright © 2018年 Egg Swift. All rights reserved. // import UIKit import ESTabBarController enum ExampleProvider { static func systemStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.tabBar.shadowImage = nil tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func mixtureStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func systemMoreStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = UITabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = UITabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = UITabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func customMoreStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = ESTabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = ESTabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = ESTabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func mixtureMoreStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = UITabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = ESTabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = UITabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func navigationWithTabbarStyle() -> ExampleNavigationController { let tabBarController = ExampleProvider.customStyle() let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func tabbarWithNavigationStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) let n1 = ExampleNavigationController.init(rootViewController: v1) let n2 = ExampleNavigationController.init(rootViewController: v2) let n3 = ExampleNavigationController.init(rootViewController: v3) let n4 = ExampleNavigationController.init(rootViewController: v4) let n5 = ExampleNavigationController.init(rootViewController: v5) v1.title = "Home" v2.title = "Find" v3.title = "Photo" v4.title = "List" v5.title = "Me" tabBarController.viewControllers = [n1, n2, n3, n4, n5] return tabBarController } static func customColorStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customBouncesStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customBackgroundColorStyle(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customHighlightableStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customIrregularityStyle(delegate: UITabBarControllerDelegate?) -> ExampleNavigationController { let tabBarController = ESTabBarController() tabBarController.delegate = delegate tabBarController.title = "Irregularity" tabBarController.tabBar.shadowImage = UIImage(named: "transparent") tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark") tabBarController.shouldHijackHandler = { tabbarController, viewController, index in if index == 2 { return true } return false } tabBarController.didHijackHandler = { [weak tabBarController] tabbarController, viewController, index in DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet) let takePhotoAction = UIAlertAction(title: "Take a photo", style: .default, handler: nil) alertController.addAction(takePhotoAction) let selectFromAlbumAction = UIAlertAction(title: "Select from album", style: .default, handler: nil) alertController.addAction(selectFromAlbumAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) tabBarController?.present(alertController, animated: true, completion: nil) } } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleIrregularityContentView(), title: nil, image: UIImage(named: "photo_verybig"), selectedImage: UIImage(named: "photo_verybig")) v4.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customTipsStyle(delegate: UITabBarControllerDelegate?) -> ExampleNavigationController { let tabBarController = ESTabBarController() tabBarController.delegate = delegate tabBarController.title = "Irregularity" tabBarController.tabBar.shadowImage = UIImage(named: "transparent") tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark") let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleTipsContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func systemRemindStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v1.tabBarItem.badgeValue = "New" v2.tabBarItem.badgeValue = "99+" v3.tabBarItem.badgeValue = "1" if let tabBarItem = v3.tabBarItem as? ESTabBarItem { tabBarItem.badgeColor = UIColor.blue } v4.tabBarItem.badgeValue = "" v5.tabBarItem.badgeValue = nil tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customRemindStyle() -> UITabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) if let tabBarItem = v1.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "New" } if let tabBarItem = v2.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "99+" } if let tabBarItem = v3.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "1" tabBarItem.badgeColor = UIColor.blue } if let tabBarItem = v4.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "" } if let tabBarItem = v5.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = nil } tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customAnimateRemindStyle(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customAnimateRemindStyle2(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customAnimateRemindStyle3(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func lottieSytle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateContentView(), title: nil, image: nil, selectedImage: nil) v4.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } }
mit
7cc7226445b12f114829e10c0442f50b
58.063584
205
0.675214
4.589609
false
false
false
false
GiorgioNatili/pokedev
Pokedev/PokemonDetails/WireFrame/PokemonDetailsWireFrame.swift
1
1213
// // Created by Benjamin Soung // Copyright (c) 2016 Benjamin Soung. All rights reserved. // import Foundation class PokemonDetailsWireFrame: PokemonDetailsWireFrameProtocol { class func presentPokemonDetailsModule(fromView view: AnyObject) { // Generating module components var view: PokemonDetailsViewProtocol = PokemonDetailsView() var presenter: protocol<PokemonDetailsPresenterProtocol, PokemonDetailsInteractorOutputProtocol> = PokemonDetailsPresenter() var interactor: PokemonDetailsInteractorInputProtocol = PokemonDetailsInteractor() var APIDataManager: PokemonDetailsAPIDataManagerInputProtocol = PokemonDetailsAPIDataManager() var localDataManager: PokemonDetailsLocalDataManagerInputProtocol = PokemonDetailsLocalDataManager() var wireFrame: PokemonDetailsWireFrameProtocol = PokemonDetailsWireFrame() // Connecting view.presenter = presenter presenter.view = view presenter.wireFrame = wireFrame presenter.interactor = interactor interactor.presenter = presenter interactor.APIDataManager = APIDataManager interactor.localDatamanager = localDataManager } }
unlicense
5dc8fd04634de69319cf978508fb0bdd
40.862069
132
0.756801
6.814607
false
false
false
false
digices-llc/paqure-ios-framework
Paqure/AppManager.swift
1
3935
// // AppManager.swift // Paqure // // Created by Linguri Technology on 7/19/16. // Copyright © 2016 Digices. All rights reserved. // import UIKit protocol AppManagerDelegate { func appObjectSynced(success : Bool) } public class AppManager { public static var sharedInstance : AppManager = AppManager() var controller : AppManagerDelegate? var object : App = App() var source : Source = Source.DEFAULT let url = NSURL(string: "https://www.digices.com/api/app.php") // stubs for localization keys let v = NSLocalizedString("version", comment: "The version release of the application") let c = NSLocalizedString("copyright", comment: "Legal term for copyrighted work") let m = NSLocalizedString("loading", comment: "The application is loading") let u = NSLocalizedString("update_available", comment: "An update to the application version is available.") let r = NSLocalizedString("ready", comment: "The UI is ready to continue") let e = NSLocalizedString("error", comment: "An error has occurred") private init() { if self.pullFromLocal() == true { self.source = Source.LOCAL } else { self.saveToLocal() } self.pushToRemote() } func setController(controller: AppManagerDelegate) { self.controller = controller } func pullFromLocal() -> Bool { let storedObject = defaults.objectForKey("app") if let retrievedObject = storedObject as? NSData { if let unarchivedObject = NSKeyedUnarchiver.unarchiveObjectWithData(retrievedObject) { if let app = unarchivedObject as? App { self.object = app return true } else { return false } } else { return false } } else { return false } } func pushToRemote() { let request = NSMutableURLRequest(URL: self.url!) request.HTTPMethod = "POST" request.HTTPBody = self.object.encodedPostBody() let task = session.dataTaskWithRequest(request, completionHandler: receiveReply) task.resume() } func receiveReply(data : NSData?, response: NSURLResponse?, error: NSError?) { // initialize parameter to pass to delegate var success : Bool = false if let data = data { do { let parsedObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) if let parsedApp = parsedObject["app"] { if let app = parsedApp as? NSDictionary { let remoteApp = App(dict: app) if remoteApp.id > 0 { self.object = remoteApp self.source = Source.REMOTE success = true } } else { print("object did not evaluate as dictionary") } } else { print("key \"app\" does not exist in data") } } catch { print("serialization failed") } } else { print("no data received") } NSOperationQueue.mainQueue().addOperationWithBlock({ if success == true { self.source = Source.SYNCED self.controller?.appObjectSynced(true) } else { self.controller?.appObjectSynced(false) } }) } func saveToLocal() { let data = NSKeyedArchiver.archivedDataWithRootObject(self.object) defaults.setObject(data, forKey: "app") self.source = Source.LOCAL } }
bsd-3-clause
a6600f4ea475d05c4cb91c117ba7df04
30.99187
112
0.542705
5.273458
false
false
false
false
yannickl/DynamicColor
Sources/Core/DynamicColor+RGBA.swift
1
3963
/* * DynamicColor * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(OSX) import AppKit #endif // MARK: RGBA Color Space public extension DynamicColor { /** Initializes and returns a color object using the specified opacity and RGB component values. Notes that values out of range are clipped. - Parameter r: The red component of the color object, specified as a value from 0.0 to 255.0. - Parameter g: The green component of the color object, specified as a value from 0.0 to 255.0. - Parameter b: The blue component of the color object, specified as a value from 0.0 to 255.0. - Parameter a: The opacity value of the color object, specified as a value from 0.0 to 255.0. The default value is 255. */ convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 255) { self.init(red: clip(r, 0, 255) / 255, green: clip(g, 0, 255) / 255, blue: clip(b, 0, 255) / 255, alpha: clip(a, 0, 255) / 255) } // MARK: - Getting the RGBA Components /** Returns the RGBA (red, green, blue, alpha) components. - returns: The RGBA components as a tuple (r, g, b, a). */ final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 #if os(iOS) || os(tvOS) || os(watchOS) getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #elseif os(OSX) guard let rgbaColor = self.usingColorSpace(.deviceRGB) else { fatalError("Could not convert color to RGBA.") } rgbaColor.getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #endif } #if os(iOS) || os(tvOS) || os(watchOS) /** The red component as CGFloat between 0.0 to 1.0. */ final var redComponent: CGFloat { return toRGBAComponents().r } /** The green component as CGFloat between 0.0 to 1.0. */ final var greenComponent: CGFloat { return toRGBAComponents().g } /** The blue component as CGFloat between 0.0 to 1.0. */ final var blueComponent: CGFloat { return toRGBAComponents().b } /** The alpha component as CGFloat between 0.0 to 1.0. */ final var alphaComponent: CGFloat { return toRGBAComponents().a } #endif // MARK: - Setting the RGBA Components /** Creates and returns a color object with the alpha increased by the given amount. - parameter amount: CGFloat between 0.0 and 1.0. - returns: A color object with its alpha channel modified. */ final func adjustedAlpha(amount: CGFloat) -> DynamicColor { let components = toRGBAComponents() let normalizedAlpha = clip(components.a + amount, 0.0, 1.0) return DynamicColor(red: components.r, green: components.g, blue: components.b, alpha: normalizedAlpha) } }
mit
cc2e7350b220c8e813921b0a726d2f12
32.302521
130
0.681302
3.8739
false
false
false
false
gottesmm/swift
benchmark/single-source/Integrate.swift
10
1923
//===--- Integrate.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // A micro-benchmark for recursive divide and conquer problems. // The program performs integration via Gaussian Quadrature class Integrate { static let epsilon = 1.0e-9 let fun: (Double) -> Double init (f: @escaping (Double) -> Double) { fun = f } private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double { let h = (r - l) / 2 let hh = h / 2 let c = l + h let fc = fun(c) let al = (fl + fc) * hh let ar = (fr + fc) * hh let alr = al + ar let error = abs(alr-a) if (error < Integrate.epsilon) { return alr } else { let a1 = recEval(c, fl:fc, r:r, fr:fr, a:ar) let a2 = recEval(l, fl:fl, r:c, fr:fc, a:al) return a1 + a2 } } @inline(never) func computeArea(_ left: Double, right: Double) -> Double { return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0) } } @inline(never) public func run_Integrate(_ N: Int) { let obj = Integrate(f: { x in (x*x + 1.0) * x}) let left = 0.0 let right = 10.0 let ref_result = 2550.0 let bound = 0.0001 var result = 0.0 for _ in 1...N { result = obj.computeArea(left, right:right) if abs(result - ref_result) > bound { break } } CheckResults(abs(result - ref_result) < bound, "Incorrect results in Integrate: abs(\(result) - \(ref_result)) > \(bound)") }
apache-2.0
28467d51f2670a5f69454b62686c38d7
27.279412
93
0.565783
3.415631
false
false
false
false
therealbnut/swift
stdlib/public/Platform/Platform.swift
2
13147
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public var noErr: OSStatus { return 0 } /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. @_fixed_layout public struct DarwinBoolean : ExpressibleByBooleanLiteral { var _value: UInt8 public init(_ value: Bool) { self._value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { return _value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension DarwinBoolean : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension DarwinBoolean : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension DarwinBoolean : Equatable {} public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool { return lhs.boolValue == rhs.boolValue } public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool { return x.boolValue } #endif //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// @_silgen_name("_swift_Platform_getErrno") func _swift_Platform_getErrno() -> Int32 @_silgen_name("_swift_Platform_setErrno") func _swift_Platform_setErrno(_: Int32) public var errno : Int32 { get { return _swift_Platform_getErrno() } set(val) { return _swift_Platform_setErrno(val) } } //===----------------------------------------------------------------------===// // stdio.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var stdin : UnsafeMutablePointer<FILE> { get { return __stdinp } set { __stdinp = newValue } } public var stdout : UnsafeMutablePointer<FILE> { get { return __stdoutp } set { __stdoutp = newValue } } public var stderr : UnsafeMutablePointer<FILE> { get { return __stderrp } set { __stderrp = newValue } } public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in vdprintf(Int32(fd), format, va_args) } } public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in return vsnprintf(ptr, len, format, va_args) } } #endif //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// #if !os(Windows) || CYGWIN @_silgen_name("_swift_Platform_open") func _swift_Platform_open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 #else @_silgen_name("_swift_Platform_open") func _swift_Platform_open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: Int32 ) -> Int32 #endif #if !os(Windows) || CYGWIN @_silgen_name("_swift_Platform_openat") func _swift_Platform_openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 #endif public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_Platform_open(path, oflag, 0) } #if !os(Windows) || CYGWIN public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_Platform_open(path, oflag, mode) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_Platform_openat(fd, path, oflag, 0) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_Platform_openat(fd, path, oflag, mode) } #else public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: Int32 ) -> Int32 { return _swift_Platform_open(path, oflag, mode) } #endif #if !os(Windows) || CYGWIN @_silgen_name("_swift_Platform_fcntl") internal func _swift_Platform_fcntl( _ fd: Int32, _ cmd: Int32, _ value: Int32 ) -> Int32 @_silgen_name("_swift_Platform_fcntlPtr") internal func _swift_Platform_fcntlPtr( _ fd: Int32, _ cmd: Int32, _ ptr: UnsafeMutableRawPointer ) -> Int32 public func fcntl( _ fd: Int32, _ cmd: Int32 ) -> Int32 { return _swift_Platform_fcntl(fd, cmd, 0) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ value: Int32 ) -> Int32 { return _swift_Platform_fcntl(fd, cmd, value) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ ptr: UnsafeMutableRawPointer ) -> Int32 { return _swift_Platform_fcntlPtr(fd, cmd, ptr) } #endif #if !os(Windows) || CYGWIN public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var S_IFWHT: mode_t { return mode_t(0o160000) } #endif public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var S_ISTXT: mode_t { return S_ISVTX } public var S_IREAD: mode_t { return S_IRUSR } public var S_IWRITE: mode_t { return S_IWUSR } public var S_IEXEC: mode_t { return S_IXUSR } #endif #else public var S_IFMT: Int32 { return Int32(0xf000) } public var S_IFREG: Int32 { return Int32(0x8000) } public var S_IFDIR: Int32 { return Int32(0x4000) } public var S_IFCHR: Int32 { return Int32(0x2000) } public var S_IFIFO: Int32 { return Int32(0x1000) } public var S_IREAD: Int32 { return Int32(0x0100) } public var S_IWRITE: Int32 { return Int32(0x0080) } public var S_IEXEC: Int32 { return Int32(0x0040) } #endif //===----------------------------------------------------------------------===// // ioctl.h //===----------------------------------------------------------------------===// #if !os(Windows) || CYGWIN @_silgen_name("_swift_Platform_ioctl") internal func _swift_Platform_ioctl( _ fd: CInt, _ request: UInt, _ value: CInt ) -> CInt @_silgen_name("_swift_Platform_ioctlPtr") internal func _swift_Platform_ioctlPtr( _ fd: CInt, _ request: UInt, _ ptr: UnsafeMutableRawPointer ) -> CInt public func ioctl( _ fd: CInt, _ request: UInt, _ value: CInt ) -> CInt { return _swift_Platform_ioctl(fd, request, value) } public func ioctl( _ fd: CInt, _ request: UInt, _ ptr: UnsafeMutableRawPointer ) -> CInt { return _swift_Platform_ioctlPtr(fd, request, ptr) } public func ioctl( _ fd: CInt, _ request: UInt ) -> CInt { return _swift_Platform_ioctl(fd, request, 0) } #endif //===----------------------------------------------------------------------===// // unistd.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func fork() -> Int32 { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func vfork() -> Int32 { fatalError("unavailable function can't be called") } #endif //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) } #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Windows) #if CYGWIN public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #else public var SIG_DFL: _crt_signal_t? { return nil } public var SIG_IGN: _crt_signal_t { return unsafeBitCast(1, to: _crt_signal_t.self) } public var SIG_ERR: _crt_signal_t { return unsafeBitCast(-1, to: _crt_signal_t.self) } #endif #else internal var _ignore = _UnsupportedPlatformError() #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// #if !os(Windows) || CYGWIN /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: UnsafeMutablePointer<sem_t>? { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) // The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS. return UnsafeMutablePointer<sem_t>(bitPattern: -1) #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) #elseif os(Windows) #if CYGWIN // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) #else _UnsupportedPlatformError() #endif #else _UnsupportedPlatformError() #endif } @_silgen_name("_swift_Platform_sem_open2") internal func _swift_Platform_sem_open2( _ name: UnsafePointer<CChar>, _ oflag: Int32 ) -> UnsafeMutablePointer<sem_t>? @_silgen_name("_swift_Platform_sem_open4") internal func _swift_Platform_sem_open4( _ name: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t>? public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32 ) -> UnsafeMutablePointer<sem_t>? { return _swift_Platform_sem_open2(name, oflag) } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t>? { return _swift_Platform_sem_open4(name, oflag, mode, value) } #endif //===----------------------------------------------------------------------===// // Misc. //===----------------------------------------------------------------------===// // FreeBSD defines extern char **environ differently than Linux. #if os(FreeBSD) || os(PS4) @_silgen_name("_swift_FreeBSD_getEnv") func _swift_FreeBSD_getEnv( ) -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>> public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _swift_FreeBSD_getEnv().pointee } #endif
apache-2.0
05a24e3d0a7a810f96631b60bbdafcbf
26.389583
127
0.597475
3.417468
false
false
false
false
Maxim-Inv/RealmS
Tests/Model/Model.swift
1
1994
// // Model.swift // RealmS // // Created by DaoNV on 3/14/16. // Copyright © 2016 Apple Inc. All rights reserved. // import RealmSwift import ObjectMapper @testable import RealmS class User: Object, Mappable { dynamic var id: String! dynamic var name: String? dynamic var address: Address? let dogs = List<Dog>() override class func primaryKey() -> String? { return "id" } convenience required init?(map: Map) { self.init() id <- map["id"] } func mapping(map: Map) { name <- map["name"] address <- map["address"] dogs <- map["dogs"] } } class Address: Object, Mappable { dynamic var street = "" dynamic var city = "" dynamic var country = "" dynamic var phone: Phone? let users = LinkingObjects(fromType: User.self, property: "address") convenience required init?(map: Map) { self.init() } func mapping(map: Map) { street <- map["street"] city <- map["city"] country <- map["country"] phone <- map["phone"] } } class Phone: Object, Mappable { enum PhoneType: String { case Work = "Work" case Home = "Home" } dynamic var number = "" dynamic var type = PhoneType.Home.rawValue let addresses = LinkingObjects(fromType: Address.self, property: "phone") convenience required init?(map: Map) { self.init() } func mapping(map: Map) { number <- map["number"] type <- map["type"] } } class Dog: Object, Mappable { dynamic var id: String! dynamic var name: String? dynamic var color: String? let users = LinkingObjects(fromType: User.self, property: "dogs") override class func primaryKey() -> String? { return "id" } convenience required init?(map: Map) { self.init() id <- map["id"] } func mapping(map: Map) { name <- map["name"] color <- map["color"] } }
mit
d865cd11b1d9129fb6cb2030b8d03967
19.546392
77
0.570998
3.978044
false
false
false
false
maicki/AsyncDisplayKit
examples/LayoutSpecExamples-Swift/Sample/OverviewCellNode.swift
12
1859
// // OverviewCellNode.swift // Sample // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // 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 // FACEBOOK 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 AsyncDisplayKit class OverviewCellNode: ASCellNode { let layoutExampleType: LayoutExampleNode.Type fileprivate let titleNode = ASTextNode() fileprivate let descriptionNode = ASTextNode() init(layoutExampleType le: LayoutExampleNode.Type) { layoutExampleType = le super.init() self.automaticallyManagesSubnodes = true titleNode.attributedText = NSAttributedString.attributedString(string: layoutExampleType.title(), fontSize: 16, color: .black) descriptionNode.attributedText = NSAttributedString.attributedString(string: layoutExampleType.descriptionTitle(), fontSize: 12, color: .lightGray) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let verticalStackSpec = ASStackLayoutSpec.vertical() verticalStackSpec.alignItems = .start verticalStackSpec.spacing = 5.0 verticalStackSpec.children = [titleNode, descriptionNode] return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 10), child: verticalStackSpec) } }
bsd-3-clause
5f726117226a14317c60b6b8dce5f59e
39.413043
151
0.762776
4.6475
false
false
false
false