hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
e650d88052e001e1c06116242bc4475bb7dab1cb
4,933
// // QueryAnimateVC.swift // SHKit // // Created by hsh on 2019/8/5. // Copyright © 2019 hsh. All rights reserved. // import UIKit class QueryAnimateVC: UIViewController,PayCheckDelegate,PayFuncDelegate { private var animaView = QueryCircleAnimateV() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white; animaView.center = self.view.center; animaView.bounds = CGRect(x: 0, y: 0, width: 70, height: 70); self.view.addSubview(animaView); let btn = UIButton() btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside); btn .setTitle("开始", for: .normal); self.view.addSubview(btn); btn.backgroundColor = UIColor.colorRGB(red: 99, green: 174, blue: 248); btn.setTitleColor(UIColor.white, for: .normal); btn.mas_makeConstraints { (maker) in maker?.bottom.mas_equalTo()(self.view)?.offset()(-20); maker?.centerX.mas_equalTo()(self.view); maker?.width.mas_equalTo()(100); maker?.height.mas_equalTo()(60); } let checkBtn = UIButton() checkBtn.setTitle("支付结果", for: .normal); checkBtn.backgroundColor = UIColor.colorRGB(red: 99, green: 174, blue: 248); checkBtn.addTarget(self, action: #selector(payCheck), for: .touchUpInside); self.view.addSubview(checkBtn); checkBtn.mas_makeConstraints { (maker) in maker?.bottom.mas_equalTo()(btn.mas_top)?.offset()(-10); maker?.centerX.with()?.height()?.mas_equalTo()(btn); maker?.width.height()?.mas_equalTo()(btn); } let payBtn = UIButton() payBtn.setTitle("发起支付", for: .normal); payBtn.backgroundColor = UIColor.colorRGB(red: 99, green: 174, blue: 248); payBtn.addTarget(self, action: #selector(payClick), for: .touchUpInside); self.view.addSubview(payBtn); payBtn.mas_makeConstraints { (maker) in maker?.bottom.mas_equalTo()(checkBtn.mas_top)?.offset()(-10); maker?.centerX.with()?.height()?.mas_equalTo()(btn); maker?.width.height()?.mas_equalTo()(btn); } } //发起支付 @objc private func payClick(){ let payV = PayFuncView() payV.foldRow = 3; PayCheckV.shared.payView = payV; payV.callPay(money: 100, orderNo: "12343", delegate: self); } //仅调起支付结果 @objc private func payCheck(){ PayCheckV.shared.payCalled = true; PayCheckV.shared.configOrder(orderNo: "12343", delegate: self); PayCheckV.shared.checkPayResult(suc: false,fromSDK: false); } //PayFuncDelegate func refreshPage(msg: String) { } func callPay(type: PayType, orderNo: String) { //获取支付参数, PayCheckV.shared.payCalled = true; PayCheckV.shared.configOrder(orderNo: "12343", delegate: self); (PayCheckV.shared.payView as! PayFuncView).dismissFromSuper(); } //自定义文案 func editPayTypeDatas(data: [PayTypeData]) -> [PayTypeData]? { for it in data { if it.type == PayType.ZhiFubao{ it.content = "使用花呗有优惠"; }else if it.type == PayType.WeChat{ it.content = "8.8你刷我买单"; }else if it.type == PayType.ApplePay{ it.content = "Apply返现1%"; }else if it.type == PayType.Union{ it.content = "银联支付立减5元" } } return data; } func payResult(suc: Bool, fromSDk: Bool) { PayCheckV.shared.checkPayResult(suc: suc,fromSDK: fromSDk); } //PayCheckDelegate func requestOrderPayResult(orderNo: String, first: Bool) { if first == false{ PayCheckV.shared.requestResult(success: false, first: first); }else{ PayCheckV.shared.requestResult(success: false, first: first); } } func checkResult(suc: Bool) { } func repayCalled() { payClick() } //动画状态轮转 @objc private func btnClick(sender:UIButton){ let title:String = (sender.titleLabel?.text!)!; if title == "开始"{ animaView.startLoadingAnimate(); sender .setTitle("成功", for: .normal); }else if title == "成功"{ animaView.showSuccessAnimate(); sender .setTitle("继续", for: .normal); }else if title == "继续"{ animaView.startLoadingAnimate(); sender .setTitle("失败", for: .normal); }else if title == "失败"{ animaView.showFailAnimate(); sender .setTitle("结束", for: .normal); }else if title == "结束"{ animaView.stopAnimate(); sender .setTitle("开始", for: .normal); } } }
30.450617
84
0.564971
d9b6a9b57571aec27305732fcb609d98c2c86d70
8,658
// // Created by yangentao on 2019/10/23. // Copyright (c) 2019 yangentao. All rights reserved. // import Foundation import Cocoa public var lParam: LinearParam { LinearParam() } open class LinearParam: LayoutParam { //对于VLinear, gravity只对水平方向有效 //对于HLinear, gravity只对竖直方向有效 public var gravity: Gravity = .fill //weight只有在height == 0 的情况下有效, //VLinear, weight是去除固定高度后, 剩余竖直空间除以所有子视图weight值相加, 再乘以当前视图的weight //w = (VHeight - sumFixHeight) / sumWeight * weight //存在weight的情况下, FILL会变成WRAP public var weight: CGFloat = 0 } public extension LinearParam { var gravityFill: LinearParam { self.gravity = .fill return self } var gravityCenter: LinearParam { self.gravity = .center return self } var gravityStart: LinearParam { self.gravity = .start return self } var gravityEnd: LinearParam { self.gravity = .end return self } @discardableResult func gravity(_ g: Gravity) -> LinearParam { self.gravity = g return self } @discardableResult func flex(_ n: CGFloat) -> LinearParam { self.weight = n return self } } public extension NSView { var linearParam: LinearParam { if let p = self.layoutParam as? LinearParam { return p } let pp = LinearParam() self.layoutParam = pp return pp } } public extension NSView { func linearV() -> LinearVer { self.add(view: LinearVer(frame: .zero)) } @discardableResult func linearV(_ block: (LinearVer) -> Void) -> LinearVer { self.add(view: LinearVer(frame: .zero), block: block) } func linearH() -> LinearHor { self.add(view: LinearHor(frame: .zero)) } @discardableResult func linearH(_ block: (LinearHor) -> Void) -> LinearHor { self.add(view: LinearHor(frame: .zero), block: block) } } public extension Linear { func linearV(param: LinearParam) -> LinearVer { self.add(view: LinearVer(frame: .zero), param: param) } func linearH(param: LinearParam) -> LinearHor { self.add(view: LinearHor(frame: .zero), param: param) } @discardableResult func linearV(_ param: LinearParam, block: (LinearVer) -> Void) -> LinearVer { let v = self.add(view: LinearVer(frame: .zero), param: param) block(v) return v } @discardableResult func linearH(_ param: LinearParam, block: (LinearHor) -> Void) -> LinearHor { let v = self.add(view: LinearHor(frame: .zero), param: param) block(v) return v } @discardableResult func emptyView(_ param: LinearParam) -> NSView { self.add(view: NSView(frame: .zero), param: param) } } open class Linear: LayoutCustom { fileprivate var linearSubviews: [NSView] { self.subViewsNeedLayout.filter { v in v.layoutParam is LinearParam } } open override var fittingSize: NSSize { let vs: [NSView] = self.linearSubviews if vs.isEmpty { return super.fittingSize } if self is LinearVer { var sumY: CGFloat = 0 var maxX: CGFloat = 0 var marginSumY: CGFloat = 0 for i in 0..<vs.count { let v: NSView = vs[i] let lp: LinearParam = v.linearParam let fitSz = v.fittingSize let mY = lp.marginTop + lp.marginBottom marginSumY += mY > 0 ? mY : 0 sumY += lp.height > 0 ? lp.height : fitSz.height maxX = max(maxX, lp.marginLeft + lp.marginRight + fitSz.width) } return NSSize(width: maxX + inset.left + inset.right, height: sumY + marginSumY + inset.top + inset.bottom) } else if self is LinearHor { var sumX: CGFloat = 0 var maxY: CGFloat = 0 var marginSumX: CGFloat = 0 for i in 0..<vs.count { let v: NSView = vs[i] let lp: LinearParam = v.linearParam let fitSz = v.fittingSize let mX = lp.marginLeft + lp.marginRight marginSumX += mX > 0 ? mX : 0 sumX += lp.width > 0 ? lp.width : fitSz.width maxY = max(maxY, lp.marginTop + lp.marginBottom + fitSz.height) } return NSSize(width: sumX + marginSumX + inset.left + inset.right, height: maxY + inset.top + inset.bottom) } else { return super.fittingSize } } } open class LinearVer: Linear { open override func onLayoutCustom() { println("LinearVer.onLayoutCustom() ") let vs: [NSView] = self.linearSubviews if vs.isEmpty { return } let selfBound = self.boundsInseted var rectList: [Rect] = [Rect](repeating: .unspec, count: vs.count) var weightSum: CGFloat = 0 for v: NSView in vs { let p = v.linearParam if p.weight > 0 { weightSum += p.weight } } var heightSum: CGFloat = 0 var marginVSum: CGFloat = 0 for i in 0..<vs.count { let v: NSView = vs[i] var r: Rect = rectList[i] let lp: LinearParam = v.linearParam let fitSz = v.fittingSize marginVSum += lp.marginTop + lp.marginBottom switch lp.gravity { case .fill: r.size.width = selfBound.width - lp.marginLeft - lp.marginRight r.origin.x = selfBound.minX + (selfBound.width - r.width) / 2 case .center: r.size.width = lp.width >= 0 ? lp.width : fitSz.width r.origin.x = selfBound.minX + (selfBound.width - r.width) / 2 break case .start: r.size.width = lp.width >= 0 ? lp.width : fitSz.width r.origin.x = selfBound.minX + lp.marginLeft break case .end: r.size.width = lp.width >= 0 ? lp.width : fitSz.width r.origin.x = selfBound.maxX - r.width - lp.marginRight break } if lp.weight <= 0 { r.size.height = lp.height >= 0 ? lp.height : fitSz.height heightSum += r.size.height } else { // weight > 0 //next ... } rectList[i] = r } if weightSum > 0 { var weightHeight: CGFloat = (selfBound.height - heightSum - marginVSum) / weightSum if weightHeight < 0 { weightHeight = 0 } for i in 0..<vs.count { let v: NSView = vs[i] let p = v.linearParam if p.weight > 0 { var r: Rect = rectList[i] r.size.height = weightHeight * p.weight rectList[i] = r } } } var top: CGFloat = selfBound.minY for i in 0..<vs.count { let v: NSView = vs[i] var r: Rect = rectList[i] let p = v.linearParam top += p.marginTop r.origin.y = top rectList[i] = r top += r.height + p.marginBottom } for i in 0..<vs.count { let v: NSView = vs[i] v.frame = rectList[i] } } } open class LinearHor: Linear { open override func onLayoutCustom() { let vs: [NSView] = self.linearSubviews if vs.isEmpty { return } let selfBound = self.boundsInseted var rectList: [Rect] = [Rect](repeating: .unspec, count: vs.count) var weightSum: CGFloat = 0 for v in vs { let p = v.linearParam if p.weight > 0 { weightSum += p.weight } } var widthSum: CGFloat = 0 var marginHSum: CGFloat = 0 for i in 0..<vs.count { let v: NSView = vs[i] var r: Rect = rectList[i] let lp: LinearParam = v.linearParam let fitSz = v.fittingSize marginHSum += lp.marginLeft + lp.marginRight switch lp.gravity { case .fill: r.size.height = selfBound.height - lp.marginTop - lp.marginBottom r.origin.y = selfBound.minY + (selfBound.height - r.height) / 2 break case .center: r.size.height = lp.height >= 0 ? lp.height : fitSz.height r.origin.y = selfBound.minY + (selfBound.height - r.height) / 2 break case .start: r.size.height = lp.height >= 0 ? lp.height : fitSz.height r.origin.y = selfBound.minY + lp.marginTop break case .end: r.size.height = lp.height >= 0 ? lp.height : fitSz.height r.origin.y = selfBound.maxY - r.height - lp.marginBottom break } if lp.weight <= 0 { r.size.width = lp.width >= 0 ? lp.width : fitSz.width widthSum += r.size.width } else { // weight > 0 //next ... } rectList[i] = r } if weightSum > 0 { var weightWidth: CGFloat = (selfBound.width - widthSum - marginHSum) / weightSum if weightWidth < 0 { weightWidth = 0 } for i in 0..<vs.count { let v: NSView = vs[i] let p = v.linearParam if p.weight > 0 { rectList[i].size.width = weightWidth * p.weight } } } else { //neve reach here } var left: CGFloat = selfBound.minX for i in 0..<vs.count { let v: NSView = vs[i] var r: Rect = rectList[i] let p = v.linearParam left += p.marginLeft r.origin.x = left rectList[i] = r left += r.width + p.marginRight } for i in 0..<vs.count { let v: NSView = vs[i] v.frame = rectList[i] } } } public extension LinearVer { @discardableResult func seprator() -> NSLabel { self.add(view: NSLabel(frame: .zero)) { b in b.linearParam.gravity(.fill).height(1).marginY(5) b.backColorLayer = .separatorColor } } } public extension LinearHor { @discardableResult func seprator() -> NSLabel { self.add(view: NSLabel(frame: .zero)) { b in b.linearParam.gravity(.fill).width(1).marginX(5) b.backColorLayer = .separatorColor } } }
23.527174
110
0.643798
b99e748c1226d9ada1e0d11b740890d91e4a27c9
1,689
// // EnableSettingCell.swift // CoreML-Classification-Comparison // // Created by Matthias Wagner on 20.06.18. // Copyright © 2018 Matthias Wagner. All rights reserved. // import UIKit import MBDataSource import ReactiveSwift import ReactiveCocoa class EnableSettingCell: UITableViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var valueSwitch: UISwitch! private var viewModel: FilterSettingsViewModel! private var valueProperty: MutableProperty<Bool>! func configure(viewModel: FilterSettingsViewModel, indexPath: IndexPath) { self.viewModel = viewModel switch viewModel.settingType! { case .modelImageSize: valueProperty = viewModel.settings.shouldUseModelImageSize titleLabel.text = Strings.EnableSettingCell.modelSizeDescription case .grayScale: valueProperty = viewModel.settings.shouldUseGrayscale titleLabel.text = Strings.EnableSettingCell.grayscaleDescription case .showScaledImage: valueProperty = viewModel.settings.shouldShowResizedImage titleLabel.text = Strings.EnableSettingCell.showResizedImagesDescription } valueSwitch.reactive.isOn <~ valueProperty.producer valueProperty <~ valueSwitch.reactive.isOnValues } } // MARK: - DataSource Extension extension EnableSettingCell { static var descriptor: CellDescriptor<FilterSettingsViewModel, EnableSettingCell> { return CellDescriptor("EnableSettingCell") .configure { (viewModel, cell, indexPath) in cell.configure(viewModel: viewModel, indexPath: indexPath) } } }
31.867925
87
0.721137
d90433cc56f45b1dbaa48b182e367c7fca64ae72
518
// // ViewController.swift // flowCoordinatorInvestigation // // Created by Adam Carlson on 7/18/18. // Copyright © 2018 adam. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.923077
80
0.677606
727802da78693698ea673142fca25333d690b20e
4,628
// // PhotoDetailViewController.swift // MyPhotoViewer // // Created by Amitai Blickstein on 9/23/17. // Copyright © 2017 Amitai Blickstein. All rights reserved. // import UIKit class PhotoDetailViewController: UIViewController { var photo: PhotoData? var imageView = UIImageView(image: Asset.placeholderIcon.image) var captionView = UITextView() var animator: UIDynamicAnimator? var imageInset: CGFloat = 5.0 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(named: .clouds).withAlphaComponent(0.4) setupImageView() setImage() setupTapToDismiss() setupCaptionView() animator = UIDynamicAnimator(referenceView: view) animator?.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let snapToCenter = UISnapBehavior(item: imageView, snapTo: view.center.offsetBy(dy: -50)) animator?.addBehavior(snapToCenter) } // MARK: UIImageView (photo) fileprivate func setupImageView() { imageView.frame = offScreenRect.insetBy(dx: imageInset, dy: imageInset) imageView.layer.cornerRadius = 3 imageView.layer.masksToBounds = true view.addSubview(imageView) } fileprivate func setImage() { if let photo = photo { do { try PhotoImageFetcher.image(forPhoto: photo, size: .full, completion: { self.imageView.image = $0 }) } catch { print(error.localizedDescription) } } } fileprivate var offScreenRect: CGRect { let fullscreenWidth = UIScreen.main.bounds.size.width let offscreenY = abs(UIScreen.main.bounds.maxY) * -2 return CGRect(x: 0, y: offscreenY, width: fullscreenWidth, height: fullscreenWidth) } // MARK: UITextView (title/caption) fileprivate func setupCaptionView() { view.addSubview(captionView) captionView.textContainer.lineBreakMode = .byWordWrapping captionView.textAlignment = .center captionView.text = photo?.title captionView.backgroundColor = Color(named: .pumpkin).withAlphaComponent(0.5) captionView.layer.cornerRadius = 5 captionView.layer.masksToBounds = true setupCaptionViewConstraints() captionView.alpha = 0 } fileprivate func setupCaptionViewConstraints() { captionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([captionViewLeadingConstraint, captionViewTrailingConstraint, captionViewHeightConstraint, imageCaptionBoundaryConstraint]) } fileprivate var captionViewLeadingConstraint: NSLayoutConstraint { return NSLayoutConstraint(item: captionView, attribute: .leading, relatedBy: .equal, toItem: imageView, attribute: .leading, multiplier: 1.0, constant: 20.0) } fileprivate var captionViewTrailingConstraint: NSLayoutConstraint { return NSLayoutConstraint(item: captionView, attribute: .trailing, relatedBy: .equal, toItem: imageView, attribute: .trailing, multiplier: 1.0, constant: -20.0) } fileprivate var captionViewHeightConstraint: NSLayoutConstraint { return NSLayoutConstraint(item: captionView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 26) } fileprivate var imageCaptionBoundaryConstraint: NSLayoutConstraint { return NSLayoutConstraint(item: captionView, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom, multiplier: 1.0, constant: 8.0) } fileprivate func setupTapToDismiss() { let tapToDismiss = UITapGestureRecognizer(target: self, action: #selector(dismissDetailView)) view.addGestureRecognizer(tapToDismiss) } @objc fileprivate func dismissDetailView() { animator?.removeAllBehaviors() let snapDownOffscreen = UISnapBehavior(item: imageView, snapTo: view.center.offsetBy(dy: 500)) animator?.addBehavior(snapDownOffscreen) presentingViewController?.dismiss(animated: true, completion: nil) } } // MARK: - UIDynamicAnimatorDelegate extension PhotoDetailViewController: UIDynamicAnimatorDelegate { func dynamicAnimatorDidPause(_ animator: UIDynamicAnimator) { UIView.animate(withDuration: 0.01, animations: { self.captionView.alpha = 1 }) } func dynamicAnimatorWillResume(_ animator: UIDynamicAnimator) { UIView.animate(withDuration: 0.01, animations: { self.captionView.alpha = 0 }) } } fileprivate extension CGPoint { func offsetBy(dx: CGFloat = 0, dy: CGFloat = 0) -> CGPoint { return CGPoint(x: x + dx, y: y + dy) } }
31.69863
102
0.718021
d7a1d1f1544cadd850d5aec700e495be14cdc929
494
class Solution { func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int { guard s > 0 && !nums.isEmpty else { return 0 } var res = Int.max var sum = 0 var left = 0 for (idx, num) in nums.enumerated() { sum += num while sum >= s { res = min(res, idx - left + 1) sum -= nums[left] left += 1 } } return res == Int.max ? 0 : res } }
24.7
57
0.394737
e0d2ed31300437ef490a35c74c8d690ce51085df
868
// // ReplyViewController.swift // Twitter // // Created by ruthie_berman on 10/1/17. // Copyright © 2017 ruthie_berman. All rights reserved. // import UIKit class ReplyViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.111111
106
0.673963
5677d21d6b3f0d96bdb6236409a94d4604f83b65
5,136
// // ViewController.swift // tip // // Created by Angela Dimon on 12/19/20. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var firstBox: UIView! @IBOutlet weak var secondBox: UIView! @IBOutlet weak var resetBox: UIView! @IBOutlet weak var partyField: UITextField! override func viewDidLoad() { super.viewDidLoad() // style view boxes firstBox.layer.borderWidth = 5 firstBox.layer.borderColor = UIColor.darkGray.cgColor firstBox.layer.cornerRadius = 25 secondBox.layer.borderWidth = 5 secondBox.layer.borderColor = UIColor.darkGray.cgColor secondBox.layer.cornerRadius = 25 resetBox.layer.borderWidth = 5 resetBox.layer.borderColor = UIColor.darkGray.cgColor resetBox.layer.cornerRadius = 25 // make the bill field the first responder billField.becomeFirstResponder() // customize currency for billField placeholder let currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.numberStyle = .currency // localize to current locale currencyFormatter.locale = Locale.current // update placeholder for billField billField.placeholder = currencyFormatter.string(from: NSNumber(value: 0))! } @IBAction func onTapReset(_ sender: Any) { // get defaults let defaults = UserDefaults.standard // set tip control bar titles tipControl.setTitle("\(15)%", forSegmentAt: 0) tipControl.setTitle("\(18)%", forSegmentAt: 1) tipControl.setTitle("\(20)%", forSegmentAt: 2) // reset defaults to common tip percentages defaults.set(15, forKey: "tip1") defaults.set(18, forKey: "tip2") defaults.set(20, forKey: "tip3") // clear billField and call calculateTip to clear tip and total labels billField.text = "" partyField.text = "1" self.calculateTip(UIView.self) } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func partyChange(_ sender: Any) { self.calculateTip(UITextField.self) } @IBAction func calculateTip(_ sender: Any) { // get defaults let defaults = UserDefaults.standard // get the bill amount from billField let bill = Double(billField.text!) ?? 0 let partySize = Double(partyField.text!) ?? 1 // get tip percentages from defaults let tip1 = defaults.double(forKey: "tip1") / 100 let tip2 = defaults.double(forKey: "tip2") / 100 let tip3 = defaults.double(forKey: "tip3") / 100 // set tip percentages let tipPercentages = [tip1, tip2, tip3] // calculate tip and total let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip // customize currency let currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.numberStyle = .currency // localize to current locale currencyFormatter.locale = Locale.current // update the tip and total labels tipLabel.text = currencyFormatter.string(from: NSNumber(value: tip/partySize))! totalLabel.text = currencyFormatter.string(from: NSNumber(value: total/partySize))! } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // update the tip amount from settings let defaults = UserDefaults.standard let tip1 = defaults.double(forKey: "tip1") / 100 let tip2 = defaults.double(forKey: "tip2") / 100 let tip3 = defaults.double(forKey: "tip3") / 100 // set tip control bar titles tipControl.setTitle("\(Int(tip1*100))%", forSegmentAt: 0) tipControl.setTitle("\(Int(tip2*100))%", forSegmentAt: 1) tipControl.setTitle("\(Int(tip3*100))%", forSegmentAt: 2) // dark mode let darkOn = defaults.bool(forKey: "darkOn") if darkOn { overrideUserInterfaceStyle = .dark } else { overrideUserInterfaceStyle = .light } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // calculate tip after returning from settings self.calculateTip(UIView.self) } // override func viewWillDisappear(_ animated: Bool) { // super.viewWillDisappear(animated) // print("view will disappear") // } // // override func viewDidDisappear(_ animated: Bool) { // super.viewDidAppear(animated) // print("view did disappear") // } }
32.713376
91
0.617017
fc92df790ed80095264585d0d09fae21ffa77d55
2,168
// // AppDelegate.swift // TabBarDemo // // Created by josscii on 2018/2/11. // Copyright © 2018年 josscii. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.12766
285
0.755535
eb973ceaac9e052c1ee2a21ca6b7c673e12c7b6e
427
// // UserDefaults.swift // RoemischeZahl // // Created by Morten Bertz on 2021/09/14. // import Foundation extension UserDefaults{ enum Keys { static let outPutModeKey = "outPutModeKey" static let daijiCompleteKey = "daijiCompleteKey" } } extension NSUserActivity{ enum ActivityTypes{ static let conversionActivity = "com.mihomaus.RoemischeZahl.conversionActivity" } }
17.08
87
0.679157
9cd0070470fca9e45a437bfab172dae7a4b59f89
2,031
// // HMCDPaginationProviderType.swift // HMRequestFramework // // Created by Hai Pham on 8/29/17. // Copyright © 2017 Holmusk. All rights reserved. // import CoreData /// Classes that implement this protocol should provide pagination properties /// to be used in event streaming. public protocol HMCDPaginationProviderType: HMCDPaginationMultipleType { /// Specify the fetch limit for a fetch request. This determines how many /// items are fetched from DB every time a stream requests for more data. /// /// - Returns: An Int value. func fetchLimit() -> UInt /// Specify the fetch offset for a fetch request. This determines the cut /// off at which data start being collected. /// /// - Returns: An Int value. func fetchOffset() -> UInt /// Specify the pagination mode. /// /// - Returns: A HMCDPaginationMode instance. func paginationMode() -> HMCDPaginationMode } public extension HMCDPaginationProviderType { public func fetchLimitWithMultiple(_ multiple: UInt) -> UInt { let fetchLimit = self.fetchLimit() switch paginationMode() { case .fixedPageCount: return fetchLimit case .variablePageCount: return fetchLimit * multiple } } // If paginationMode is fixedPageCount, we need to increment the fetchOffset // by multiples of fetchLimit to simulate page flipping. We also need to // decrement the multiple by 1 because we need the first page's fetchOffset // to be the base fetchOffset (in case the multiple is 0 or larger than 1). public func fetchOffsetWithMultiple(_ multiple: UInt) -> UInt { let fetchOffset = self.fetchOffset() let fetchLimit = self.fetchLimit() switch paginationMode() { case .fixedPageCount: return fetchOffset + fetchLimit * (Swift.max(multiple, 1) - 1) case .variablePageCount: return fetchOffset } } }
32.238095
80
0.651896
4a1bc3bc97aacaad889fc6e093b6497375749aa3
2,002
import SnapshotTesting import SwiftUI import XCTest @testable import Bathymetry // MARK: - MapZoomViewTests class MapZoomViewTests: XCTestCase { // MARK: life cycle override func setUpWithError() throws { super.setUp() } override func tearDownWithError() throws { super.tearDown() } // MARK: test func testMapZoomView_whenZoomLevelIsMax_snapshotTesting() throws { let sut = UIHostingController( rootView: MapZoomView( zoomLevel: Binding<BathymetryZoomLevel>( get: { .max }, set: { _ in } ) ) ) [(UIUserInterfaceStyle.dark, "dark"), (UIUserInterfaceStyle.light, "light")].forEach { style, named in sut.overrideUserInterfaceStyle = style assertSnapshot( matching: sut, as: .img(precision: 0.98), named: named + "." + model.name ) } } func testMapZoomView_whenZoomLevelIsMin_snapshotTesting() throws { let sut = UIHostingController( rootView: MapZoomView( zoomLevel: Binding<BathymetryZoomLevel>( get: { .min }, set: { _ in } ) ) ) [(UIUserInterfaceStyle.dark, "dark"), (UIUserInterfaceStyle.light, "light")].forEach { style, named in sut.overrideUserInterfaceStyle = style assertSnapshot( matching: sut, as: .img(precision: 0.98), named: named + "." + model.name ) } } func testMapZoomView_whenZoomLevelIsMidOfMaxAndMin_snapshotTesting() throws { let sut = UIHostingController( rootView: MapZoomView( zoomLevel: Binding<BathymetryZoomLevel>( get: { (.min + .max) / 2 }, set: { _ in } ) ) ) [(UIUserInterfaceStyle.dark, "dark"), (UIUserInterfaceStyle.light, "light")].forEach { style, named in sut.overrideUserInterfaceStyle = style assertSnapshot( matching: sut, as: .img(precision: 0.98), named: named + "." + model.name ) } } }
25.341772
106
0.607393
e8a93b78e4d0c02016c62a78ab00b3bc7f70f46d
1,932
import XCTest import SwiftUI @testable import SwiftTheming final class SwiftThemingUserDefaultsTests: XCTestCase { func testUserDefaults() { let themeKey = UserDefaults.Key.theme let appearanceKey = UserDefaults.Key.preferredAppearance XCTAssertEqual(themeKey.rawValue, "theming.theme.key") XCTAssertEqual(appearanceKey.rawValue, "theming.preferredAppearance.key") UserDefaults.standard.removeObject(forKey: themeKey.rawValue) UserDefaults.standard.removeObject(forKey: appearanceKey.rawValue) XCTAssertNil(UserDefaults.get(Theme.self, key: .theme)) XCTAssertNil(UserDefaults.get(PreferredAppearance.self, key: .preferredAppearance)) UserDefaults.set(Theme.jadoTheme, key: .theme) XCTAssertEqual(UserDefaults.get(Theme.self, key: .theme), .jadoTheme) UserDefaults.set(PreferredAppearance.system, key: .preferredAppearance) XCTAssertEqual(UserDefaults.get(PreferredAppearance.self, key: .preferredAppearance), .system) UserDefaults.set(Theme.bluoTheme, key: .theme) XCTAssertEqual(UserDefaults.get(Theme.self, key: .theme), .bluoTheme) UserDefaults.set(PreferredAppearance.light, key: .preferredAppearance) XCTAssertEqual(UserDefaults.get(PreferredAppearance.self, key: .preferredAppearance), .light) UserDefaults.set(PreferredAppearance.dark, key: .preferredAppearance) XCTAssertEqual(UserDefaults.get(PreferredAppearance.self, key: .preferredAppearance), .dark) UserDefaults.set(FailedEcodeObject(), key: .theme) XCTAssertEqual(UserDefaults.get(Theme.self, key: .theme), .bluoTheme) } } struct FailedEcodeObject: Codable { func encode(to encoder: Encoder) throws { throw EncodingError.invalidValue("", .init(codingPath: [], debugDescription: "", underlyingError: nil)) } }
44.930233
111
0.713251
874cc6188aad9d56b6e5faf2afdc69aca7b3ea29
4,543
// // SecondViewController.swift // SwiftBaseExample // // Created by 张少晴 on 2019/9/10. // Copyright © 2019 administrator. All rights reserved. // import UIKit //import MJRefresh class SQBaseTableViewVC: SQBaseViewController { private lazy var tableView:UITableView = { let tableView = UITableView.defaultLineTableView(style: .grouped) tableView.separatorColor = UIColor.red tableView.separatorInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) tableView.backgroundColor = UIColor.white tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)") tableView.delegate = self; tableView.dataSource = self; if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } else { automaticallyAdjustsScrollViewInsets = false } return tableView }() func setUpUI() { self.view.backgroundColor = UIColor.white self.view.addSubview(tableView) self.tableView.frame = self.view.frame self.tableView.reloadData() // self.tableView.snp.makeConstraints { (make) in // make.edges.equalTo(view) // } // self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in // // }) // self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in // // }) // if UserManager.shared.isLoginStatus { // self.tableView.mj_header.beginRefreshing() // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() let str2 = decimalString(string: "\(Myview.self)") print(str2) setUpUI() } //MARK:- 消除浮动 func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.tableView { let sectionHeaderHeight = CGFloat(50) if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsets.init(top: -scrollView.contentOffset.y, left: 0, bottom: 0, right: 0); } else if (scrollView.contentOffset.y>=sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsets.init(top: -sectionHeaderHeight, left: 0, bottom: 0, right: 0); } } } } //MARK:- UITableViewDataSource UITableViewDelegate extension SQBaseTableViewVC: UITableViewDelegate, UITableViewDataSource{ //MARK:- UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath) cell?.textLabel?.text = "你好" cell?.selectionStyle = .none // cell?.separatorInset = UIEdgeInsets.zero // cell?.layoutMargins = UIEdgeInsets.zero // cell?.separatorInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16) // cell?.layoutMargins = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16) // cell.setNeedsUpdateConstraints() // cell.updateConstraintsIfNeeded() return cell!; } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView.init() } //MARK: UITableViewDelegate // 设置cell高度 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.001 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } // 选中cell后执行此方法 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
32.219858
124
0.613251
ed58507a500de5bfa5bdc9b710faf6ee6c6f5350
2,160
// // AppDelegate.swift // UIKitDynamicsLSLA // // Created by Garric Nahapetian on 6/22/16. // Copyright © 2016 Learn Swift LA. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.957447
285
0.755093
505bb4ae2bc278153123b08e16dd236204853b2c
1,032
// // GoodNightViewController.swift // wakeupworld // // Created by Ken Chen on 4/9/16. // Copyright © 2016 wakeup. All rights reserved. // import UIKit class GoodNightViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "goodnight6.png")!) self.navigationController!.navigationBar.hidden = true // 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. } */ }
27.891892
106
0.686047
4a47ebaadd3774bdde5aa0e191182a7819081835
547
// // ConstraintMetadata.swift // Zendo // // Created by Anton Pavlov on 16/08/2018. // Copyright © 2018 zenbf. All rights reserved. // import Foundation enum MetadataType: String { case time = "time" case now = "now" case motion = "motion" case sdnn = "sdnn" case heart = "heart" case pitch = "pitch" case roll = "roll" case yaw = "yaw" } let metadataTypeArray: [MetadataType] = [.time, .now, .motion, .sdnn, .heart, .pitch, .roll, .yaw] let metadataTypeArraySmall: [MetadataType] = [.time, .sdnn, .heart]
21.88
98
0.634369
ff7ad284e0727fa191da3c35145484772ce520de
6,602
// // MessageViewController.swift // ThinkSNS + // // Created by lip on 2017/9/4. // Copyright © 2017年 ZhiYiCX. All rights reserved. // // 消息页面根控制器,持有切换2个子控制器 import UIKit class MessageViewController: TSLabelViewController { /// 会话控制器 let conversationVC: TSConversationTableViewController /// IM第二版聊天列表页面(新构造的) let chatListNewVC: ChatListViewController /// 是否将通知控制器添加为子控制器 var isAddNotiVC = false /// 网络控制器 lazy var unreadCountNetworkManager = UnreadCountNetworkManager() /// 发起聊天按钮 fileprivate weak var chatButton: UIButton! /// 我的群聊 fileprivate weak var groupButton: UIButton! override init(labelTitleArray: [String], scrollViewFrame: CGRect?, isChat: Bool = false) { self.conversationVC = TSConversationTableViewController(style: .plain, model: MessageViewController.pasteNiticeModel()) self.chatListNewVC = ChatListViewController() super.init(labelTitleArray: labelTitleArray, scrollViewFrame: scrollViewFrame, isChat: isChat) self.conversationVC.superViewController = self self.chatListNewVC.superViewController = self self.add(childViewController: chatListNewVC, At: 1) } required init?(coder aDecoder: NSCoder) { fatalError("该控制器不支持") } override func viewDidLoad() { super.viewDidLoad() setChatButton() setGroupButton() setupUI() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) loadUnreadInfo() NotificationCenter.default.addObserver(self, selector: #selector(loadUnreadInfo), name: NSNotification.Name.APNs.receiveNotice, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.APNs.receiveNotice, object: nil) } // MARK: - 设置发起聊天按钮(设置右上角按钮) func setChatButton() { let chatItem = UIButton(type: .custom) chatItem.addTarget(self, action: #selector(rightButtonClick), for: .touchUpInside) self.setupNavigationTitleItem(chatItem, title: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: chatItem) self.chatButton = chatItem self.chatButton.setImage(UIImage(named: "ico_spchat"), for: UIControlState.normal) self.chatButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: self.chatButton.width - (self.chatButton.currentImage?.size.width)!, bottom: 0, right: 0) } // MARK: - 已经加入的群聊按钮 func setGroupButton() { let chatItem = UIButton(type: .custom) chatItem.addTarget(self, action: #selector(leftButtonClick), for: .touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: chatItem) self.groupButton = chatItem self.groupButton.setImage(UIImage(named: "ico_title_group"), for: UIControlState.normal) self.groupButton.size = CGSize(width: 24, height: 24) } func loadUnreadInfo() { self.unreadCountNetworkManager.unreadCount { [weak self] (_) in guard let weakSelf = self else { return } // 整合数据给子视图 然后刷新 DispatchQueue.main.async { weakSelf.countUnreadInfo() weakSelf.conversationVC.noticeCellModel = MessageViewController.pasteNiticeModel() weakSelf.conversationVC.tableView.reloadData() } } } open func countUnreadInfo() { DispatchQueue.main.async { let unreadInfo = TSCurrentUserInfo.share.unreadCount var imMessageCount = unreadInfo.imMessage if imMessageCount < 0 { imMessageCount = 0 } self.badges[1].isHidden = imMessageCount.isEqualZero if unreadInfo.isHiddenNoticeBadge && unreadInfo.onlyNoticeUnreadCount().isEqualZero { self.badges[0].isHidden = true } else { self.badges[0].isHidden = false } self.unreadCountNetworkManager.unploadTabbarBadge() } } func setupUI() { scrollView.backgroundColor = TSColor.inconspicuous.background add(childViewController: conversationVC, At: 0) } static func pasteNiticeModel() -> [NoticeConversationCellModel] { if TSCurrentUserInfo.share.isLogin == false { return [] } else { let unreadInfo = TSCurrentUserInfo.share.unreadCount let systemModel = NoticeConversationCellModel(title: "系统消息", content: unreadInfo.systemInfo ?? "暂无系统消息", badgeCount: unreadInfo.system, date: unreadInfo.systemTime, image: "ico_message_systerm") let commentModel = NoticeConversationCellModel(title: "收到的评论", content: unreadInfo.commentsUsers ?? "显示_收到的评论占位字".localized, badgeCount: unreadInfo.comments, date: unreadInfo.commentsUsersDate, image: "IMG_message_comment") let likeModel = NoticeConversationCellModel(title: "收到的赞", content: unreadInfo.likedUsers ?? "显示_收到的赞占位字".localized, badgeCount: unreadInfo.like, date: unreadInfo.likeUsersDate, image: "IMG_message_good") let pendModel = NoticeConversationCellModel(title: "审核通知", content: unreadInfo.pendingUsers ?? "显示_审核通知占位字".localized, badgeCount: unreadInfo.pending, date: unreadInfo.pendingUsersDate, image: "IMG_ico_message_check") var atStr = unreadInfo.atUsers ?? "显示_收到的at占位字".localized if atStr.isEmpty { atStr = "显示_收到的at占位字".localized } let atModel = NoticeConversationCellModel(title: "@我的", content: atStr, badgeCount: unreadInfo.at, date: unreadInfo.pendingUsersDate, image: "ico_@") return [systemModel, atModel, commentModel, likeModel, pendModel] } } override func selectedPageChangedTo(index: Int) { if index == 0 { // 当视图切换到第一个时,刷新通知信息 loadUnreadInfo() chatListNewVC.searchBar?.resignFirstResponder() } // 当视图切换到第二个页面且未成功添加子视图时,添加通知视图 if index == 1 && isAddNotiVC == false { isAddNotiVC = true add(childViewController: chatListNewVC, At: 1) } } // MARK: - 发起聊天按钮点击事件(右上角按钮点击事件) func rightButtonClick() { let vc = TSChatFriendListViewController() self.navigationController?.pushViewController(vc, animated: true) } // MARK: - 已加入群聊入口 func leftButtonClick() { let vc = JoinedGroupListVC() self.navigationController?.pushViewController(vc, animated: true) } }
42.050955
235
0.671463
21040c0c2aab80ac9880a6abac55f52491d881b8
9,862
// RUN: %empty-directory(%t/ForeignModule.swiftmodule) // RUN: touch %t/ForeignModule.swiftmodule/garbage-garbage-garbage.swiftmodule // Test format: We try to import ForeignModule with architectures besides // garbage-garbage-garbage and check the target triple listed in the error // message to make sure it was normalized correctly. This works in lieu of a // mechanism to query the compiler for normalized triples. // // The extra flags in the RUN lines serve the following purposes: // // * "-parse-stdlib" ensures we don't reject any of these for not having an // appropriate standard library built. // * "-Xcc -arch -Xcc i386" makes sure the clang importer doesn't reject triples // clang considers invalid. import ForeignModule // CHECK: error: could not find module 'ForeignModule' // CHECK-SAME: '[[NORM]]' // Run lines for individual test cases follow. // // OSES // // OS version numbers should be stripped. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // macos, macosx, and darwin should all normalize to macos. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-darwin46.0 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // ios, tvos, watchos should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s // Other OSes should be passed through without version stripping. We can't test // a totally garbage case because we'll get diag::error_unsupported_target_os. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-apple-linux40.04 %s // // VENDORS // // If the OS looks like an Apple OS, vendor should be normalized to apple. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64--ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-ibm-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-snapple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s // // ARCHITECTURES // // arm64 and aarch64 are normalized to arm64. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // armv7s, armv7k, armv7, arm64e should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7s-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7s-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7k-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7k-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64e-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64e-apple-ios %s // x86_64h should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64h-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64h-apple-macos %s // x64_64 and amd64 are normalized to x86_64. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // i[3-9]86 are normalized to i386. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i486-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i586-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i686-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i786-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i886-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // Other arches should be passed through. We can't test a totally garbage case // because we'll get diag::error_unsupported_target_arch. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target powerpc64-apple-macos10.11 2>&1 | %FileCheck -DNORM=powerpc64-apple-macos %s // // ENVIRONMENTS // // simulator should be permitted on the non-Mac operating systems. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-watchos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=i386-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=i386-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=i386-apple-watchos-simulator %s // simulator should be inferred when an Intel architecture is used with iOS, tvOS, or watchOS. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-ios40.0 2>&1 | %FileCheck -DNORM=x86_64-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-tvos40 2>&1 | %FileCheck -DNORM=x86_64-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-watchos9.1.1 2>&1 | %FileCheck -DNORM=x86_64-apple-watchos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0 2>&1 | %FileCheck -DNORM=i386-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-tvos40 2>&1 | %FileCheck -DNORM=i386-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-watchos9.1.1 2>&1 | %FileCheck -DNORM=i386-apple-watchos-simulator %s // Other environments should be passed through. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-in_spaaaaaaace 2>&1 | %FileCheck -DNORM=i386-apple-ios-in_spaaaaaaace %s // // DARWIN ONLY // // Non-isDarwinOS() OSes should have no normalization applied. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-unknown-linux40.04 %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64--linux-android 2>&1 | %FileCheck -DNORM=aarch64--linux-android %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-ibm-linux40.04 2>&1 | %FileCheck -DNORM=amd64-ibm-linux40.04 %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-snapple-haiku 2>&1 | %FileCheck -DNORM=i986-snapple-haiku %s
73.051852
192
0.719732
91714e1ba557578840977b7affad08916e9b5d2b
10,148
import Foundation import XCTest @testable import SwiftyVK final class JSONTests: XCTestCase { func test_init_whenDataIsNil() { // When let json = try? JSON(data: nil) // Then XCTAssertNil(json) } func test_init_whenDataIsIncorrect() { // When let json = try? JSON(data: Data()) // Then XCTAssertNil(json) } func test_init_whenDataIsCorrect() { // When let json = try? JSON(data: "[]".data(using: .utf8)) // Then XCTAssertNotNil(json) } func test_any_isNotNil_whenDataIsArray() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.any("0") // Then XCTAssertNotNil(value) } func test_any_isNotNil_whenDataIsDict() { // When let json = try! JSON(data: "{\"test\": 1}".data(using: .utf8)) let value = json.any("test") // Then XCTAssertNotNil(value) } func test_any_isNotNil_whenArrayContainsEnclosedArray() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value = json.any("0,0") // Then XCTAssertNotNil(value) } func test_any_isNotNil_whenArrayContainsEnclosedDict() { // When let json = try! JSON(data: "[{\"test\": 1}]".data(using: .utf8)) let value = json.any("0,test") // Then XCTAssertNotNil(value) } func test_any_isNotNil_whenPathIsLong() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.any("0,0,0,0,0") // Then XCTAssertNil(value) } func test_any_isNotNil_whenPathComponentIsEmpty() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value = json.any("0, ") // Then XCTAssertNil(value) } func test_any_isNotNil_whenIndexIncorrect() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.any("1") // Then XCTAssertNil(value) } func test_data_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value = json.data("0") // Then XCTAssertEqual(value?.count, 3) } func test_data_isNotEmpty_whenDataIsDict() { // When let json = try! JSON(data: "{\"test\": [1]}".data(using: .utf8)) let value = json.data("test") // Then XCTAssertEqual(value?.count, 3) } func test_forcedData_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value = json.forcedData("0") // Then XCTAssertEqual(value.count, 3) } func test_forcedData_isEmpty_whenDataIsDict() { // When let json = try! JSON(data: "1".data(using: .utf8)) let value = json.forcedData("test") // Then XCTAssertEqual(value.count, 0) } func test_data_isNil_whenDataIsPrimitive() { // When let json = try! JSON(data: "1".data(using: .utf8)) let value = json.data("*") // Then XCTAssertNil(value) } func test_array_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value: [Any]? = json.array("0") // Then XCTAssertEqual(value?.count, 1) } func test_array_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value: [Any]? = json.array("0") // Then XCTAssertNil(value) } func test_forcedArray_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[[1]]".data(using: .utf8)) let value: [Any] = json.forcedArray("0") // Then XCTAssertFalse(value.isEmpty) } func test_forcedArray_isEmpty_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value: [Any] = json.forcedArray("0") // Then XCTAssertTrue(value.isEmpty) } func test_dict_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[{\"test\": 1}]".data(using: .utf8)) let value: [String: Any]? = json.dictionary("0") // Then XCTAssertEqual(value?.count, 1) } func test_dict_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value: [String: Any]? = json.dictionary("0") // Then XCTAssertNil(value) } func test_forcedDict_isNotEmpty_whenDataIsArray() { // When let json = try! JSON(data: "[{\"test\": 1}]".data(using: .utf8)) let value: [String: Any] = json.forcedDictionary("0") // Then XCTAssertFalse(value.isEmpty) } func test_forcedDict_isEmpty_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value: [String: Any] = json.forcedDictionary("0") // Then XCTAssertTrue(value.isEmpty) } func test_bool_isTrue_whenDataIsTrue() { // When let json = try! JSON(data: "[true]".data(using: .utf8)) let value = json.bool("0") // Then XCTAssertTrue(value ?? false) } func test_bool_isFalse_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.bool("0") // Then XCTAssertNil(value) } func test_forcedBool_isTrue_whenDataIsTrue() { // When let json = try! JSON(data: "[true]".data(using: .utf8)) let value = json.forcedBool("0") // Then XCTAssertTrue(value) } func test_forcedBool_isFalse_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.forcedBool("0") // Then XCTAssertFalse(value) } func test_string_isExist_whenDataIsString() { // When let json = try! JSON(data: "[\"test\"]".data(using: .utf8)) let value = json.string("0") // Then XCTAssertEqual(value, "test") } func test_string_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.string("0") // Then XCTAssertNil(value) } func test_forcedString_isExist_whenDataIsString() { // When let json = try! JSON(data: "[\"test\"]".data(using: .utf8)) let value = json.forcedString("0") // Then XCTAssertEqual(value, "test") } func test_forcedString_isEmpty_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.forcedString("0") // Then XCTAssertTrue(value.isEmpty) } func test_int_isExist_whenDataIsInt() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.int("0") // Then XCTAssertEqual(value, 1) } func test_int_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.int("0") // Then XCTAssertNil(value) } func test_forcedInt_isExist_whenDataIsInt() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.forcedInt("0") // Then XCTAssertEqual(value, 1) } func test_forcedInt_isZero_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.forcedInt("0") // Then XCTAssertEqual(value, 0) } func test_float_isExist_whenDataIsFloat() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.float("0") // Then XCTAssertEqual(value, 1) } func test_float_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.float("0") // Then XCTAssertNil(value) } func test_forcedFloat_isExist_whenDataIsInt() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.forcedFloat("0") // Then XCTAssertEqual(value, 1) } func test_forcedFloat_isZero_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.forcedFloat("0") // Then XCTAssertEqual(value, 0) } func test_double_isExist_whenDataIsDouble() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.double("0") // Then XCTAssertEqual(value, 1) } func test_double_isNil_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.double("0") // Then XCTAssertNil(value) } func test_forcedDouble_isExist_whenDataIsInt() { // When let json = try! JSON(data: "[1]".data(using: .utf8)) let value = json.forcedDouble("0") // Then XCTAssertEqual(value, 1) } func test_forcedDouble_isZero_whenDataNotExist() { // When let json = try! JSON(data: "[]".data(using: .utf8)) let value = json.forcedDouble("0") // Then XCTAssertEqual(value, 0) } func test_int_isExist_whenDataIsRoot() { // When let json = try! JSON(data: "1".data(using: .utf8)) let value = json.int("*") // Then XCTAssertEqual(value, 1) } func test_any_isNil_whenPathIsEmpty() { // When let json = try? JSON(data: "".data(using: .utf8)) let value = json?.any("") // Then XCTAssertNil(value) } }
27.80274
72
0.54257
39a812ee6c7a9e4ad87e2849776ec4f9e6ffbdaf
175
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(skyflow_iOS_soapConnectionTests.allTests) ] } #endif
17.5
58
0.708571
1cbf617f3a3cad58088c5214dbc9408b6277df89
1,505
// // ContentView.swift // PHPicker // // Created by 藤 治仁 on 2020/07/12. // import SwiftUI struct ContentView: View { @State var images: [UIImage] = [] @State var picker = false var body: some View { VStack { Spacer() if !images.isEmpty { ScrollView(.horizontal, showsIndicators: false, content: { HStack(spacing: 15.0) { ForEach(images,id: \.self){image in Image(uiImage: image) .resizable() .frame(width: 250.0, height: 250.0) .cornerRadius(25) } } }) } Spacer() Button(action: { picker.toggle() }) { Text("画像を選択する") .foregroundColor(.white) .padding(.vertical, 10.0) .padding(.horizontal, 35.0) .background(Color.blue) .clipShape(Capsule()) } .padding(.bottom, 16.0) } .sheet(isPresented: $picker) { // Pickerを開く ImagePicker(images: $images, picker: $picker) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
25.948276
74
0.403987
9b2d8275fde7cb021aa8d41e4e768a33506fbc90
674
// REQUIRES: CPU=x86_64 // RUN: %target-swift-frontend -c -module-name someModule -embed-bitcode-marker -o %t.o %s // RUN: llvm-objdump -macho -section="__LLVM,__bitcode" %t.o | %FileCheck -check-prefix=MARKER %s // RUN: llvm-objdump -macho -section="__LLVM,__swift_cmdline" %t.o | %FileCheck -check-prefix=MARKER-CMD %s // This file tests Mach-O file output, but Linux variants do not produce Mach-O // files. // UNSUPPORTED: OS=linux-gnu // UNSUPPORTED: OS=linux-gnueabihf // UNSUPPORTED: OS=freebsd // MARKER: Contents of (__LLVM,__bitcode) section // MARKER-NEXT: 00 // MARKER-CMD: Contents of (__LLVM,__swift_cmdline) section // MARKER-CMD-NEXT: 00 func test() { }
35.473684
107
0.719585
6716146af3d8fe5d6b61ef12d587f19447e9a9ab
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum A<T{class a{class B func a{class a{class B<I:T.E
37.166667
87
0.757848
db1a9a97114395ea10887f2e2ff7f3d7f9d193ef
1,026
// // DataTests.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 1/10/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(Linux) import Glibc #endif import XCTest @testable import SwiftFoundation final class DataTests: XCTestCase { static let allTests: [(String, (DataTests) -> () throws -> Void)] = [("testFromBytePointer", testFromBytePointer)] func testFromBytePointer() { let string = "TestData" let testData = string.toUTF8Data() XCTAssert(testData.isEmpty == false, "Could not create test data") let dataPointer = UnsafeMutablePointer<Byte>.allocate(capacity: testData.count) defer { dataPointer.deallocate(capacity: testData.count) } memcpy(dataPointer, testData.bytes, testData.count) let data = SwiftFoundation.Data(bytes: dataPointer, count: testData.count) XCTAssert(data == testData, "\(data) == \(testData)") } }
26.307692
118
0.628655
03250f472080a010146d618b654bc58d2009fb46
2,452
// // MapViewController.swift // FoodPin // // Created by Simon Ng on 30/10/2019. // Copyright © 2019 AppCoda. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet var mapView: MKMapView! var restaurant = Restaurant() override func viewDidLoad() { super.viewDidLoad() // Convert address to coordinate and annotate it on map let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(restaurant.location, completionHandler: { placemarks, error in if let error = error { print(error) return } if let placemarks = placemarks { // Get the first placemark let placemark = placemarks[0] // Add annotation let annotation = MKPointAnnotation() annotation.title = self.restaurant.name annotation.subtitle = self.restaurant.type if let location = placemark.location { annotation.coordinate = location.coordinate // Display the annotation self.mapView.showAnnotations([annotation], animated: true) self.mapView.selectAnnotation(annotation, animated: true) } } }) // Configure map view mapView.delegate = self mapView.showsCompass = true mapView.showsScale = true mapView.showsTraffic = true } // MARK: - Map View Delegate methods func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "MyMarker" if annotation.isKind(of: MKUserLocation.self) { return nil } // Reuse the annotation if possible var annotationView: MKMarkerAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView if annotationView == nil { annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier) } annotationView?.glyphText = "😋" annotationView?.markerTintColor = UIColor.orange return annotationView } }
30.271605
146
0.573002
e8cafbe7c37f8de4d0c8d2c9cbaa28e8c017959a
4,371
// // UIAlertController.swift // RxModal // // Created by Jérôme Alves on 07/02/2021. // import UIKit import RxSwift extension DialogActionStyle { fileprivate var alertActionStyle: UIAlertAction.Style { switch self { case .default: return .default case .cancel: return .cancel case .destructive: return .destructive } } } extension DialogAction { fileprivate func makeAlertAction(observer: AnyObserver<Observable<T>>, textFields: @escaping () -> [UITextField]) -> UIAlertAction { UIAlertAction(title: title, style: style.alertActionStyle) { _ in observer.onNext(self.onNext(textFields())) observer.onCompleted() } } } extension Dialog { fileprivate func makeAlertController(style: DialogStyle, observer: AnyObserver<Observable<T>>) -> UIAlertController { let controller: UIAlertController switch style { case .alert: controller = UIAlertController(title: title, message: message, preferredStyle: .alert) case .actionSheet(let source): controller = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) switch source { case .view(let view, let rect): controller.popoverPresentationController?.sourceRect = rect controller.popoverPresentationController?.sourceView = view case .barButtonItem(let item): controller.popoverPresentationController?.barButtonItem = item } } if case .alert = style { for textField in textFields { controller.addTextField(configurationHandler: textField.configuration) } } for action in actions { let alertAction = action.makeAlertAction(observer: observer) { [unowned controller] in controller.textFields ?? [] } controller.addAction(alertAction) if action.isPreferred { controller.preferredAction = alertAction } } return controller } } public enum DialogSource { case view(UIView, rect: CGRect) case barButtonItem(UIBarButtonItem) public static func bounds(_ view: UIView) -> DialogSource { .view(view, rect: view.bounds) } } public enum DialogStyle { case alert case actionSheet(source: DialogSource) } extension RxModal { public static func alert<T>( _ type: T.Type = T.self, presenter: Presenter = .keyWindow, title: String? = nil, message: String? = nil, textFields: [DialogTextField] = [], actions: [DialogAction<T>] ) -> Observable<T> { present(.alert, presenter: presenter, title: title, message: message, textFields: textFields, actions: actions) } public static func actionSheet<T>( _ type: T.Type = T.self, presenter: Presenter = .keyWindow, source: DialogSource, title: String? = nil, message: String? = nil, actions: [DialogAction<T>] ) -> Observable<T> { present(.actionSheet(source: source), presenter: presenter, title: title, message: message, actions: actions) } public static func present<T>( _ style: DialogStyle, type: T.Type = T.self, presenter: Presenter = .keyWindow, title: String? = nil, message: String? = nil, textFields: [DialogTextField] = [], actions: [DialogAction<T>] ) -> Observable<T> { let dialog = Dialog(title: title, message: message, textFields: textFields, actions: actions) return present( dialog, style: style, presenter: presenter) } public static func present<T>( _ dialog: Dialog<T>, style: DialogStyle, presenter: Presenter = .keyWindow ) -> Observable<T> { UIAlertControllerCoordinator.present(using: presenter) { coordinator in dialog.makeAlertController(style: style, observer: coordinator.result.asObserver()) } sequence: { coordinator in coordinator.result.merge() } } } private class UIAlertControllerCoordinator<T>: RxModalCoordinator<UIAlertController> { required init() {} let result = PublishSubject<Observable<T>>() }
31.905109
136
0.620453
1da5bb06ab382f5ad6dbef892c868a84d1d96a78
2,444
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // -------------------------------------------------------------------------- import AzureCore import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable identifier_name // swiftlint:disable line_length extension EnumOperation { /// User-configurable options for the `AutoRestSwaggerBATService.PutReferencedConstant` operation. public struct PutReferencedConstantOptions: RequestOptions { /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// Highly recommended for correlating client-side activites with requests received by the server. public let clientRequestId: String? /// A token used to make a best-effort attempt at canceling a request. public let cancellationToken: CancellationToken? /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. public var dispatchQueue: DispatchQueue? /// A `PipelineContext` object to associate with the request. public var context: PipelineContext? /// Initialize a `PutReferencedConstantOptions` structure. /// - Parameters: /// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// - cancellationToken: A token used to make a best-effort attempt at canceling a request. /// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. /// - context: A `PipelineContext` object to associate with the request. public init( clientRequestId: String? = nil, cancellationToken: CancellationToken? = nil, dispatchQueue: DispatchQueue? = nil, context: PipelineContext? = nil ) { self.clientRequestId = clientRequestId self.cancellationToken = cancellationToken self.dispatchQueue = dispatchQueue self.context = context } } }
46.113208
126
0.65671
2088f896af6a7ae2a61123664e8b639e6906a1ec
2,144
// // AppDelegate.swift // Tinder // // Created by Darrell Shi on 3/24/16. // Copyright © 2016 iOS Development. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.617021
285
0.753731
08bd86ccf6e977cd6bf5532951703f594d9d0216
1,679
// // File.swift // // // Created by Zehua Chen on 5/20/21. // import simd extension simd_float4x4 { /// Create a translation matrix along the X, Y, Z axis /// - Parameter offset: offset along the X, Y, Z axis /// - Returns: a translation matrix @inlinable public static func translate(_ offset: SIMD3<Float32>) -> Self { return simd_float4x4( SIMD4<Float32>(1, 0, 0, 0), SIMD4<Float32>(0, 1, 0, 0), SIMD4<Float32>(0, 0, 1, 0), SIMD4<Float32>(offset.x, offset.y, offset.z, 1)) } /// Create a translation matrix along the X axis /// - Parameter offset: offset along the X axis /// - Returns: a translation matrix @inlinable public static func translateX(_ offset: Float32) -> Self { return simd_float4x4( SIMD4<Float32>(1, 0, 0, 0), SIMD4<Float32>(0, 1, 0, 0), SIMD4<Float32>(0, 0, 1, 0), SIMD4<Float32>(offset, 0, 0, 1)) } /// Create a translation matrix along the Y axis /// - Parameter offset: offset along the Y axis /// - Returns: a translation matrix @inlinable public static func translateY(_ offset: Float32) -> Self { return simd_float4x4( SIMD4<Float32>(1, 0, 0, 0), SIMD4<Float32>(0, 1, 0, 0), SIMD4<Float32>(0, 0, 1, 0), SIMD4<Float32>(0, offset, 0, 1)) } /// Create a translation matrix along the Z axis /// - Parameter offset: offset along the Z axis /// - Returns: a translation matrix @inlinable public static func translateZ(_ offset: Float32) -> Self { return simd_float4x4( SIMD4<Float32>(1, 0, 0, 0), SIMD4<Float32>(0, 1, 0, 0), SIMD4<Float32>(0, 0, 1, 0), SIMD4<Float32>(0, 0, offset, 1)) } }
28.948276
66
0.616438
48f159c2d8408cd0344aaf8b52f94c693622076a
1,232
// // HomeViewController.swift // DOUYUTV // // Created by 王新伟 on 2017/4/15. // Copyright © 2017年 王新伟. All rights reserved. // import UIKit class HomeViewController: UIViewController { //MARK: --- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() //设置UI setUpUI() } } //MARK:设置UI界面 extension HomeViewController{ fileprivate func setUpUI(){ //1.不需要调整scrollView的内边距 automaticallyAdjustsScrollViewInsets = false //2.设置导航栏相关 setUpNavigationBar(); } } extension HomeViewController{ fileprivate func setUpNavigationBar(){ //1.设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName:"logo") //设置导航栏右侧的按钮 let size = CGSize(width: 40 , height: 40) let historyItem = UIBarButtonItem(imageName:"image_my_history" ,heightImageName:"Image_my_history_click" , size:size) let searchItem = UIBarButtonItem(imageName:"btn_search" , heightImageName : "btn_search_clicked" ,size:size) let qrcodeItem = UIBarButtonItem(imageName:"Image_scan" , heightImageName:"Image_scan_click",size:size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } }
27.377778
125
0.685877
1c295d2c166ba46eb1df9b4e4d8bbf076673aea7
589
// // ImageResource.swift // R.swift.Library // // Created by Mathijs Kadijk on 11-01-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation public protocol ImageResourceType { /// Bundle this image is in var bundle: NSBundle { get } /// Name of the image var name: String { get } } public struct ImageResource: ImageResourceType { /// Bundle this image is in public let bundle: NSBundle /// Name of the image public let name: String public init(bundle: NSBundle, name: String) { self.bundle = bundle self.name = name } }
17.848485
57
0.677419
5625b15eb401ba05c20a5e63620ae3e48a15645a
323
// // CompileError.swift // Lioness // // Created by Louis D'hauwe on 04/11/2016. // Copyright © 2016 - 2017 Silver Fox. All rights reserved. // import Foundation public enum CompileError: Error { case unexpectedCommand case emptyStruct case unexpectedBinaryOperator case functionNotFound case unbalancedScope }
17.944444
60
0.752322
f71df47b097141853b7573c3beff7653e335faea
48,691
//: Playground - noun: a place where people can play import UIKit /* The Basics */ /* Numeric Literals */ // Integer Literals let decimalInteger = 22 let binaryInteger = 0b10 // 2 in binary let octalInteger = 0o31 let hexadecimalInteger = 0x1A // Floating Point Literals // to define a floating point literal in hex/decimal they need a number on both sides of the decimal point // they can have an exponent as well var floatingPointHex = 0xC.3p0 var doubleWithExponent = 1.25e10 // formatting literals for readability // using '_' and padding with leading zeros doesn't affect the value var oneMillion = 1_000_000 var paddedDouble = 000123.456 /* Numeric Type Conversion */ // Only use Int16, UInt16, etc when required for performance, memory usage, or other required optimizations - and compatibility with an outside API/data sources // Integer Conversion // let cannotBeNegative: UInt8 = -1 // generate compile time error, cannot put a negative in an unsigned int // let tooBig: Int8 = Int8.max + 1 // Type conversion for specific number types is handled in an "opt-in" way to prevent unexpected type conversions - you must be explicit let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 // let twoThousandAndOne = twoThousand + one // type error let twoThousandAndOne = twoThousand + UInt16(one) // behind the scenes the UInt16 type has an initializer that accepts a UInt8 type. Due to that, not all types can be used in the UInt16() initializer call // Allowing UInt16 to accept additional types (including custom types) is covered in the section titled "Extensions" // Integer and Floating-Point Conversion // conversions between Integers and Floating Point types must be explicit as well let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine // Floating-Point to Int must be explicit too // Initializing a new Int using a floating-point source will always truncate the value let integerPi = Int(pi) let allowed = 3 + 0.145 // allowed since the literals have no type, it is only infered at compile time when evaluated /* Type Aliases */ // Type aliases define an alternative name for an existing type. // An alias can be used to create descriptive types/names when working with an external data source typealias AudioSample = UInt16 AudioSample.max /* Tuples */ // tuples group multiple values into a single compound value. The values can be of any type var notFound = (404, "Not Found") // the notFound tuple can be described as "a tuple of type (Int, String)" // you can have any number or combination of types (Int, Int, Int), (Bool, Int, UInt16), etc // to get specific values from a tuple, you "decompose" them: let (statusCode, statusMessage) = notFound print(statusMessage) // to skip values use _ let (_, newStatusMessage) = notFound print(newStatusMessage) // tuples can also be accessed using index values and dot notation: notFound.0 // elements can also be named let myName = (first: "Austin", last: "Rude") myName.first myName.0 // index values still work // Tuples are useful as return values for functions. It's a method to return multiple values from a function // Tuples are good for temporary data in a single scope, if the data will be passed to other scopes or is complex then a struct or class is more appropriate /* Basic Operators */ // Nil Coalescing Operator // Provides an elegent way to do conditional checking and unwrap the optional // unwraps an optional a if it contains a value, otherwise returns b // b must be the same type of a // (a ?? b) // if a != nil, it short-circuits (b never is evaluated) // shorthand of the following ternary conditional operator syntax: // a!= nil a! : b let defaultColorName = "Red" var userDefinedColorName: String? var colorName = (userDefinedColorName ?? defaultColorName) /* Strings and Characters */ // Remeber strings are value types, you are always working with a copy when passing them to a function, etc. // NSString in cocoa is different, when creating an NSString instance and passing it to a function, you are passing a reference! You only use a copy when specifically requesting it! // Unicode // Swift's String and Unicode types are fully unicode compliant // Unicode Scalars // Behind the scenes the String type is built from Unicode scalar values // Unicode scalar is a 21 bit number for a character or modifier, such as U+0061 for "a" or U+1F425 for "FRONT-FACING BABY CHICK" - 🐥 // unicode scalar - u{1-8 digit hex number} let heart = "\u{1F496}" // Extended Grapheme Clusters // A Character instance represents an extended grapheme cluster // an extended grapheme cluster is a sequence of one or more unicode scalars that produce a single human-readable character let eAcute = "\u{00e9}" // Character type let eAcute2 = "\u{65}\u{301}" // Character type let testString = "T\u{65}\u{301}his is just a test" let testIndex = testString.startIndex.successor() // successor returns the next human-readable Character testString[testIndex] let testIndex2 = testString.endIndex.predecessor() // predecessor returns the previous human-readable Character testString[testIndex2] /* Unicode Representations of Strings */ let dogString = "Dog\u{203C}\u{1F436}" // UTF-8 uses an 8-bit(using UInt8 values) representation for each character for char in dogString.utf8 {print(char)} // UTF-16 uses a 16-bit(using UInt16 values) representation for each character for char in dogString.utf16 {print(char)} // Unicode Scalar Representation uses a 21-bit(using UInt32 values) representation for each character for char in dogString.unicodeScalars {print(char)} /* Collection Types */ // Dictionaries // unordered key/value store // Swift's Dictionary type is bridged with Foundation's NSDictionary class // A dictionary key MUST conform to the Hashable protocol var dict = [Int: String]() dict[0] = "Zero" dict[1] = "One" dict dict.count // empty a dictionary // dict = [:] // keeps types // create a dictionary with a dictionary literal var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] // test if dict has data airports.isEmpty // update an existing value airports["LHR"] = "London" airports["LHR"] = "London Heathrow" airports.updateValue("London", forKey: "LHR") airports // remove a pair airports["LHR"] = nil airports.removeValueForKey("DUB") airports // Loop over a Dictionary for (key, value) in airports { print(key) print(value) } // get the keys or values into an Array var airportsArray = [String](airports.keys) /* Control Flow */ // Tuples // Tuples can be used to test multiple values in a switch statement // If you want to accept any value in the tuple, use _ let somePoint = (1, 0) switch somePoint { case (0, 0): print("At the center") case (0, _): print("On the x-axis") case (_, 0): print("On the y-axis") case (-2...2, -2...2): print("In a box between (-2, -2) and (2, 2)") default: print("At \(somePoint.0), \(somePoint.1)") } // unlike C, swift allows multiple matching switch cases. When multiples matches are possible, the first matching case is always used // Value Bindings // a switch case can bind values it matches to temporary variables/constants: var someOtherPoint = (1, 5) switch someOtherPoint { case (0, let y): print("On the x-axis, at \(y)") case (let x, 0): print("On the y-axis, at \(x)") case let (x, y): // since this case matches all other possible values, a default case is not required! print("At \(x), \(y)") } // var and let work, if using var the variable is only for the scope/lifetime of the case // Where // a switch case can use a where clause to check for additional conditions someOtherPoint = (5, 5) switch someOtherPoint { case (let x, let y) where x == y: print("\(x) == \(y) is on the line where x == y") case (let x, let y) where x == -y: print("\(x) == \(y) is on the line where x == -y") case let (x, y): print("At \(x), \(y)") } // the switch case only matches if the where condition evaluates to true /* Functions */ // Functions with Multiple Return Values // a tuple can be used to return multiple values from a function as part of one compound value func minMax(array: [Int]) -> (min: Int, max: Int) { return (array.minElement()!, array.maxElement()!) } // minMax returns both the min and max item in the array as a tuple of type (Int, Int) var results = minMax([1, 60, 5, 9]) results.min results.max // since the return tuple members were labeled, you can use dot notation to retrieve the values // Optional Tuple Return Types // If the tuple type being returned can have "no value", you can use an optional tuple return type // specified with a question mark after the type definition: (Int, String)? func minMaxSafe(array: [Int]) -> (min: Int, max: Int)? { if !array.isEmpty { return (array.minElement()!, array.maxElement()!) } else { return nil } } // minMax returns both the min and max item in the array as a tuple of type (Int, Int) var safeResults = minMaxSafe([]) // Optional binding can be used to extract a value if let theResult = minMaxSafe([5, 2, 33]) { print("The min is \(theResult.min) and the max is \(theResult.max)") } // Function Parameter Names // Functions parameters have both an external and a local parameter name // the internal name is only used within the function // by default the first parameter omits its external name, and the other parameters use their loca names as their external name: func doSomething(myParam1: Int, myParam2: Int) -> Int { return (myParam1 + myParam2) } doSomething(2, myParam2: 3) // all parameters must have unique kicak nanesm but may share external names // Specifying External Parameter Names func doSomethingElse(ext local: String) { print(local) } doSomethingElse(ext: "Test") // if you provide an external parameter name for a parameter, it must ALWAYS be used when calling the function func sayHello(to person1: String, and person2: String) { print("Hi \(person1) and \(person2)") } sayHello(to: "Zoey", and: "Sasha") // using expressive external parameter names as above is considered good style // Omitting External Parameter Names // You can omit the 2nd and beyond external parameter names by using _ // the first parameter's external name is _ by default func someFunction(firstParameterName: Int, _ secondParameterName: Int) -> Int { return firstParameterName + secondParameterName } someFunction(1, 5) // Default Parameter Values // place default parameters at the end of the argument list. It ensures calls to the function use the same order for non-default parameters func myNewFuncWithDefaultParam(highScore: Int = 0) -> Int { return highScore } myNewFuncWithDefaultParam(555) // Variadic Parameters // a variadic parameter accepts 0 or more values of a specified type // Specify a variadic parameter by putting ... immediately after the parameter type func sumMultipleInts(numbers: Int...) -> Int { var total = 0 for number in numbers { total += number } return total } sumMultipleInts(5, 20, 11, 30, 55) func arithmeticMean(numbers: Double...) -> Double { var total = 0.0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(22, 21, 20) // a function can have only one variadic parameter, and it must be the last parameter in the parameter list // Constant and Variable Parameters // function parameters are constants by default - attempting to change them in the function body is a compile error // to get a modifiable copy of the variable, use the prefix var: func alignRight(var string: String, totalLength: Int, pad: Character) -> String { let amountToPad = totalLength - string.characters.count if amountToPad < 1 { return string } let padString = String(pad) for _ in 1...amountToPad { // string can be modified due to the var keyword in the parameter list, otherwise this wouldn't compile // the variable parameter only exists in the function body string = padString + string } return string } let originalString = "hello" let paddedString = alignRight(originalString, totalLength: 20, pad: " ") // In-Out Parameters // unlike variable parameters above, In-Out parameters can be used to make modifications in the function persist // in-out parameters are specified with the `inout` keyword // an inout parameter is passed into the function, modified, and passed back out of the function to replace the original value // only a variable (var) can be an inout, a constant (let) is not allowed // in the function call, you place an & before the parameter ot indicate you know it can be modified by the function // inout's cannot have default values, and variadic parameters cannot be inout // if you mark a parameter inout, it cannot also be marked var or let func swapTwoInts(inout a: Int, inout _ b: Int) { let originalA = a a = b b = originalA } var a = 1 var b = 2 swapTwoInts(&a, &b) a b // inout parameters are an alternative way to modify data outside of a function (versus returning a value) /* Closures */ // capturing values // a closure can capture values outside it's scope, and refer to/modify them within it's body, even though the original scope no longer exists // a nested function is the simplest example of a closure // -> Void -> Int means it returns a function which returns an Int func makeIncrementer(amount: Int) -> Void -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } let incrementByTen = makeIncrementer(10) // makeIncrementer returns a function which increments by 10 incrementByTen() incrementByTen() // notice how the value of runningTotal is persisted - it is a reference within incrementor() // even though incrementByTen() returned, it still holds a reference to the existing runningTotal amount // since amount isn't mutated, it is stored as a copy of the value incrementByTen() // Swift determines what hsould be by value and by reference, it also does all the memory management let incrementBySeven = makeIncrementer(7) // incrementBySeven and incrementByTen contain different references and are independent incrementBySeven() incrementByTen() incrementBySeven() // if you assign a closure to a property of a class instance, the closure captures the instance. You create a strong reference cycle between the closure and the instance. // these reference cycles can be broken with "capture lists" // Closures are Reference Types // incrementBySeven() and incrementByTen() were able to increment their runningTotal because functions AND closures are reference types // here we're assigning a REFERENCE to incrementByTen. let specifies that the reference cannot be changed, not that the function can't return a different value let anotherIncrementByTen = incrementByTen anotherIncrementByTen() /* Enumerations */ // an enumeration defines a common type for a group of related values, and allows you to work with those values in a type-safe way // enumerations are first-class types, with many features traditionally supported only by classes: computed properties, instance methods, inititializers, extensions, and protocols. // Enumeration Syntax enum CompassPoint { case North case South case East case West case Unknown } // North, South, etc are member values (or members) // multiple members can be on a single line: /* enum CompassPoint { case North, South, East, West } */ // an enum definition defines a new type, so it should be Capitalized // give enumeration types singular rather than plural names var directionToHead = CompassPoint.West // now that directionToHead is declared as a CompassPoint, we can use dot syntax directionToHead = .South // Swift knows this is a CompassPoint, so we must mean CompassPoint.East switch directionToHead { case .North: print("Say Hi to Santa!") case .East: print("Where the sun rises") case .West: print("Where the skies are blue") case .South: print("Watch out for penguins") default: print("Be careful!") } // Associated Values // store values of different types in an enum enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) // when re-assigning to .QRCode, the UPCA is released. Variables of the Barcode type can hold a UPCA or QRCode, not BOTH at once! productBarcode = .QRCode("ABC") switch productBarcode { //case .UPCA(let numberSystem, let manufacturer, let product, let check): // for when all members aren't constants case let .UPCA(numberSystem, manufacturer, product, check): print("\(manufacturer), \(product)") case .QRCode(let code): print("\(code)") } // Raw Values // alternative to associated values, these enum members are prepopulated with default values (called raw values) enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" } // raw values are prepopulated and predefined in the enum definition // raw values can be strings, characters, or any of the integer or floating-point types // the raw value for a particular enum is always the same // they differer from associated values - which are set when you create a new constant or variable based on one of the enum's members, // Auto-incrementation increments the raw value for each enum member enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } let earthsOrder = Planet.Earth.rawValue // access the raw value with .rawValue // an enum with a type of rawValue (Int, Double, String, etc) automatically gets an initializer that accepts a rawValue type let seventhPlanet = Planet(rawValue: 7) // returns Planet?, it is a failable initializer seventhPlanet! // optional binding to a switch statement if let somePlanet = Planet(rawValue: 9) { switch somePlanet { case .Earth: print("Safe for humans") default: print("Not safe for humans") } } else { print("Planet not found") } /* Classes and Structures */ // Structures and Enumerations are value types // all of the basic types in Swift (Integer, Double, Dictionary, String, Boolean, and Array) are actually Structs behind the scene, which are value types // All structures and enums are value tyupes in Swift // Any structure or enumeration instances you create are always copied when passed around in code struct Resolution { var width = 0 var height = 0 } let hd = Resolution(width: 1920, height: 1080) var cinema = hd // a copy of hd is made, and assigned to cinema. Even though they share the same width, height, cinema and hd are two seperate instances cinema.width = 2048 cinema.width hd.width // enums are also by value var currentDirection = CompassPoint.West let rememberedDirection = currentDirection currentDirection = .East rememberedDirection // still .West, since a copy was made // Classes are Reference Types // When assigned to a variable/constant or passed to a function, a reference to the existing instance is passed class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 // tenEighty is a constant instance of the VideoMode class let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 tenEighty.frameRate // because classes are reference types, tenEighty and alsoTenEighty are just references to the same class instance // Identity Operators // to test whether two variables/constants point to the exact same instance of a class // === - test equal // !== - test not equal if tenEighty === alsoTenEighty { print("tenEighty and alsoTenEighty are the exact same class instance") } // Choosing between Classes and Structures // Consider using a structure when one or more of the following apply // - The structures primary purpose is to encapsulate a few relatively simply data values // - It is reasonable to expect the enacapsulated values will be copied when assigning or passing around an instance of the structure // - Any properties stored by the structure are themselves value types, which would be expected to be copied rather than referenced // - the structure does not need to inherit properties or behavior from another existing type // Examples of good candidates for a struct // - the size of a geometric shape, with width/height properties of type Double // - a way to refer to ranges within a series, with a start and length property, both of type Int // - a point in a 3D coordinate system, with properties x, y, and z of type Double // In all other cases, define a class, create an instance of the class to be managed and passed by reference. // Classes should be the most common data structure in practice - NOT structures // Assignment and Copy Behavior for Strings, Arrays, and Dictionaries // Swift's String, Array, and Dictionary types are implemented as structures // This is different then Foundation, where NSString, NSArray, and NSDictionary are implemented as classes.i // Swift optimized the memory management of copying, and only does it when necessary. Don't avoid assignment/copying - let Swift handle the optimization /* Properties */ // Lazy Stored Properties // a Lazy Stored Property is a property whose value isn't calculated until it is first used. // it is indicated with the "lazy" modifier before the declaration // a lazy property must always be declared as a variable - it cannot be a constant since it's value is assigned after initialization (constants must have a value before initialization) // lazy properties are useful when the initial property is dependent on outside factors whose values aren't known until after initialization is complete // also useful if the setup of the property is expensive/complex, and shouldn't be done unless/until it is needed. // a use case might be reading a file into memory - we don't want to do that on initialization because it can be time consuming, so using lazy would be a good fit // if multiple threads access a lazy property simultaneously, the property may be initialized more than once // Property Observers // property observers observer and respond to changes in a properties value. // they are called every time a properties value is set - even if the value is the same as the existing value // they can be added to any stored property (except lazy stored properties) // they can be added to any inherited property (whether stored or computed) by overriding the property within a subclass (see Overriding chapter) // not needed for non-overridden computed properties, because you can use the setter instead. // you can define either or both of the observers on a property: // willSet - called just before the value is stored // didSet - called immediately after the new value is stored // willSet is passed the new property value, you can specify a name, if not the default name of "newValue" is used // didSet is passed the old value, you can specify a name, if not the default name of "oldValue" is used // willSet and didSet are not called when a value is set in an initializer before delegation takes place class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set steps to \(newTotalSteps)") } didSet { // no custom name, using default oldValue name print("Changed steps from \(oldValue) to \(totalSteps)") // totalSteps += 1 // this would NOT trigger willSet/didSet again } } } var steps = StepCounter() steps.totalSteps = 5 steps.totalSteps = 19 steps.totalSteps = 19 // willSet and didSet property observers are still called // Global and Local Variables // a global is defined outside any function, method, closure or type // global constants and variables are always computed lazily, but do not need the lazy modifier // local constants and variables are never computed lazily (unless using the lazy keyword) // Type Properties // properties assigned to the type rather than the instance. Only one set for the type. // useful for values that are universal to all instances of a type, such as a constant property all instances can use // for value types (structures and enumerations) you can define stored and computed TYPE properties // for reference types (classes) you can only define computed TYPE properties // unlike stored instance properties, stored type properties MUST be given a default value (since the type itself has no initializer) // type properties are defined with the static keyword (for classes with computed type properties, you can use the class keyword instead so subclasses can override) struct SomeStructure { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } } // although the examples above only show read only computed type properties, read/write can be used // Querying and Setting Type Properties // type properties are queries and set with dot syntax, but on the TYPE rather than the instance! SomeClass.storedTypeProperty = "Some other value" SomeClass.storedTypeProperty struct Player { static let maxHP = 100 // could make this a var and update it in currentHP's didSet var currentHP:Int = 100 { didSet { if currentHP > Player.maxHP { currentHP = Player.maxHP } } } } var me = Player() me.currentHP = 1000 me.currentHP me.currentHP = 99 me.currentHP /* Methods */ // Instance Methods // Classes, Enumerations, and Structures can all define instance (and type) methods // provide ways to access and modify the instances properties, or by providing functionality related to the instances purpose // instance methods have the exact same syntax as functions class Counter { var count = 0 func increment() { ++count } func decrement() { --count } // refer to the methods first parameter using a preposition such as with, for, or by: func incrementBy(val: Int) { // this method name is good style. It can be read as a sentence. count += val } } var myCounter = Counter() myCounter.incrementBy(56) myCounter.count // modifying external parameter names class Table { var legs = 4 func increaseLegsTo(newLegCount newLegCount: Int) { // double up the parameter name to make it required in the func call legs = newLegCount } } var kitchenTable = Table() kitchenTable.increaseLegsTo(newLegCount: 6) kitchenTable.legs // The self Property // Every instance has an implicit property called self, which is exactly equivelent to the instance itself // self rarely needs used, the main exception is when an instance method parameter name is the same as an instance property (the parameter name takes precedence) /* // this should work but doesn't compile. Using an online compiler it works with Swift 1.2 and 2.0, not sure what the deal is struct NewPoint { var x = 0.0, y = 0.0 func isToTheRightOfX(x: Double) -> Bool { return self.x > x } } let somePoint = NewPoint(x: 4.1,y: 5.2) somePoint.isToTheRightOfX(1.3) */ // Modifying Value Types from Within Instance Methods // By default properties of a value type (struct and enum) cannot be modified from within its instance methods // however, a method can be marked with the mutating keyword to permit the behavior (changes to properties are written when the method ends) // mutating instance methods can set the self property to a new instance of the type, replacing itself when the method ends struct Enemy { var health = 100 mutating func reduceHealthBy(hp: Int) { health -= hp } mutating func respawn() { self = Enemy() } } var bigBoss = Enemy() bigBoss.health bigBoss.reduceHealthBy(20) bigBoss.health // respawn sets self = Enemy() // this replaces the current instance with a newly created one bigBoss.respawn() bigBoss.health let immortalBoss = Enemy() //immortalBoss.reduceHealthBy(5) // not allowed, constants can't use mutating instance methods! // enum mutating method example enum PlayerState { case Dead, Alive mutating func killOrRespawn() { switch self { case Dead: self = PlayerState.Alive case Alive: self = PlayerState.Dead } } } var myState = PlayerState.Alive myState.killOrRespawn() myState // Type Methods // methods that are called on the type itself. Work for classes, enums, and structs // use the "static" keyword to signify a type method // use "class" to allow subclasses to override class SomeNewClass { class func someTypeMethod() { print("called") // self in the type method would refer to the type itself // calling other type methods doesn't require the type name, this type and it's properties are in scope } } SomeNewClass.someTypeMethod() /* Subscripts */ // subscripts are shortcuts for accessing and modifying elements of a list, collection or sequence. // classes, structure, and enumerations can define subscripts. // subscripts can be read/write or read only. this is chosen by implementing a getter and/or setter (same as computed properties /* subscript(index: Int) -> Int { get { // return an Int } set(newValue) { // set it to the new value } } */ struct TimesTable { let multiplier: Int // read-only subscript (can drop the get {} ) // using a read-only subscript makes sense, a times table is static and based on mathematical rules subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) threeTimesTable[5] // Subscript Usage // The Disctionary type implements subscript behind the scenes. (the subscript returns an Optional) // Subscript options // subscripts can take any number of input parameters, and can return any type. // subscripts can use variable and variadic parameters, but cannot use in-out parameters or provide default param values // a class or struct can provide as many subscript implementations it needs, and the correct implementation will be inferred using the types of the value(s) in the subscript braces[]. This is known as subscript overloading struct Matrix { let rows: Int, cols: Int var grid: [Double] init(rows: Int, cols: Int) { self.rows = rows self.cols = cols grid = Array(count: rows * cols, repeatedValue: 0.0) } func indexIsValidForRow(row: Int, col: Int) -> Bool { return row >= 0 && row < rows && col >= 0 && col < cols } subscript(row: Int, col: Int) -> Double { get { assert(indexIsValidForRow(row, col: col), "Index out of range") return grid[(row*cols) + col] } set { assert(indexIsValidForRow(row, col: col), "Index out of range") return grid[(row*cols) + col] = newValue } } } var matrix = Matrix(rows: 2, cols: 2) matrix[0, 1] = 5 matrix[0, 1] matrix[0,0] // 0 /* Inheritance */ // classes can inherit methods, properties, and subscripts. // a subclass inherits from a class (that class is called the superclass) // the subclass can override the superclass, replacing the superclasses behavior/etc with it's own // classes can also add property observers to inherited properties and be notified of changes // Defining a Base Class // any class that doesn't inherit from another class is known as a base class // swift doesn't have a universal/default inherited class. all classes are base classes unless you specify a superclass class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() { // do nothing } } let someVehicle = Vehicle() someVehicle.currentSpeed = 5.3 someVehicle.description /* Subclassing */ // subclassing is the act of basing a new class off an existing class // you inherit it's characteristics, which can then be refined (or added to). // a subclass is declared by listing the superclass name, after the class name and following a colon class Bicycle: Vehicle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket bicycle.currentSpeed = 15.0 bicycle.description // subclasses can be subclassed class Tandem: Bicycle { var currentNumberOfPassengers = 0 } let tandem = Tandem() // tandem inherites from Bicycle, which inherits from Vehicle tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 350.0 tandem.description // Overriding // overriding is when a subclass supplies it's own implementation of an instance method, type method, instance property, type property, or subscript // to override something, just use the override keyword // it can be useful to access the superclass properties, methods, or subscripts when overriding - to do so use the super keyword // super.someMethod() // access an overridden method within the overriding method implementation // super.someProperty // access an overridden property in a getter/setter // super[someIndex] // access the superclass version of a subscript within the overriding implementation // Overriding Methods class Train: Vehicle { override func makeNoise() { print("Choo Choo!!") } } let train = Train() train.makeNoise() // Overriding Properties // the getter and setter of an inherited instance or type property can overridden // a custom getter and setter can be used to override any inherited property, both stored and computed. // Overriding Property Getters and Setters // a subclass doesn't know if an inherited property is stored or computed (it only knows the name and type to check that the superclass has a matching property) // if you provide a setter as part of a property override, you must provide a setter // if you don't want to override the getter, return super.propertyName from the getter class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear \(gear)" } } var subaru = Car() subaru.description // overriding property observers // to get notified of changes to an inherited property (both stored and calculated) you can use overriding // you cannot add property observers to inherited constant stored properties, or computed read-only properties class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let jeep = AutomaticCar() jeep.currentSpeed = 55.0 jeep.description // Preventing Overrides // to prevent a method, property, or subscript from being overridden mark it as "final" // any attemot to override when marked final is a compile-time error // a class can also be marked final, which prevents it from being subclassed /* Initialization */ // initialization is the process of preparing a class, enum, or struct for use // initializers are to make sure a class instance is ready before its first use // deinitializers can also be implemented, to perform cleanup before an instance is deallocated // Setting initial values for stored properties // classes and structures MUST set all stored properties to a value - either as a default, or in the initializer // note: using a default value or setting the value in the initializer will NOT trigger any property observers // Initializers struct Farenheit { var temparature: Double // this would work too (then the init() wouldn't be necessary) // var temparature = 32.0 init() { temparature = 32.0 } } var f = Farenheit() f.temparature // Customizing Initialization // Initialization Parameters // parameters can be used in the initializers definition to provide custom initializers based on the parameters provided struct Celsius { var temparatureInCelsius: Double init(fromFarenheit farenheit: Double) { temparatureInCelsius = (farenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temparatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFarenheit: 212.0) boilingPointOfWater.temparatureInCelsius let freezingPointOfWater = Celsius(fromKelvin: 273.15) freezingPointOfWater.temparatureInCelsius struct Color { var red: Double, green: Double, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white } } var halfGray = Color(white: 0.5) var magenta = Color(red: 1.0, green: 0.0, blue: 1.0) // note: Swift provides an external parameter name for EVERY initialization parameter, since their names help identify the initializer being used. It's the same as if every parameter had a hash tag before it // initalizer external names must always be used if provided, otherwise it's a compile-time error // var errorColor = Color(0.5) // Initializer Parameters Without External Names // to not use the external parameter name(s) use a _ in the initializer definition: // init(_ celsius: Double) { // temparatureInCelsius = celsius // } // Optional Property Types // optional properties don't have to be initialized, are nil until a value is assigned // Constants in Initializers // you can wait to assign a value to a constant property until the initializer. It MUST have a value by the time initialization finished class SurveyQuestion { let text: String // constant is set in the init() var response: String? // optional property (notice it isn't assigned in the init() either) init(text: String) { self.text = text } func ask() { print(text) } } var question = SurveyQuestion(text: "What is your favorite color?") question.ask() question.response = "BLUE!!!" // Default Initializers // if a base class or structure has default values for all of it's properties and an init() isn't implemented, Swift provides a default initializer which sets all of the properties to their default values class ShopppingListItem { var name: String? // optionals automatically has a default value of nil var quantity = 1 var purchased = false } var milk = ShopppingListItem() // Memberwise initializers for struct // structures automatically geta memberwise initializer, if an init isn't implemented - even when its stored properties don't have default values // initial values are passed by name struct Size { var width, height: Double } var twoByTwo = Size(width: 2.0, height: 2.0) /* Initializer Delegation for Value Types */ // initializers calling other initializers - avoids duplicating code // value types (struct and enum) don't support inheritance, therefore can only delegate to other initializers they implement // classes can inherit and thus need to ensure all stored properties (including inherited ones) are assigned a value) // for value types, you use self.init to refer to other initializers (from the same value type) // implementing an init on a value type causes you to lose the default init and memberwise initializer struct SizeWithDefault { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = SizeWithDefault() // this is a replacement for the default initializer we lost (due to implementing custom initializers) // it takes no arguments and uses the stored properties default values, and allows us to create an instance with var x = Rect() init() {} // same as the memberwise initializer we would have had we not implemented custom initializers init(origin: Point, size: SizeWithDefault) { self.origin = origin self.size = size } // calculates the center of the point to use as the origin, then it calls(delegates) to the init(origin, size) initializer init(center: Point, size: SizeWithDefault) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let basicRect = Rect() let originRect = Rect(origin: Point(x: 1.0, y: 2.0), size: SizeWithDefault(width: 5.0, height: 10.0)) let centerRect = Rect(center: Point(x: 1.0, y: 2.0), size: SizeWithDefault(width: 5.0, height: 10.0)) /* Setting a Default Property Value with a Closure or a Function */ // useful if a property requires customization or setup // when a new instance is created, the return value of the closure or function is assigned to the property // Note: You cannot access self. or other properties in the closure or function, as they have not been initialized // when using a closure to assign a property value at initialization, remember to include empty parens () so swift knows you want to execute the closure immediately and assign it's return value. Otherwise the closure itself is assigned! struct CheckerBoard { let boardColors: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...10 { for j in 1...10 { temporaryBoard.append(isBlack) isBlack = !isBlack } isBlack = !isBlack } return temporaryBoard }() // don't forget the parens when assigning a closure as a default property value func squareIsBlackAtRow(row: Int, column: Int) -> Bool { return boardColors[(row * 10) + column] } } let board = CheckerBoard() board.squareIsBlackAtRow(0, column: 1) board.squareIsBlackAtRow(9, column: 9) /* Type Casting */ // checking the type of a class, or treat it as if it is a different superclass or subclass from its hierarchy // type casting is implemented using the "is" and "as" operators class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } // swift infers the type of [MediaItem] through the common superclass (MediaItem) let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Movie(name: "Goodfellas", director: "Martin Scorsese"), Song(name: "Blue Suede Shoes", artist: "Elvis") ] // items in the array are of type MediaItem, to use them as a Song/Movie they must be check their type, or downcast them to a different type // Checking Type // use the type check operator (is) to check whether an instance is of a certain subclass type // returns true if it is of that subclass type, false if not var movieCount = 0 for item in library { if item is Movie { ++movieCount } } movieCount // Downcasting // a constant or variable of a certain class type may refer to an instance of a subclass behind the scenes. // you downcast the constant/variable as the subclass type using as? or as! // as? returns an optional value of the type trying to be downcast to (since downcasting can fail) // as! downcasts and force-unwraps the result // use as? if you are not sure the downcast will succeed, if it is not successful/possible it's value will be nil // use as! if you are POSITIVE the downcast will succeed - if it doesn't there will be a runtime-error! // use as to force downcast, and doesn't need optional unwrapping. Is always safe in a switch case statement for item in library { // as? returns an optional here, returns Movie?, so we use optional binding to check and create the temp constant if let movie = item as? Movie { print("\(movie.name) directed by \(movie.director)") } } // casting doesn't actually modifiy the instance or change it's value. Casting just changes how it is treated and accessed // Type Casting for Any and AnyObject // Any and AnyObject are type aliases, provided for dealing with non-specific types // AnyObject can represent an instance of any class type // Any can represent an instance of any type, including function types // only use Any/AnyObject when you explicitly need the behavior they provide // AnyObject // Cocoa APIs commonly return an array of AnyObject due to objective-c not having explicitly typed arrays // the API often defines what types are actually held in the returned [AnyObject], in which case you can use "as" which forces the downcast, without the need for optional unwrapping let someObjects: [AnyObject] = [ Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"), Movie(name: "Alien", director: "Ridley Scott") ] for object in someObjects { let movie = object as! Movie print("\(movie.name) directed by \(movie.director)") } // shorter version, downcasts the entire array rather than each item for movie in someObjects as! [Movie] { print("\(movie.name) directed by \(movie.director)") } // Any var things = [Any]() things.append(0.0) things.append((1.0, 5.2)) things.append("test") things.append(Movie(name: "Jaws", director: "Steven Spielberg")) things.append({ (name: String) -> String in "Hello, \(name)"}) for thing in things { switch thing { case 0 as Int: print("Zero as an Int") case 0 as Double: print("Zero as a Double") case let movie as Movie: print("\(movie.name)") case let text as String: print(text) case let (x, y) as (Double, Double): print("coordinate at \(x), \(y)") default: print("Unknown!") } } // notice the use of the forced version of the type cast operator (as) to check and cast to a type. It is always safe to use in a switch statement /* Nested Types */ // Allow types to have supporting types nested, which help them provide their functionality struct BlackJackCard { // nested Suit enum enum Suit: Character { case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣" } enum Rank: Int { case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King, Ace struct Values { let first: Int, second: Int? } var values: Values { switch self { case .Ace: return Values(first: 1, second: 11) case .Jack, .Queen, .King: return Values(first: 10, second: nil) default: return Values(first: self.rawValue, second: nil) } } } let rank: Rank, suit: Suit var description: String { var output = "Suit is \(suit.rawValue)," output += " value is \(rank.values.first)" if let second = rank.values.second { output += " or \(second)" } return output } } let theAceOfSpades = BlackJackCard(rank: .Ace, suit: .Spades) theAceOfSpades.description // referring to a nested type outside the context it is defined: let heartSymbol = BlackJackCard.Suit.Hearts.rawValue /* Advanced Operators */ // Overflow Operators // if you try to assign a value to a variable that doesn't fit, Swift gives you an error // this gives some safety over the alternative - creating an incorrect value // Overflow Operators allow you to opt-in to truncating the values, rather than throwing an error // Overflow addition (&+) // Overflow subtraction (&-) // Overflow multiplication (&*) // numbers can overflow in both the positive and negative direction var unsignedOverflow = UInt8.max // 11111111 unsignedOverflow = UInt8.max &+ 1 // 100000000 unsignedOverflow // negative overflow unsignedOverflow &- 1 // signed overflow var signedOverflow = Int8.min // 10000000 signedOverflow &- 1 // 01111111 - subtracting 1 wraps around and the sign is reversed
35.105263
236
0.718737
d9db09dfb9b92828a4eba4e696bb80c3203448d0
2,492
// // ComposeTweetViewController.swift // tweety // // Created by Gale on 2/27/16. // Copyright © 2016 Gale. All rights reserved. // import UIKit @objc protocol ComposeTweetViewControllerDelegate { optional func composeTweetViewController(composeTweetViewController: ComposeTweetViewController, didUpdateTweet newTweet: Tweet) } class ComposeTweetViewController: UIViewController { weak var delegate: ComposeTweetViewControllerDelegate? @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var tweetTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() tweetTextField.becomeFirstResponder() countLabel.text = "\(140 - tweetTextField.text!.characters.count)" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Button Actions @IBAction func onCloseButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onTweetButton(sender: AnyObject) { let apiParameters = NSMutableDictionary() apiParameters["status"] = tweetTextField.text! TwitterClient.sharedInstance.replyToTweetWithCompletion(apiParameters) { (tweet, error) -> () in if tweet != nil { self.delegate?.composeTweetViewController!(self, didUpdateTweet: tweet!) self.dismissViewControllerAnimated(true, completion: nil) } } } // MARK: - Text Field Functions func checkMaxLength(textField: UITextField!, maxLength: Int) { if tweetTextField.text!.characters.count > maxLength { textField.deleteBackward() } } @IBAction func onEditingText(sender: AnyObject) { checkMaxLength(sender as! UITextField, maxLength: 140) countLabel.text = "\(140 - tweetTextField.text!.characters.count)" print(tweetTextField.text!.characters.count) } /* // 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. } */ }
31.544304
132
0.676164
18be31e47055a8752980326027fb6430fdb378b6
1,678
// // DepressingButton.swift // Animase // // Created by Camvy Films on 2015-03-03. // Copyright (c) 2015 June. All rights reserved. // import UIKit ///An extension to allow a depressing animation when touched down extension UIButton { func setupDepression() { addTarget(self, action: "didTouchDown:", forControlEvents: .TouchDown) addTarget(self, action: "didTouchDragExit:", forControlEvents: .TouchDragExit) addTarget(self, action: "didTouchUp:", forControlEvents: .TouchUpInside) } func didTouchDown(button:UIButton) { UIView.animateWithDuration(0.07){ self.transform = CGAffineTransformMakeScale(0.98, 0.98) } } func didTouchDragExit(button:UIButton) { UIView.animateWithDuration(0.07){ self.transform = CGAffineTransformMakeScale(1, 1) } } func didTouchUp(button:UIButton) { UIView.animateWithDuration(0.07){ self.transform = CGAffineTransformMakeScale(1, 1) } } override public func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { let exitExtension: CGFloat = 5 let outerBounds: CGRect = CGRectInset(self.bounds, -exitExtension, -exitExtension) let touchOutside: Bool = !CGRectContainsPoint(outerBounds, touch.locationInView(self)) if touchOutside { let previousTouchInside = CGRectContainsPoint(outerBounds, touch.previousLocationInView(self)) if previousTouchInside { sendActionsForControlEvents(.TouchDragExit) return false } else { sendActionsForControlEvents(.TouchDragOutside) return false } } return super.continueTrackingWithTouch(touch, withEvent: event) } }
31.074074
100
0.713945
6417b6da3d0be8dd25e8c75550a3b7c875bfddbb
11,881
// RUN: %target-typecheck-verify-swift -swift-version 3 //===----------------------------------------------------------------------===// // Deduction of generic arguments //===----------------------------------------------------------------------===// func identity<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> Int { return 0 } struct X { } struct Y { } func useIdentity(_ x: Int, y: Float, i32: Int32) { var x2 = identity(x) var y2 = identity(y) // Deduction that involves the result type x2 = identity(17) var i32_2 : Int32 = identity(17) // Deduction where the result type and input type can get different results var xx : X, yy : Y xx = identity(yy) // expected-error{{cannot assign value of type 'Y' to type 'X'}} xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} } // FIXME: Crummy diagnostic! func twoIdentical<T>(_ x: T, _ y: T) -> T {} func useTwoIdentical(_ xi: Int, yi: Float) { var x = xi, y = yi x = twoIdentical(x, x) y = twoIdentical(y, y) x = twoIdentical(x, 1) x = twoIdentical(1, x) y = twoIdentical(1.0, y) y = twoIdentical(y, 1.0) twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func mySwap<T>(_ x: inout T, _ y: inout T) { let tmp = x x = y y = tmp } func useSwap(_ xi: Int, yi: Float) { var x = xi, y = yi mySwap(&x, &x) mySwap(&y, &y) mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} // expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}} mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func takeTuples<T, U>(_: (T, U), _: (U, T)) { } func useTuples(_ x: Int, y: Float, z: (Float, Int)) { takeTuples((x, y), (y, x)) takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} // FIXME: Use 'z', which requires us to fix our tuple-conversion // representation. } func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {} func passFunction(_ f: (Int) -> Float, x: Int, y: Float) { acceptFunction(f, x, y) acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}} func testReturnTuple(_ x: Int, y: Float) { returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}} var _ : (Int, Float) = returnTuple(x) var _ : (Float, Float) = returnTuple(y) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) { confusingArgAndParam(g, f) confusingArgAndParam(f, g) } func acceptUnaryFn<T, U>(_ f: (T) -> U) { } func acceptUnaryFnSame<T>(_ f: (T) -> T) { } func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { } func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { } func unaryFnIntInt(_: Int) -> Int {} func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}} func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}} // Variable forms of the above functions var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt func passOverloadSet() { // Passing a non-generic function to a generic function acceptUnaryFn(unaryFnIntInt) acceptUnaryFnSame(unaryFnIntInt) // Passing an overloaded function set to a generic function // FIXME: Yet more terrible diagnostics. acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}} acceptUnaryFnSame(unaryFnOvl) // Passing a variable of function type to a generic function acceptUnaryFn(unaryFnIntIntVar) acceptUnaryFnSame(unaryFnIntIntVar) // Passing a variable of function type to a generic function to an inout parameter acceptUnaryFnRef(&unaryFnIntIntVar) acceptUnaryFnSameRef(&unaryFnIntIntVar) acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}} } func acceptFnFloatFloat(_ f: (Float) -> Float) {} func acceptFnDoubleDouble(_ f: (Double) -> Double) {} func passGeneric() { acceptFnFloatFloat(identity) acceptFnFloatFloat(identity2) } //===----------------------------------------------------------------------===// // Simple deduction for generic member functions //===----------------------------------------------------------------------===// struct SomeType { func identity<T>(_ x: T) -> T { return x } func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}} func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}} func returnAs<T>() -> T {} } func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) { var st = sti, i = ii, f = fi i = st.identity(i) f = st.identity(f) i = st.identity2(i) f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}} i = st.returnAs() f = st.returnAs() acceptFnFloatFloat(st.identity) acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}} acceptFnDoubleDouble(st.identity2) } struct StaticFuncs { static func chameleon<T>() -> T {} func chameleon2<T>() -> T {} } struct StaticFuncsGeneric<U> { // FIXME: Nested generics are very broken // static func chameleon<T>() -> T {} } func chameleon<T>() -> T {} func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) { var x: Int16 x = StaticFuncs.chameleon() x = sf.chameleon2() // FIXME: Nested generics are very broken // x = sfi.chameleon() // typealias SFI = StaticFuncsGeneric<Int> // x = SFI.chameleon() _ = x } //===----------------------------------------------------------------------===// // Deduction checking for constraints //===----------------------------------------------------------------------===// protocol IsBefore { func isBefore(_ other: Self) -> Bool } func min2<T : IsBefore>(_ x: T, _ y: T) -> T { if y.isBefore(x) { return y } return x } extension Int : IsBefore { func isBefore(_ other: Int) -> Bool { return self < other } } func callMin(_ x: Int, y: Int, a: Float, b: Float) { _ = min2(x, y) min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}} } func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} func callRangeOfIsBefore(_ ia: [Int], da: [Double]) { rangeOfIsBefore(ia.makeIterator()) rangeOfIsBefore(da.makeIterator()) // expected-error{{type 'Double' does not conform to protocol 'IsBefore'}} } func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {} // expected-note@-1 {{candidate requires that the types 'Int' and 'Double' be equivalent (requirement specified as 'A.Element' == 'B.Element' [with A = IndexingIterator<[Int]>, B = IndexingIterator<[Double]>])}} func compareIterators() { var a: [Int] = [] var b: [Double] = [] testEqualIterElementTypes(a.makeIterator(), b.makeIterator()) // expected-error@-1 {{cannot invoke 'testEqualIterElementTypes(_:_:)' with an argument list of type '(IndexingIterator<[Int]>, IndexingIterator<[Double]>)'}} } protocol P_GI { associatedtype Y } class C_GI : P_GI { typealias Y = Double } class GI_Diff {} func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {} // expected-note@-1 {{candidate requires that 'GI_Diff' inherit from 'T.Y' (requirement specified as 'T.Y' : 'GI_Diff' [with T = C_GI])}} genericInheritsA(C_GI()) // expected-error@-1 {{cannot invoke 'genericInheritsA(_:)' with an argument list of type '(C_GI)'}} //===----------------------------------------------------------------------===// // Deduction for member operators //===----------------------------------------------------------------------===// protocol Addable { static func +(x: Self, y: Self) -> Self } func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T { u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} return x+y } //===----------------------------------------------------------------------===// // Deduction for bound generic types //===----------------------------------------------------------------------===// struct MyVector<T> { func size() -> Int {} } func getVectorSize<T>(_ v: MyVector<T>) -> Int { return v.size() } func ovlVector<T>(_ v: MyVector<T>) -> X {} func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {} func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) { var i : Int i = getVectorSize(vi) i = getVectorSize(vf) getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}} var x : X, y : Y x = ovlVector(vi) x = ovlVector(vf) var vvi : MyVector<MyVector<Int>> y = ovlVector(vvi) var yy = ovlVector(vvi) yy = y y = yy } // <rdar://problem/15104554> postfix operator <*> protocol MetaFunction { associatedtype Result static postfix func <*> (_: Self) -> Result? } protocol Bool_ {} struct False : Bool_ {} struct True : Bool_ {} postfix func <*> <B>(_: Test<B>) -> Int? { return .none } postfix func <*> (_: Test<True>) -> String? { return .none } class Test<C: Bool_> : MetaFunction { typealias Result = Int } // picks first <*> typealias Inty = Test<True>.Result var iy : Inty = 5 // okay, because we picked the first <*> var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}} // rdar://problem/20577950 class DeducePropertyParams { let badSet: Set = ["Hello"] } // SR-69 struct A {} func foo() { for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}} } let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}} let oi : Int? = 5 let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}} } infix operator +& func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {} // expected-note@-1 {{candidate requires that the types 'String' and 'Character' be equivalent (requirement specified as 'R.Element' == 'S.Element' [with R = [String], S = String])}} func rdar33477726_1() { var arr: [String] = [] arr +& "hello" // expected-error@-1 {{binary operator '+&(_:_:)' cannot be applied to operands of type '[String]' and 'String'}} } func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {} // expected-note@-1 {{candidate requires that the types 'Int' and 'Character' be equivalent (requirement specified as 'S' == 'R.Element' [with R = String, S = Int])}} rdar33477726_2("answer", 42) // expected-error@-1 {{cannot invoke 'rdar33477726_2(_:_:)' with an argument list of type '(String, Int)'}} prefix operator +- prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {} // expected-note@-1 {{candidate requires that the types 'Character' and 'Int' be equivalent (requirement specified as 'T.Element' == 'Int' [with T = String])}} +-"hello" // expected-error@-1 {{unary operator '+-(_:)' cannot be applied to an operand of type 'String'}}
34.638484
211
0.618803
4604a6671906640c3753868ca04d0ef7b1b4c746
11,994
// // ReviewerssController.swift // App // // Created by Oguz Sutanrikulu on 21.03.20. // import Vapor import Leaf struct ReviewersController: RouteCollection { func boot(routes: RoutesBuilder) throws { routes.get("reviewers", use: reviewers) routes.get("reviewers", ":id", "projects", use: reviewerProjects) routes.get("reviewers", ":id", "repositories", use: reviewerRepositories) routes.post("reviewers", ":id", "remove") { req -> EventLoopFuture<Response> in return self.removeReviewer(req: req).transform(to: req.redirect(to: "/reviewers")) } routes.post("reviewers", ":id", "projects", ":projectID", "add") { req -> EventLoopFuture<Response> in guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(req.redirect(to: "/reviewers"))} return self.addProjectReviewer(req: req).transform(to: req.redirect(to: "/reviewers/\(reviewerParameter)/projects")) } routes.post("reviewers", ":id", "projects", ":projectID", "remove") { req -> EventLoopFuture<Response> in guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(req.redirect(to: "/reviewers"))} return self.removeProjectReviewer(req: req).transform(to: req.redirect(to: "/reviewers/\(reviewerParameter)/projects")) } routes.post("reviewers", ":id", "repositories", ":repoID", "add") { req -> EventLoopFuture<Response> in guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(req.redirect(to: "/reviewers"))} return self.addRepositoryReviewer(req: req).transform(to: req.redirect(to: "/reviewers/\(reviewerParameter)/repositories")) } routes.post("reviewers", ":id", "repositories", ":repoID", "remove") { req -> EventLoopFuture<Response> in guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(req.redirect(to: "/reviewers"))} return self.removeRepositoryReviewer(req: req).transform(to: req.redirect(to: "/reviewers/\(reviewerParameter)/repositories")) } routes.post("reviewers") { req -> EventLoopFuture<Response> in let context = try req.content.decode(ReviewerPostCreateContext.self) return self.addReviewer(req: req, context: context).transform(to: req.redirect(to: "/reviewers")) } } func reviewers(req: Request) -> EventLoopFuture<View> { guard req.hasSession else { return req.view.render("login") } return Reviewer.query(on: req.db).all().flatMap { allReviewers in let context = ReviewersContext(reviewers: allReviewers) return req.view.render("reviewers", context) } } func reviewerProjects(req: Request) -> EventLoopFuture<View> { guard req.hasSession else { return req.view.render("login") } guard let reviewerParameter = req.parameters.get("id") else { return req.view.render("index") } guard let reviewerId = Int(reviewerParameter) else { return req.view.render("index") } return Reviewer.find(reviewerId, on: req.db).flatMap { reviewer in guard let reviewer = reviewer else { return req.view.render("index") } return ProjectReviewer.query(on: req.db).with(\.$reviewer).with(\.$project).all().flatMap { projectReviewers in let projectsReviewers = projectReviewers.filter { $0.reviewer.id == reviewerId } let reviewersProjects = projectsReviewers.map { $0.project } return LicoreProject.query(on: req.db).all().flatMap { allProjects in let projects = allProjects.filter { !reviewersProjects.contains($0) } let context = ReviewersProjectContext(reviewer: reviewer, reviewersProjects: reviewersProjects, projects: projects) return req.view.render("reviewerProjects", context) } } } } func reviewerRepositories(req: Request) -> EventLoopFuture<View> { guard req.hasSession else { return req.view.render("login") } guard let reviewerParameter = req.parameters.get("id") else { return req.view.render("index") } guard let reviewerId = Int(reviewerParameter) else { return req.view.render("index") } return Reviewer.find(reviewerId, on: req.db).flatMap { reviewer in guard let reviewer = reviewer else { return req.view.render("index") } return RepositoryReviewer.query(on: req.db).with(\.$reviewer).with(\.$repository).all().flatMap { repositoryReviewers in let repositoryReviewer = repositoryReviewers.filter { $0.reviewer.id == reviewerId } let reviewersRepositories = repositoryReviewer.map { $0.repository } return Repository.query(on: req.db).all().flatMap { allRepositories in let repositories = allRepositories.filter { !reviewersRepositories.contains($0) } let context = ReviewersRepositoryContext(reviewer: reviewer, reviewersRepositories: reviewersRepositories, repositories: repositories) return req.view.render("reviewerRepositories", context) } } } } func addReviewer(req: Request, context: ReviewerPostCreateContext) -> EventLoopFuture<HTTPStatus> { let reviewer = Reviewer(slug: context.slug, name: context.name, email: context.email) return reviewer.save(on: req.db).transform(to: .ok) } func removeReviewer(req: Request) -> EventLoopFuture<HTTPStatus> { guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(.internalServerError) } guard let reviewerId = Int(reviewerParameter) else { return req.eventLoop.future(.internalServerError) } return ProjectReviewer.query(on: req.db).all().flatMap { allProjectReviewers in return RepositoryReviewer.query(on: req.db).all().flatMap { allRepositoryReviewers in allProjectReviewers.forEach { projectReviewer in if projectReviewer.$reviewer.id == reviewerId { projectReviewer.delete(on: req.db) } } allRepositoryReviewers.forEach { repositoryReviewer in if repositoryReviewer.$reviewer.id == reviewerId { repositoryReviewer.delete(on: req.db) } } return Reviewer.find(reviewerId, on: req.db).flatMap { reviewer in guard let reviewer = reviewer else { return req.eventLoop.future(.notFound) } return reviewer.delete(on: req.db).transform(to: .ok) } } } } func addProjectReviewer(req: Request) -> EventLoopFuture<HTTPStatus> { guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(.internalServerError) } guard let reviewerId = Int(reviewerParameter) else { return req.eventLoop.future(.internalServerError) } guard let projectParameter = req.parameters.get("projectID") else { return req.eventLoop.future(.internalServerError) } guard let projectId = Int(projectParameter) else { return req.eventLoop.future(.internalServerError) } return RepositoryReviewer.query(on: req.db).all().flatMap { repositoryReviewers in let removingReviewers = repositoryReviewers.filter { $0.$reviewer.id == reviewerId } removingReviewers.forEach { $0.delete(on: req.db) } return ProjectReviewer(projectID: projectId, reviewerID: reviewerId).save(on: req.db).transform(to: .ok) } } func removeProjectReviewer(req: Request) -> EventLoopFuture<HTTPStatus> { guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(.internalServerError) } guard let reviewerId = Int(reviewerParameter) else { return req.eventLoop.future(.internalServerError) } guard let projectParameter = req.parameters.get("projectID") else { return req.eventLoop.future(.internalServerError) } guard let projectId = Int(projectParameter) else { return req.eventLoop.future(.internalServerError) } return ProjectReviewer.query(on: req.db).all().flatMap { allProjectReviewers in let projectReviewers = allProjectReviewers.filter { $0.$project.id == projectId && $0.$reviewer.id == reviewerId } guard let projectReviewer = projectReviewers.first else { return req.eventLoop.future(.internalServerError) } return projectReviewer.delete(on: req.db).transform(to: .ok) } } func addRepositoryReviewer(req: Request) -> EventLoopFuture<HTTPStatus> { guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(.internalServerError) } guard let reviewerId = Int(reviewerParameter) else { return req.eventLoop.future(.internalServerError) } guard let repositoryParameter = req.parameters.get("repoID") else { return req.eventLoop.future(.internalServerError) } guard let repositoryId = Int(repositoryParameter) else { return req.eventLoop.future(.internalServerError) } return ProjectReviewer.query(on: req.db).all().flatMap { projectReviewers in let removingReviewers = projectReviewers.filter { $0.$reviewer.id == reviewerId } removingReviewers.forEach { $0.delete(on: req.db) } return RepositoryReviewer(repositoryID: repositoryId, reviewerID: reviewerId).save(on: req.db).transform(to: .ok) } } func removeRepositoryReviewer(req: Request) -> EventLoopFuture<HTTPStatus> { guard let reviewerParameter = req.parameters.get("id") else { return req.eventLoop.future(.internalServerError) } guard let reviewerId = Int(reviewerParameter) else { return req.eventLoop.future(.internalServerError) } guard let repositoryParameter = req.parameters.get("repoID") else { return req.eventLoop.future(.internalServerError) } guard let repositoryId = Int(repositoryParameter) else { return req.eventLoop.future(.internalServerError) } return RepositoryReviewer.query(on: req.db).all().flatMap { allRepositoryReviewers in let repositoryReviewers = allRepositoryReviewers.filter { $0.$repository.id == repositoryId && $0.$reviewer.id == reviewerId } guard let repositoryReviewer = repositoryReviewers.first else { return req.eventLoop.future(.internalServerError) } return repositoryReviewer.delete(on: req.db).transform(to: .ok) } } } struct ReviewerPostCreateContext: Content { let slug: String let name: String let email: String } struct ReviewersContext: Content { let reviewers: [Reviewer] } struct ReviewersProjectContext: Content { let reviewer: Reviewer let reviewersProjects: [LicoreProject] let projects: [LicoreProject] } struct ReviewersRepositoryContext: Content { let reviewer: Reviewer let reviewersRepositories: [Repository] let repositories: [Repository] }
51.038298
138
0.627564
76c27118337386ded28d4f66ecd375aa89a75dde
544
import Flutter import UIKit public class SwiftFlutterPluginDrawerPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_plugin_drawer", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterPluginDrawerPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } }
36.266667
109
0.786765
e453be7f46a796f1b22d21ee975b44ce9b0f372b
1,461
// // Copyright 2017 Mobile Jazz SL // // 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 /// Reachability interface public protocol VastraReachability { func isReachable() -> Bool } /// The strategy implements the following approach: /// /// - If internet is NOT available: the strategy considers all objects valid (.Valid) /// - If internet is available: the strategy doesn't decide if the object is valid (.Unknown) public class VastraReachabilityStrategy: VastraStrategy { private let reachability : VastraReachability /// Default initializer /// /// - Parameter reachability: An reachability object public init(_ reachability : VastraReachability) { self.reachability = reachability } public func isObjectValid<T>(_ object: T) -> VastraStrategyResult { if reachability.isReachable() { return .Unknown } else { return .Valid } } }
31.76087
93
0.702943
67f6424c06f7f67ee4171237ba23f5b76165e32e
1,525
// // DFCGWindowInfoHelper.swift // WindowSnap // // Created by raymond on 2021/1/7. // import Foundation import Cocoa public class DFCGWindowInfoHelper : NSObject { public static func getCGWindowInfoList(option: CGWindowListOption, windowId:CGWindowID) -> [[String:Any]]? { let infos = CGWindowListCopyWindowInfo(option , windowId) as? [[ String : Any]] return infos } public static func getCGWindowInfoListInDesktopAndOnlyScreen() -> [[String:Any]]?{ let infos = CGWindowListCopyWindowInfo(CGWindowListOption(rawValue: CGWindowListOption.optionOnScreenOnly.rawValue | CGWindowListOption.excludeDesktopElements.rawValue) , kCGNullWindowID) as? [[ String : Any]] return infos } public static func CGWindowInfoListOnlyScreen() -> [[String:Any]]?{ let infos = CGWindowListCopyWindowInfo(CGWindowListOption(rawValue: CGWindowListOption.optionOnScreenOnly.rawValue ) , kCGNullWindowID) as? [[ String : Any]] return infos } public static func getCGWindowInfo(windowNumber:Int,option: CGWindowListOption) -> [String : Any]? { if let windowsInfos = getCGWindowInfoList(option: option, windowId: kCGNullWindowID){ for dict in windowsInfos { let winNum : Int = dict[kCGWindowNumber as String] as! Int if winNum == windowNumber { return dict } } return nil }else{ return nil } } }
35.465116
217
0.652459
21d8fe58b564a3aa0160a1c65543a26090d1cbaa
1,579
import XCTest @testable import LocStringGen final class FunctionParameterTests: XCTestCase { func test_sourceCodeRepresentation_bothNamesExist_useBoth() { // Given let sut = FunctionParameter(externalName: "at", localName: "index", type: Int.self) // When let sourceCode = sut.sourceCodeRepresentation(alternativeName: "param1") // Then XCTAssertEqual(sourceCode, "at index: Int") } func test_sourceCodeRepresentation_bothNameAreEqual_useOne() { // Given let sut = FunctionParameter(externalName: "index", localName: "index", type: Int.self) // When let sourceCode = sut.sourceCodeRepresentation(alternativeName: "param1") // Then XCTAssertEqual(sourceCode, "index: Int") } func test_sourceCodeRepresentation_externalNameNotExist_useLocalName() { // Given let sut = FunctionParameter(externalName: "", localName: "index", type: Int.self) // When let sourceCode = sut.sourceCodeRepresentation(alternativeName: "param1") // Then XCTAssertEqual(sourceCode, "index: Int") } func test_sourceCodeRepresentation_bothNamesNotExist_useAlternativeName() { // Given let sut = FunctionParameter(externalName: "", localName: "", type: Int.self) // When let sourceCode = sut.sourceCodeRepresentation(alternativeName: "param1") // Then XCTAssertEqual(sourceCode, "param1: Int") } }
32.22449
94
0.632679
4839a9c34c30139e7b305b0e856ec0142c79ea5c
1,100
// // SavedMoviesInteractor.swift // UpcomingMovies // // Created by Bheem Singh on 7/23/20. // Copyright © 2020 Bheem Singh. All rights reserved. // import Foundation import UpcomingMoviesDomain final class FavoritesSavedMoviesInteractor: SavedMoviesInteractorProtocol { private let accountUseCase: AccountUseCaseProtocol init(useCaseProvider: UseCaseProviderProtocol) { self.accountUseCase = useCaseProvider.accountUseCase() } func getSavedMovies(page: Int?, completion: @escaping (Result<[Movie], Error>) -> Void) { accountUseCase.getFavoriteList(page: page, completion: completion) } } final class WatchListSavedMoviesInteractor: SavedMoviesInteractorProtocol { private let accountUseCase: AccountUseCaseProtocol init(useCaseProvider: UseCaseProviderProtocol) { self.accountUseCase = useCaseProvider.accountUseCase() } func getSavedMovies(page: Int?, completion: @escaping (Result<[Movie], Error>) -> Void) { accountUseCase.getWatchList(page: page, completion: completion) } }
28.205128
93
0.720909
ff49ec2006c53886985b3a66715b9f4a467712c1
5,766
// // SwmCoreTests.swift // SwmCoreTests // // Created by Taketo Sano on 2017/05/03. // Copyright © 2017年 Taketo Sano. All rights reserved. // import XCTest import SwmCore @testable import SwmEigen class EigenIntMatrixTests: XCTestCase { typealias R = Int typealias M<n: SizeType, m: SizeType> = EigenMatrix<R, n, m> typealias M2 = M<_2, _2> func testInitByInitializer() { let a = M2 { setEntry in setEntry(0, 1, 2) setEntry(1, 0, 5) } XCTAssertEqual(a.serialize(), [0,2,5,0]) } func testInitByGrid() { let a = M2(grid: [1,2,3,4]) XCTAssertEqual(a.serialize(), [1,2,3,4]) } func testInitByArrayLiteral() { let a: M2 = [1,2,3,4] XCTAssertEqual(a.serialize(), [1,2,3,4]) } func testEquality() { let a: M2 = [1,2,3,4] let b: M2 = [1,2,3,4] XCTAssertEqual(a, b) } func testInequality() { let a: M2 = [1,2,3,4] let b: M2 = [1,3,2,4] XCTAssertNotEqual(a, b) } func testInitWithMissingGrid() { let a: M2 = [1,2,3] XCTAssertEqual(a, [1,2,3,0]) } func testSubscript() { let a: M2 = [1,2,0,4] XCTAssertEqual(a[0, 0], 1) XCTAssertEqual(a[0, 1], 2) XCTAssertEqual(a[1, 0], 0) XCTAssertEqual(a[1, 1], 4) } func testSubscriptSet() { var a: M2 = [1,2,0,4] a[0, 0] = 0 a[0, 1] = 0 a[1, 1] = 2 XCTAssertEqual(a[0, 0], 0) XCTAssertEqual(a[0, 1], 0) XCTAssertEqual(a[1, 0], 0) XCTAssertEqual(a[1, 1], 2) } func testCopyOnMutate() { let a: M2 = [1,2,0,4] var b = a b[0, 0] = 0 XCTAssertEqual(a[0, 0], 1) XCTAssertEqual(b[0, 0], 0) } func testSum() { let a: M2 = [1,2,3,4] let b: M2 = [2,3,4,5] XCTAssertEqual(a + b, [3,5,7,9]) } func testIsZero() { var a: M2 = [0,0,0,0] XCTAssertTrue(a.isZero) a[0, 0] = 1 a[0, 0] = 0 XCTAssertTrue(a.isZero) } func testZero() { let a: M2 = [1,2,3,4] let o = M2.zero XCTAssertEqual(a + o, a) XCTAssertEqual(o + a, a) } func testNeg() { let a: M2 = [1,2,3,4] XCTAssertEqual(-a, [-1,-2,-3,-4]) XCTAssertEqual(a - a, M2.zero) } func testSub() { let a: M2 = [1,2,3,4] let b: M2 = [2,1,7,2] XCTAssertEqual(a - b, [-1,1,-4,2]) } func testMul() { let a: M2 = [1,2,3,4] let b: M2 = [2,3,4,5] XCTAssertEqual(a * b, [10,13,22,29]) } func testMul2() { let a: M2 = [1,1,-1,1] let b: M2 = [1,1,1,-1] XCTAssertEqual(a * b, [2, 0, 0, -2]) } func testScalarMul() { let a: M2 = [1,2,3,4] XCTAssertEqual(2 * a, [2,4,6,8]) XCTAssertEqual(a * 3, [3,6,9,12]) } func testId() { let a: M2 = [1,2,3,4] let e = M2.identity XCTAssertEqual(a * e, a) XCTAssertEqual(e * a, a) } func testInv() { let a: M2 = [1,2,2,3] XCTAssertEqual(a.inverse!, [-3,2,2,-1]) } func testNonInvertible() { let b: M2 = [1, 0, 0, 0] XCTAssertFalse(b.isInvertible) XCTAssertNil(b.inverse) } func testPow() { let a: M2 = [1,2,3,4] XCTAssertEqual(a.pow(0), M2.identity) XCTAssertEqual(a.pow(1), a) XCTAssertEqual(a.pow(2), [7,10,15,22]) XCTAssertEqual(a.pow(3), [37,54,81,118]) } func testTrace() { let a: M2 = [1,2,3,4] XCTAssertEqual(a.trace, 5) } func testDet() { let a: M2 = [1,2,3,4] XCTAssertEqual(a.determinant, -2) } func testDet4() { let a: M<_4, _4> = [3,-1,2,4, 2,1,1,3, -2,0,3,-1, 0,-2,1,3] XCTAssertEqual(a.determinant, 66) } func testTransposed() { let a: M2 = [1,2,3,4] XCTAssertEqual(a.transposed, [1,3,2,4]) } func testSubmatrixRow() { let a: M2 = [1,2,3,4] let a1 = a.submatrix(rowRange: 0 ..< 1).as(M<_1, _2>.self) XCTAssertEqual(a1, [1, 2]) } func testSubmatrixCol() { let a: M2 = [1,2,3,4] let a2 = a.submatrix(colRange: 1 ..< 2).as(M<_2, _1>.self) XCTAssertEqual(a2, [2, 4]) } func testSubmatrixBoth() { let a: M2 = [1,2,3,4] let a3 = a.submatrix(rowRange: 1 ..< 2, colRange: 0 ..< 1).as(M<_1, _1>.self) XCTAssertEqual(a3, [3]) } func testSubmatrixCopyOnWrite() { let a: M2 = [1,2,3,4] var b = a.submatrix(rowRange: 0 ..< 2, colRange: 0 ..< 1) b[0, 0] = 10 XCTAssertEqual(a[0, 0], 1) XCTAssertEqual(b[0, 0], 10) } func testConcat() { let a: M2 = [1,2,3,4] let b: M2 = [5,6,7,8] let c = a.concat(b).as(M<_2, _4>.self) XCTAssertEqual(c, [1,2,5,6,3,4,7,8]) } func testStack() { let a: M2 = [1,2,3,4] let b: M2 = [5,6,7,8] let c = a.stack(b).as(M<_4, _2>.self) XCTAssertEqual(c, [1,2,3,4,5,6,7,8]) } func testStack2() { let a: M2 = [1,2,3,4] let b: M2 = [0,0,0,0] let c = a.stack(b).as(M<_4, _2>.self) XCTAssertEqual(c, [1,2,3,4,0,0,0,0]) } func testPermuteRows() { let a: M2 = [1,2,3,4] let s = Permutation<_2>.transposition(0, 1) let b = a.permuteRows(by: s) XCTAssertEqual(b, [3,4,1,2]) } func testPermuteCols() { let a: M2 = [1,2,3,4] let s = Permutation<_2>.transposition(0, 1) let b = a.permuteCols(by: s) XCTAssertEqual(b, [2,1,4,3]) } }
23.156627
85
0.474679
e004bb8a815e1b2c5b9d6867e5a75dcf9300c2bf
8,881
// // Typestyle.swift // IFTTT SDK // // Copyright © 2019 IFTTT. All rights reserved. // import UIKit extension UIFont { /// The weight options available for the app's custom fonts. enum CustomFontWeight: String { /// A font with the heavy weight. case heavy = "Heavy" /// A font with the bold weight. case bold = "Bold" /// A font with the demi bold weight. case demiBold = "DemiBold" /// A font with the medium weight. case medium = "Medium" } private static func customFontName(withWeight weight: CustomFontWeight) -> String { return "AvenirNext-\(weight.rawValue)" } private static func customFont(withName name: String, size: CGFloat, style: UIFont.TextStyle, isDynamic: Bool) -> UIFont { let font = UIFont(name: name, size: size)! if #available(iOS 11, *), isDynamic { return style.metrics.scaledFont(for: font) } return font } /// Creates the header 1 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h1(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle if #available(iOS 11, *) { style = isCallout == true ? .callout : .largeTitle } else { style = isCallout == true ? .callout : .title1 } return customFont(withName: name, size: 36, style: style, isDynamic: isDynamic) } /// Creates the header 2 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h2(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .title1 return customFont(withName: name, size: 30, style: style, isDynamic: isDynamic) } /// Creates the header 3 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h3(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .title2 return customFont(withName: name, size: 28, style: style, isDynamic: isDynamic) } /// Creates the header 4 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h4(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .title3 return customFont(withName: name, size: 24, style: style, isDynamic: isDynamic) } /// Creates the header 5 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h5(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .headline return customFont(withName: name, size: 20, style: style, isDynamic: isDynamic) } /// Creates the header 6 font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func h6(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .subheadline return customFont(withName: name, size: 18, style: style, isDynamic: isDynamic) } /// Creates the body font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to medium. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func body(weight: CustomFontWeight = .medium, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .body return customFont(withName: name, size: 16, style: style, isDynamic: isDynamic) } /// Creates the standard callout font /// This is equivalent to body with demi bold weight and isCallout == true /// /// - Parameters: /// - weight: The thickness of the font. Defaults to demi bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - Returns: The font configured. static func callout(weight: CustomFontWeight = .demiBold, isDynamic: Bool = true) -> UIFont { return .body(weight: weight, isDynamic: isDynamic, isCallout: true) } /// Creates the footnote font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to medium. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func footnote(weight: CustomFontWeight = .medium, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .footnote return customFont(withName: name, size: 14, style: style, isDynamic: isDynamic) } /// Creates the caption font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to medium. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func caption(weight: CustomFontWeight = .medium, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .caption1 return customFont(withName: name, size: 12, style: style, isDynamic: isDynamic) } /// Creates the small font. /// /// - Parameters: /// - weight: The thickness of the font. Defaults to bold. /// - isDynamic: Whether the font scales based on a user's settings. Defaults to true. /// - isCallout: Whether the font style should be set to `.callout`. Defaults to false. /// - Returns: The font configured. static func small(weight: CustomFontWeight = .bold, isDynamic: Bool = true, isCallout: Bool = false) -> UIFont { let name = customFontName(withWeight: weight) let style: UIFont.TextStyle = isCallout == true ? .callout : .caption2 return customFont(withName: name, size: 10, style: style, isDynamic: isDynamic) } }
44.405
126
0.625042
56902f802148404e401f502fdf4a521458bb88ea
3,954
// // UserAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Alamofire public class UserAPI: APIBase { /** User Activity - parameter offset: (query) Offset the list of returned results by this amount. Default is zero. (optional) - parameter limit: (query) Number of items to retrieve. Default is 5, maximum is 100. (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func historyGet(offset offset: Int32? = nil, limit: Int32? = nil, completion: ((data: Activities?, error: ErrorType?) -> Void)) { historyGetWithRequestBuilder(offset: offset, limit: limit).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** User Activity - GET /history - The User Activity endpoint returns data about a user&#39;s lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.&lt;br&gt;&lt;br&gt;The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary. - examples: [{"contentType":"application/json","example":"{\n \"offset\": \"\",\n \"limit\": \"\",\n \"count\": \"\",\n \"history\": [\n {\n \"uuid\": \"aeiou\"\n }\n ]\n}"}] - parameter offset: (query) Offset the list of returned results by this amount. Default is zero. (optional) - parameter limit: (query) Number of items to retrieve. Default is 5, maximum is 100. (optional) - returns: RequestBuilder<Activities> */ public class func historyGetWithRequestBuilder(offset offset: Int32? = nil, limit: Int32? = nil) -> RequestBuilder<Activities> { let path = "/history" let URLString = SwaggerClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "offset": offset?.encodeToJSON(), "limit": limit?.encodeToJSON() ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Activities>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** User Profile - parameter completion: completion handler to receive the data and the error objects */ public class func meGet(completion: ((data: Profile?, error: ErrorType?) -> Void)) { meGetWithRequestBuilder().execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** User Profile - GET /me - The User Profile endpoint returns information about the Uber user that has authorized with the application. - examples: [{"contentType":"application/json","example":"{\n \"first_name\": \"aeiou\",\n \"last_name\": \"aeiou\",\n \"email\": \"aeiou\",\n \"picture\": \"aeiou\",\n \"promo_code\": \"aeiou\"\n}"}] - returns: RequestBuilder<Profile> */ public class func meGetWithRequestBuilder() -> RequestBuilder<Profile> { let path = "/me" let URLString = SwaggerClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Profile>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } }
44.931818
466
0.673242
18261da775edbdae76b815ba17fb07c5046298db
513
// AreaChartStyle.swift // SwiftUIX // // Copyright © 2021-2022 Alexandre H. Saad // Licensed under the MIT License // import SwiftUI /// A chart style that displays its data with an area. @available(*, unavailable) public struct AreaChartStyle { /// Creates an area chart style public init() {} } // MARK: - ChartStyle @available(*, unavailable) extension AreaChartStyle: ChartStyle { public func makeBody(configuration: Self.Configuration) -> some View { // TODO: chart style return Color.clear } }
19.730769
71
0.719298
46ea7e3b89bc455023969b9170dd8767b5846e81
624
// // ErrorModel.swift // SampleKit // // Created by Jesus Rodriguez on 16.08.19. // Copyright © 2019 com.jesusrod. All rights reserved. // import Foundation public struct ErrorMessage: Error { // MARK: - Properties public let id: UUID public let title: String public let message: String // MARK: - Methods public init(title: String, message: String) { id = UUID() self.title = title self.message = message } } extension ErrorMessage: Equatable { public static func == (lhs: ErrorMessage, rhs: ErrorMessage) -> Bool { return lhs.id == rhs.id } }
19.5
74
0.626603
6292773fde5ba879701f4a90bee844fb53e7a433
1,420
// // tippyUITests.swift // tippyUITests // // Created by Manan Surana on 1/22/20. // Copyright © 2020 codepath. All rights reserved. // import XCTest class tippyUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
32.272727
182
0.650704
648b7ea08c7422af08cf067b2b60926a93917807
4,686
// // DataSource.swift // SwiftBrick // // Created by iOS on 2021/7/16. // Copyright © 2021 狄烨 . All rights reserved. // import Foundation import QuartzCore import DifferenceKit class DataSource<SectionType: Hashable, ItemType: Hashable> { typealias Section = SectionStruct<SectionType, ItemType>.Section ////添加apply方法处理diff逻辑,判断哪些数据需要刷新 private let dispatcher = MainThreadSerialDispatcher() private var currentSnapshot = DataSourceSnapshot<SectionType, ItemType>() ///构建数据源 private var sections: [Section] = [] ///获取section个数------代理方法里用 func numberOfSections() -> Int{ return sections.count } ///获取section中item个数------代理方法里用 func numberOfItems(in section: Int) -> Int{ return sections[section].elements.count } ///根据数字位置获取Section对象 func sectionID(for section: Int) -> SectionType? { let section = sections[section] return section.differenceIdentifier } ///根据IndexPath获取item对象 func itemID(for indexPath: IndexPath) -> ItemType? { guard 0..<sections.endIndex ~= indexPath.section else { return nil } let items = sections[indexPath.section].elements guard 0..<items.endIndex ~= indexPath.item else { return nil } return items[indexPath.item].differenceIdentifier } ///根据item获取其所在IndexPath func indexPath(for itemID: ItemType) -> IndexPath? { let indexPathMap: [ItemType: IndexPath] = sections.enumerated() .reduce(into: [:]) { result, section in for (itemIndex, item) in section.element.elements.enumerated() { result[item.differenceIdentifier] = IndexPath( item: itemIndex, section: section.offset ) } } return indexPathMap[itemID] } ///不安全的方式获取item对象,索引位置不正确可能获取为空 func itemID(for indexPath: IndexPath) -> ItemType { guard let itemID = itemID(for: indexPath) else { fatalError("item\(indexPath) 不存在") } return itemID } ///使用DifferenceKit在子线程进行数据比对 func apply<View: AnyObject>(_ snapshot: DataSourceSnapshot<SectionType, ItemType>, view: View?, animatingDifferences: Bool, performUpdates: @escaping (View, StagedChangeset<[Section]>, @escaping ([Section]) -> Void) -> Void, completion: (() -> Void)?) { dispatcher.dispatch { [weak self] in guard let self = self else { return } self.currentSnapshot = snapshot let newSections = snapshot.structer.sections guard let view = view else { return self.sections = newSections } func performDiffingUpdates() { let changeset = StagedChangeset(source: self.sections, target: newSections) performUpdates(view, changeset) { sections in self.sections = sections } } CATransaction.begin() CATransaction.setCompletionBlock(completion) if animatingDifferences { performDiffingUpdates() } else { CATransaction.setDisableActions(true) performDiffingUpdates() } CATransaction.commit() } } func snapshot() -> DataSourceSnapshot<SectionType, ItemType> { var snapshot = DataSourceSnapshot<SectionType, ItemType>() snapshot.structer.sections = currentSnapshot.structer.sections return snapshot } } final class MainThreadSerialDispatcher { private let executingCount = UnsafeMutablePointer<Int32>.allocate(capacity: 1) init() { executingCount.initialize(to: 0) } deinit { executingCount.deinitialize(count: 1) executingCount.deallocate() } func dispatch(_ action: @escaping () -> Void) { let count = OSAtomicIncrement32(executingCount) if Thread.isMainThread && count == 1 { action() OSAtomicDecrement32(executingCount) } else { DispatchQueue.main.async { [weak self] in guard let self = self else { return } action() OSAtomicDecrement32(self.executingCount) } } } }
30.828947
132
0.559326
915b49f9275976e0c4165810c17cfee7dd005fa9
602
// // SubtitleCellModel.swift // InlinePicker // // Created by Jeff Kereakoglow on 4/18/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import Foundation final class SubtitleCellModel: NSObject, CellModelType { let state = CellModelState.Closed let rowIndex: Int var title: String var subTitle: String var values: [String] { didSet { self.subTitle = self.values.joinWithSeparator(", ") } } init(rowIndex: Int, title: String, subTitle: String) { self.rowIndex = rowIndex self.title = title self.subTitle = subTitle values = [""] } }
20.066667
57
0.672757
090dc38718d88a7720a56858029d3112ed2bce18
660
// // InstagramResponse.swift // SwiftInstagram // // Created by Ander Goig on 16/9/17. // Copyright © 2017 Ander Goig. All rights reserved. // struct InstagramResponse<T: Decodable>: Decodable { // MARK: - Properties let data: T? let meta: Meta let pagination: Pagination? // MARK: - Types struct Meta: Decodable { let code: Int let errorType: String? let errorMessage: String? } struct Pagination: Decodable { let nextUrl: String? let nextMaxId: String? } } /// Dummy struct used for empty Instagram API data responses public struct InstagramEmptyResponse: Decodable { }
20
60
0.643939
50fe80dffb1cbe39c8f76641b97701a595515c38
441
/// Haskell `infixl 9` precedencegroup TryParsecJSONExtractionPrecedence { associativity: left higherThan: BitwiseShiftPrecedence } /// Haskell `infixl 9` precedencegroup TryParsecJSONKeyValuePrecedence { associativity: left higherThan: BitwiseShiftPrecedence } infix operator !! : TryParsecJSONExtractionPrecedence infix operator !? : TryParsecJSONExtractionPrecedence infix operator ~ : TryParsecJSONKeyValuePrecedence
25.941176
53
0.807256
09124e656ba3862d3fe1d4f20d83947d89abb19b
2,029
// // RealmCacheTests.swift // SuperCodableTests // // Created by 卓同学 on 2018/11/5. // Copyright © 2018 kiwi. All rights reserved. // import XCTest import RealmSwift @testable import SuperCodable class RealmCacheTests: XCTestCase { struct TestModel: Codable, RealmStringPersist { var primaryKey: String let name: String } override func setUp() { let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "MyInMemoryRealm")) RealmCache.defaultRealm = realm } private let primaryKey = "test1" func testCacheModel() { let model = TestModel(primaryKey: primaryKey, name: "xxx") XCTAssert(model.save()) if let queryModel = TestModel.loadFromCache(primaryKey: primaryKey) { XCTAssert(queryModel.name == "xxx") } else { XCTFail() } } func testRemoveCacheModelStatic() { let model = TestModel(primaryKey: primaryKey, name: "yyy") XCTAssert(model.save()) XCTAssertNotNil(TestModel.loadFromCache(primaryKey: primaryKey)) TestModel.removeFromCache(primaryKey: primaryKey) XCTAssertNil(TestModel.loadFromCache(primaryKey: primaryKey)) } func testRemoveCacheModel() { let model = TestModel(primaryKey: primaryKey, name: "yyy") XCTAssert(model.save()) XCTAssertNotNil(TestModel.loadFromCache(primaryKey: primaryKey)) model.removeFromCache() XCTAssertNil(TestModel.loadFromCache(primaryKey: primaryKey)) } func testQuerySort() { let model1 = TestModel(primaryKey: "A", name: "111") let model2 = TestModel(primaryKey: "B", name: "222") model1.save(sortPriority: 2) model2.save(sortPriority: 1) var firstModel = TestModel.loadAll()!.first! XCTAssert(firstModel.primaryKey == "A") model2.save(sortPriority: 5) firstModel = TestModel.loadAll()!.first! XCTAssert(firstModel.primaryKey == "B") } }
31.703125
105
0.649581
1e713ecd0183d6b1afeff4b05767a8d1d8c2c635
907
// // Vertex.swift // Triangle // // Created by burt on 2016. 2. 25.. // Copyright © 2016년 BurtK. All rights reserved. // import Foundation import GLKit enum VertexAttributes : GLuint { case position = 0 case color = 1 case texCoord = 2 } struct Vertex { var x : GLfloat = 0.0 var y : GLfloat = 0.0 var z : GLfloat = 0.0 var r : GLfloat = 0.0 var g : GLfloat = 0.0 var b : GLfloat = 0.0 var a : GLfloat = 1.0 var u : GLfloat = 0.0 var v : GLfloat = 0.0 init(_ x : GLfloat, _ y : GLfloat, _ z : GLfloat, _ r : GLfloat = 0.0, _ g : GLfloat = 0.0, _ b : GLfloat = 0.0, _ a : GLfloat = 1.0, _ u : GLfloat = 0.0, _ v : GLfloat = 0.0) { self.x = x self.y = y self.z = z self.r = r self.g = g self.b = b self.a = a self.u = u self.v = v } }
19.717391
181
0.491731
09a0fed308f028b41dadc77902794bffe82c7a2b
2,526
// // ColorAttributedStringBlockBuilder.swift // EvidationMarkdown // Copyright © 2021 Evidation Health Inc. All rights reserved. // import Markdown class ColorAttributedStringBlockBuilder: ContainerAttributedStringBlockBuilder { //MARK: LayoutBuilder override func relatedMarkDownItemType() -> MarkDownItem.Type { return ColorMarkDownItem.self } override open func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<NSMutableAttributedString>, styling: ItemStyling?) -> NSMutableAttributedString { let string = super.build(markDownItem, asPartOfConverter: converter, styling: styling) // Override the color attribute if let item = markDownItem as? ColorMarkDownItem, let colorString = item.color { if let color = (styling as? ColorStyling)?.knownColors[colorString] { let range = NSRange(location: 0, length: string.length) string.addAttribute(.foregroundColor, value: color, range: range) } else if colorString.hasPrefix("#") { let range = NSRange(location: 0, length: string.length) let color = UIColor(hexString: colorString) string.addAttribute(.foregroundColor, value: color, range: range) } } return string } } extension UIColor { convenience init(hexString: String) { let (a, r, g, b) = ColorConverter.convertHex(hexString) self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0) } } struct ColorConverter { static func convertHex(_ hexString: String) -> (UInt64, UInt64, UInt64, UInt64) { var hex = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (hex.hasPrefix("#")) { hex.remove(at: hex.startIndex) } var int = UInt64() Scanner(string: hex).scanHexInt64(&int) let a, r, g, b: UInt64 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } return (a, r, g, b) } }
36.608696
187
0.590657
4612a39c154831439ed99eab0f24faea73a6b24b
726
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing re g{ enum b = c(")) let a{}() }class A { a B<T where g:b(") class d>(_ = c{ import Foundation func f.C{let:T? = [Void{ class A { class d<f<T : { init() var b<T : T if true{ T] { init() class A{ if tocol c(){ struct S <T.c var a struct Q<T where H:T.c() class A : {enum b { class B:P{ end " ( 1 ] var a{ struct c(){ class B<C<d<d<d<T{}struct S< C { func c(_ = F>() struct A< class C<T { struct S< { class B< g<T where T.e: {let v{{} b{{ var b:T.c{ enum b<T{ let c{ var b(_ = 0 B func f<T : T.c{ enum b = e class A : a { if true {}class B:P{ class C{ struct
15.782609
87
0.612948
39f958bf3e2c7902803557bd30b524835d3714f1
3,771
//: [Previous](@previous) import Foundation // added ; instead of empty lines - faster var input = getInput().split(separator: ";").map{ $0.replacingOccurrences(of: " ", with: "\n").split(separator: "\n") } // MARK:- Part 1 let requiredFields : Set<String.SubSequence> = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"] let numberOfValidPassports = input.map{ (record) -> Int in let recordFields = Set(record.map { field in field.split(separator: ":").first! }) let missingFields = requiredFields.subtracting(recordFields) if (missingFields.count == 1) { // cid is optional return missingFields.first! == "cid" ? 1 : 0 } if (missingFields.count > 0) { return 0 // invalid } return 1 // valid }.reduce(0, +) // wrong submissions assert(251 != numberOfValidPassports) assert(210 > numberOfValidPassports) print("The answer is \(numberOfValidPassports)") // MARK:- Part 2 struct Passport { var byr: Int? var isByrValid: Bool { byr != nil && byr! >= 1920 && byr! <= 2002 } var iyr: Int? var isIyrValid: Bool { iyr != nil && iyr! >= 2010 && iyr! <= 2020 } var eyr: Int? var isEyrValid: Bool { eyr != nil && eyr! >= 2020 && eyr! <= 2030 } var hgt: (Int, Unit)? var isHgtValid: Bool { guard let hgt = hgt else { return false } switch hgt.1 { case .cm: return 150 <= hgt.0 && hgt.0 <= 193 case .inches: return 59 <= hgt.0 && hgt.0 <= 76 } } var hcl: String? var isHclValid: Bool { guard let hcl = hcl else { return false } return hcl.count == 7 && hcl.starts(with: "#") && Int(hcl.dropFirst(), radix: 16) != nil } var ecl: EyeColor? var isEclValid: Bool { ecl != nil } var pid: String? var isPidValid: Bool { guard let pid = pid else { return false } return pid.count == 9 && Int(pid) != nil } var cid: String? // not required var isValid: Bool { isByrValid && isIyrValid && isEyrValid && isHgtValid && isHclValid && isEclValid && isPidValid } enum Unit: String { case cm="cm", inches="in" } enum EyeColor: String { case amb = "amb", blu = "blu", brn = "brn", gry = "gry", grn = "grn", hzl = "hzl", oth = "oth" } enum Fields: String { case byr = "byr", iyr = "iyr", eyr = "eyr", hgt = "hgt", hcl = "hcl", ecl = "ecl", pid = "pid", cid = "cid" } init(record: [String.SubSequence]) { for pair in record { let keyVal = pair.split(separator: ":") guard let field = Fields(rawValue: String(keyVal.first ?? "")), let value = keyVal.last, keyVal.count == 2 else { print("Can't find keyValue in the record!") continue } switch field { case .byr: byr = Int(value) case .iyr: iyr = Int(value) case .eyr: eyr = Int(value) case .hgt: guard let height = Int(value.dropLast(2)), let unit = Unit(rawValue: String(value.dropFirst(value.count - 2))) else { continue } hgt = (height, unit) case .hcl: hcl = String(value) case .ecl: ecl = EyeColor(rawValue: String(value)) case .pid: pid = String(value) case .cid: cid = String(value) } } } } let newAnswer = input.map{ Passport(record: $0).isValid ? 1 : 0}.reduce(0, +) print(newAnswer) assert(13 != newAnswer) assert(109 == newAnswer) print("The answer is \(newAnswer)") //: [Next](@next)
28.568182
119
0.524264
71e92b8b1002c595547a21ea48445366d8573548
982
// // WebvilleeFrameworkTests.swift // WebvilleeFrameworkTests // // Created by WV-Mac4 on 08/09/20. // Copyright © 2020 Mac-4. All rights reserved. // import XCTest @testable import WebvilleeFramework class WebvilleeFrameworkTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
28.057143
111
0.677189
616a60e0a5947338bca5d983bbcb4662fb44f7fc
943
print("debug1") import Foundation import LanguageTranslatorV3 struct Input: Codable { let username: String let password: String let url: String? } struct Output: Codable { let translation: String } func main(param: Input, completion: @escaping (Output?, Error?) -> Void) -> Void { let languageTranslator = LanguageTranslator(username: param.username , password: param.password, version: "2018-09-16") let request = TranslateRequest(text: ["Hello"], source: "en", target: "es") let failure = {(error: Error) in print(" calling translate Error") print(error) completion(nil, error) } let _ = languageTranslator.translate( request: request, failure: failure) {translation in print(translation) let result = Output(translation: translation.translations.first?.translationOutput as! String) print(result) completion(result, nil) } }
27.735294
123
0.669141
e2066d25a649023d83f27575335912e17a32aec5
6,900
// // SelectionView.swift // SelectionView // // Created by Dmytro Anokhin on 13/08/2021. // import SwiftUI /// Drag direction, counter clockwise enum Direction: CaseIterable { case top case topLeft case left case bottomLeft case bottom case bottomRight case right case topRight func translateRect(_ rect: CGRect, translation: CGSize) -> CGRect { CGRect(origin: translatePoint(rect.origin, translation: translation), size: translateSize(rect.size, translation: translation)) } func translatePoint(_ point: CGPoint, translation: CGSize) -> CGPoint { var result = point switch self { case .top: result.y += translation.height case .topLeft: result.x += translation.width result.y += translation.height case .left: result.x += translation.width case .bottomLeft: result.x += translation.width case .bottom: break case .bottomRight: break case .right: break case .topRight: result.y += translation.height } return result } func translateSize(_ size: CGSize, translation: CGSize) -> CGSize { var result = size switch self { case .top: result.height -= translation.height case .topLeft: result.width -= translation.width result.height -= translation.height case .left: result.width -= translation.width case .bottomLeft: result.width -= translation.width result.height += translation.height case .bottom: result.height += translation.height case .bottomRight: result.width += translation.width result.height += translation.height case .right: result.width += translation.width case .topRight: result.width += translation.width result.height -= translation.height } return result } } enum DragState { case inactive case pressing case dragging(translation: CGSize, direction: Direction) var translation: CGSize { switch self { case .inactive, .pressing: return .zero case .dragging(let translation, _): return translation } } var direction: Direction? { switch self { case .inactive, .pressing: return nil case .dragging(_, let direction): return direction } } func translateRect(_ rect: CGRect) -> CGRect { switch self { case .inactive, .pressing: return rect case .dragging(let translation, let direction): return direction.translateRect(rect, translation: translation) } } } struct SelectionView: View { @Binding var selectionRect: CGRect var knobRadius: CGFloat = 10.0 var body: some View { let rect = dragState.translateRect(selectionRect) return ZStack(alignment: .topLeading) { Rectangle() .stroke(Color.blue) .frame(width: rect.width, height: rect.height) ForEach(0..<Direction.allCases.count) { index in knobView(direction: Direction.allCases[index], size: rect.size) } } .frame(width: rect.width, height: rect.height) .position(x: rect.midX, y: rect.midY) .animation(.linear(duration: minimumLongPressDuration)) } @GestureState private var dragState = DragState.inactive #if os(macOS) private let minimumLongPressDuration = 0.01 #else private let minimumLongPressDuration = 0.3 #endif private func knobView(direction: Direction, size: CGSize) -> some View { let bounds = CGRect(origin: .zero, size: size) let rect = knobRect(direction: direction, in: bounds) let gesture = LongPressGesture(minimumDuration: minimumLongPressDuration) .sequenced(before: DragGesture()) .updating($dragState) { value, state, transaction in switch value { case .first(true): state = .pressing case .second(true, let drag): state = .dragging(translation: drag?.translation ?? .zero, direction: direction) default: state = .inactive } } .onEnded { value in guard case .second(true, let drag?) = value else { return } selectionRect = direction.translateRect(selectionRect, translation: drag.translation) } return ZStack { Circle() .fill(Color.white) Circle() .stroke(Color.blue) } .frame(width: rect.width, height: rect.height) .position(x: rect.midX, y: rect.midY) .gesture(gesture) } private func knobRect(direction: Direction, in rect: CGRect) -> CGRect { let size = CGSize(width: knobRadius * 2.0, height: knobRadius * 2.0) let origin: CGPoint switch direction { case .top: origin = CGPoint(x: rect.midX - knobRadius, y: rect.minY - knobRadius) case .topLeft: origin = CGPoint(x: rect.minX - knobRadius, y: rect.minY - knobRadius) case .left: origin = CGPoint(x: rect.minX - knobRadius, y: rect.midY - knobRadius) case .bottomLeft: origin = CGPoint(x: rect.minX - knobRadius, y: rect.maxY - knobRadius) case .bottom: origin = CGPoint(x: rect.midX - knobRadius, y: rect.maxY - knobRadius) case .bottomRight: origin = CGPoint(x: rect.maxX - knobRadius, y: rect.maxY - knobRadius) case .right: origin = CGPoint(x: rect.maxX - knobRadius, y: rect.midY - knobRadius) case .topRight: origin = CGPoint(x: rect.maxX - knobRadius, y: rect.minY - knobRadius) } return CGRect(origin: origin, size: size) } } struct SelectionView_Previews: PreviewProvider { static var previews: some View { let rect = CGRect(x: 40.0, y: 40.0, width: 320.0, height: 480.0) return SelectionView(selectionRect: .constant(rect)) } }
28.278689
86
0.535072
0894da775cb3b5c339cb22b8f79adb1b581cb830
34,864
// // 🦠 Corona-Warn-App // import Foundation import OpenCombine import OpenCombineFoundation import OpenCombineDispatch import ExposureNotification import FMDB import UIKit import HealthCertificateToolkit import CertLogic protocol CoronaWarnAppDelegate: AnyObject { var client: HTTPClient { get } var wifiClient: WifiOnlyHTTPClient { get } var downloadedPackagesStore: DownloadedPackagesStore { get } var store: Store { get } var appConfigurationProvider: AppConfigurationProviding { get } var riskProvider: RiskProvider { get } var exposureManager: ExposureManager { get } var taskScheduler: ENATaskScheduler { get } var environmentProvider: EnvironmentProviding { get } var contactDiaryStore: DiaryStoringProviding { get } func requestUpdatedExposureState() } // swiftlint:disable file_length // swiftlint:disable:next type_body_length class AppDelegate: UIResponder, UIApplicationDelegate, CoronaWarnAppDelegate, RequiresAppDependencies, ENAExposureManagerObserver, CoordinatorDelegate, ExposureStateUpdating, ENStateHandlerUpdating { // MARK: - Init override init() { self.environmentProvider = Environments() #if DEBUG if isUITesting { self.store = MockTestStore() self.restServiceCache = KeyValueCacheFake() } else { self.store = SecureStore(subDirectory: "database") self.restServiceCache = SecureKeyValueCache(subDirectory: "RestServiceCache", store: store) } #else self.store = SecureStore(subDirectory: "database") self.restServiceCache = SecureKeyValueCache(subDirectory: "RestServiceCache") #endif if store.appInstallationDate == nil { store.appInstallationDate = InstallationDate.inferredFromDocumentDirectoryCreationDate() Log.debug("App installation date: \(String(describing: store.appInstallationDate))") } self.restServiceProvider = RestServiceProvider(cache: restServiceCache) self.client = HTTPClient(environmentProvider: environmentProvider) self.wifiClient = WifiOnlyHTTPClient(environmentProvider: environmentProvider) self.recycleBin = RecycleBin(store: store) self.downloadedPackagesStore.keyValueStore = self.store super.init() recycleBin.testRestorationHandler = CoronaTestRestorationHandler(service: coronaTestService) recycleBin.certificateRestorationHandler = HealthCertificateRestorationHandler(service: healthCertificateService) // Make the analytics working. Should not be called later than at this moment of app initialization. let testResultCollector = PPAAnalyticsTestResultCollector( store: store ) let submissionCollector = PPAAnalyticsSubmissionCollector( store: store, coronaTestService: coronaTestService ) Analytics.setup( store: store, coronaTestService: coronaTestService, submitter: analyticsSubmitter, testResultCollector: testResultCollector, submissionCollector: submissionCollector ) // Let ELS run for our testers as soon as possible to see any possible errors in startup, too. Only in release builds we wait for the user to start it manually. #if !RELEASE if store.elsLoggingActiveAtStartup { elsService.startLogging() } else { Log.warning("ELS is not set to be active at app startup.") } #endif // Migrate the old pcr test structure from versions older than v2.1 coronaTestService.migrate() } deinit { // We are (intentionally) keeping strong references for delegates. Let's clean them up. self.taskExecutionDelegate = nil } // MARK: - Protocol UIApplicationDelegate var window: UIWindow? func application( _: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { Log.info("Application did finish launching.", log: .appLifecycle) // Save and possibly log current app version number and the timestamp. logCurrentAppVersion() logCurrentCensoringState() #if DEBUG setupOnboardingForTesting() setupDataDonationForTesting() setupInstallationDateForTesting() setupAntigenTestProfileForTesting() setupSelectedRegionsForTesting() #endif if AppDelegate.isAppDisabled() { // Show Disabled UI setupUpdateOSUI() didSetupUI = true // Return false, because if the app is disabled, we cannot handle URL ressources or user activity. // More information: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622921-application return false } // 'appLaunchedFromUserActivityURL' inidcates, if the app was launched through a QR-Code scan, from the System Camera. // Based on that, the routing and UI rendering works differently in the subsequent delegate callbacks. // // We can have different paths of delegate callbacks depending on the app was started with a QR-Code scan or not. // Possible paths after QR-Code was scanned: // App was suspended: didFinishLaunchingWithOptions -> applicationDidBecomeActive -> continue userActivity // App was in background: continue userActivity -> applicationDidBecomeActive // // Either 'continue userActivity' or 'applicationDidBecomeActive' needs to show the UI. // 'appLaunchedFromUserActivityURL' helps to indicate which of the two callbacks needs to show the UI. appLaunchedFromUserActivityURL = appLaunchedFromUserActicityURL(launchOptions) QuickAction.setup() UIDevice.current.isBatteryMonitoringEnabled = true // some delegates taskScheduler.delegate = taskExecutionDelegate UNUserNotificationCenter.current().delegate = notificationManager /// Setup DeadmanNotification after AppLaunch DeadmanNotificationManager().scheduleDeadmanNotificationIfNeeded() consumer.didFailCalculateRisk = { [weak self] error in if self?.store.isOnboarded == true { self?.showError(error) } } riskProvider.observeRisk(consumer) exposureManager.observeExposureNotificationStatus(observer: self) NotificationCenter.default.addObserver(self, selector: #selector(isOnboardedDidChange(_:)), name: .isOnboardedDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(backgroundRefreshStatusDidChange), name: UIApplication.backgroundRefreshStatusDidChangeNotification, object: nil) // Background task registration on iOS 12.5 requires us to activate the ENManager (https://jira-ibs.wbs.net.sap/browse/EXPOSUREAPP-8919) if #available(iOS 13.5, *) { // Do nothing since we can use BGTask in this case. } else if NSClassFromString("ENManager") != nil { // Make sure that ENManager is available. -> iOS 12.5.x if store.isOnboarded, exposureManager.exposureManagerState.status == .unknown { self.exposureManager.activate { error in if let error = error { Log.error("[ENATaskExecutionDelegate] Cannot activate the ENManager.", log: .api, error: error) } } } } return handleQuickActions(with: launchOptions) } func applicationWillEnterForeground(_ application: UIApplication) { logCurrentCensoringState() let detectionMode = DetectionMode.fromBackgroundStatus() riskProvider.riskProvidingConfiguration.detectionMode = detectionMode riskProvider.requestRisk(userInitiated: false) let state = exposureManager.exposureManagerState updateExposureState(state) Analytics.triggerAnalyticsSubmission() appUpdateChecker.checkAppVersionDialog(for: window?.rootViewController) healthCertificateService.updateDCCWalletInfosIfNeeded() } func applicationWillTerminate(_ application: UIApplication) { Log.info("Application will terminate.", log: .appLifecycle) } func applicationDidBecomeActive(_ application: UIApplication) { Log.info("Application did become active.", log: .appLifecycle) // If the UI was not setup before, and the app was NOT started from an user activity, // 'applicationDidBecomeActive' is the last delegate callback and needs to build up the UI. if !didSetupUI && !appLaunchedFromUserActivityURL { setupUI() showUI() appLaunchedFromUserActivityURL = false didSetupUI = true route = nil } hidePrivacyProtectionWindow() UIApplication.shared.applicationIconBadgeNumber = 0 if !AppDelegate.isAppDisabled() { // explicitly disabled as per #EXPOSUREAPP-2214 plausibleDeniabilityService.executeFakeRequestOnAppLaunch(probability: 0.0) } // Cleanup recycle-bin. Remove old entries. recycleBin.cleanup() } func applicationDidEnterBackground(_ application: UIApplication) { showPrivacyProtectionWindow() if #available(iOS 13.0, *) { taskScheduler.scheduleTask() } Log.info("Application did enter background.", log: .appLifecycle) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { Log.info("Application continue user activity.", log: .appLifecycle) // handle QR codes scanned in the camera app if userActivity.activityType == NSUserActivityTypeBrowsingWeb, let incomingURL = userActivity.webpageURL { route = Route(url: incomingURL) } // If the UI was not setup before, and the app was started from an user activity, // 'continue userActivity' is the last delegate callback and needs to build up the UI. if !didSetupUI && appLaunchedFromUserActivityURL { setupUI() showUI() appLaunchedFromUserActivityURL = false didSetupUI = true route = nil } else { guard store.isOnboarded else { postOnboardingRoute = route return false } showHome(route) } return true } // MARK: - Protocol CoronaWarnAppDelegate let client: HTTPClient let wifiClient: WifiOnlyHTTPClient let cachingClient = CachingHTTPClient() let downloadedPackagesStore: DownloadedPackagesStore = DownloadedPackagesSQLLiteStore(fileName: "packages") let taskScheduler: ENATaskScheduler = ENATaskScheduler.shared let contactDiaryStore: DiaryStoringProviding = ContactDiaryStore.make() let eventStore: EventStoringProviding = { #if DEBUG if isUITesting { return MockEventStore() } #endif return EventStore.make() }() let environmentProvider: EnvironmentProviding var store: Store let restServiceCache: KeyValueCaching lazy var coronaTestService: CoronaTestServiceProviding = { return CoronaTestService( client: client, restServiceProvider: restServiceProvider, store: store, eventStore: eventStore, diaryStore: contactDiaryStore, appConfiguration: appConfigurationProvider, healthCertificateService: healthCertificateService, healthCertificateRequestService: healthCertificateRequestService, recycleBin: recycleBin, badgeWrapper: badgeWrapper ) }() lazy var badgeWrapper: HomeBadgeWrapper = { return HomeBadgeWrapper(store) }() lazy var eventCheckoutService: EventCheckoutService = EventCheckoutService( eventStore: eventStore, contactDiaryStore: contactDiaryStore ) lazy var plausibleDeniabilityService: PlausibleDeniabilityService = { PlausibleDeniabilityService( client: self.client, restServiceProvider: self.restServiceProvider, store: self.store, coronaTestService: coronaTestService ) }() lazy var appConfigurationProvider: AppConfigurationProviding = { #if DEBUG if isUITesting { // provide a static app configuration for ui tests to prevent validation errors return CachedAppConfigurationMock(isEventSurveyEnabled: true, isEventSurveyUrlAvailable: true) } #endif // use a custom http client that uses/recognized caching mechanisms let appFetchingClient = CachingHTTPClient(environmentProvider: environmentProvider) let provider = CachedAppConfiguration(client: appFetchingClient, store: store) // used to remove invalidated key packages provider.packageStore = downloadedPackagesStore return provider }() lazy var riskProvider: RiskProvider = { let keyPackageDownload = KeyPackageDownload( downloadedPackagesStore: downloadedPackagesStore, client: client, wifiClient: wifiClient, store: store ) let traceWarningPackageDownload = TraceWarningPackageDownload( client: client, store: store, eventStore: eventStore ) let checkinRiskCalculation = CheckinRiskCalculation( eventStore: eventStore, checkinSplittingService: CheckinSplittingService(), traceWarningMatcher: TraceWarningMatcher(eventStore: eventStore) ) #if !RELEASE return RiskProvider( configuration: .default, store: store, appConfigurationProvider: appConfigurationProvider, exposureManagerState: exposureManager.exposureManagerState, enfRiskCalculation: DebugRiskCalculation(riskCalculation: ENFRiskCalculation(), store: store), checkinRiskCalculation: checkinRiskCalculation, keyPackageDownload: keyPackageDownload, traceWarningPackageDownload: traceWarningPackageDownload, exposureDetectionExecutor: exposureDetectionExecutor, coronaTestService: coronaTestService, downloadedPackagesStore: downloadedPackagesStore ) #else return RiskProvider( configuration: .default, store: store, appConfigurationProvider: appConfigurationProvider, exposureManagerState: exposureManager.exposureManagerState, checkinRiskCalculation: checkinRiskCalculation, keyPackageDownload: keyPackageDownload, traceWarningPackageDownload: traceWarningPackageDownload, exposureDetectionExecutor: exposureDetectionExecutor, coronaTestService: coronaTestService, downloadedPackagesStore: downloadedPackagesStore ) #endif }() private lazy var healthCertificateService: HealthCertificateService = HealthCertificateService( store: store, dccSignatureVerifier: dccSignatureVerificationService, dscListProvider: dscListProvider, appConfiguration: appConfigurationProvider, cclService: cclService, recycleBin: recycleBin ) private lazy var healthCertificateRequestService = HealthCertificateRequestService( store: store, client: client, appConfiguration: appConfigurationProvider, healthCertificateService: healthCertificateService ) private lazy var cclService: CCLServable = { CCLService(restServiceProvider, appConfiguration: appConfigurationProvider) }() private lazy var analyticsSubmitter: PPAnalyticsSubmitting = { return PPAnalyticsSubmitter( store: store, client: client, appConfig: appConfigurationProvider, coronaTestService: coronaTestService, ppacService: ppacService ) }() private lazy var otpService: OTPServiceProviding = OTPService( store: store, client: client, riskProvider: riskProvider ) private lazy var ppacService: PrivacyPreservingAccessControl = PPACService( store: store, deviceCheck: PPACDeviceCheck() ) private lazy var dccSignatureVerificationService: DCCSignatureVerifying = { #if DEBUG if isUITesting { if LaunchArguments.healthCertificate.isCertificateInvalid.boolValue { return DCCSignatureVerifyingStub(error: .HC_DSC_NOT_YET_VALID) } return DCCSignatureVerifyingStub() } #endif return DCCSignatureVerification() }() private lazy var dscListProvider: DSCListProviding = { return DSCListProvider(client: cachingClient, store: store) }() private var vaccinationValueSetsProvider: VaccinationValueSetsProvider { #if DEBUG if isUITesting { return VaccinationValueSetsProvider(client: CachingHTTPClientMock(), store: store) } #endif return VaccinationValueSetsProvider(client: cachingClient, store: store) } private lazy var healthCertificateValidationService: HealthCertificateValidationProviding = { #if DEBUG if isUITesting { var mock = MockHealthCertificateValidationService() if LaunchArguments.healthCertificate.invalidCertificateCheck.boolValue { // Provide data for invalid validation let fakeResult: ValidationResult = .fake(result: .fail) fakeResult.rule?.description = [Description(lang: "de", desc: "Die Impfreihe muss vollständig sein (z.B. 1/1, 2/2)."), Description(lang: "en", desc: "The vaccination schedule must be complete (e.g., 1/1, 2/2).")] mock.validationResult = .success(.validationFailed([fakeResult])) } else { mock.validationResult = .success(.validationPassed([.fake(), .fake(), .fake()])) } return mock } #endif let rulesDownloadService = RulesDownloadService(restServiceProvider: restServiceProvider) return HealthCertificateValidationService( store: store, client: client, vaccinationValueSetsProvider: vaccinationValueSetsProvider, dccSignatureVerifier: dccSignatureVerificationService, dscListProvider: dscListProvider, rulesDownloadService: rulesDownloadService ) }() private lazy var healthCertificateValidationOnboardedCountriesProvider: HealthCertificateValidationOnboardedCountriesProviding = HealthCertificateValidationOnboardedCountriesProvider( restService: restServiceProvider ) /// Reference to the ELS server handling error log recording & submission private lazy var elsService: ErrorLogSubmissionProviding = ErrorLogSubmissionService( client: client, store: store, ppacService: ppacService, otpService: otpService ) private let recycleBin: RecycleBin private let restServiceProvider: RestServiceProviding #if COMMUNITY // Enable third party contributors that do not have the required // entitlements to also use the app lazy var exposureManager: ExposureManager = { return ENAExposureManager(manager: MockENManager()) }() #elseif targetEnvironment(simulator) lazy var exposureManager: ExposureManager = { let keys = [ENTemporaryExposureKey()] return MockExposureManager(exposureNotificationError: nil, diagnosisKeysResult: (keys, nil)) }() #else lazy var exposureManager: ExposureManager = ENAExposureManager() #endif /// A set of required dependencies /// /// Computed instead of lazy 'fixed' var because previous implementation created multiple instances of the `WarnOthersReminder` for themselves. /// Currently we copy this behavior until further checks where made to refactor this. var exposureSubmissionServiceDependencies: ExposureSubmissionServiceDependencies { ExposureSubmissionServiceDependencies( exposureManager: self.exposureManager, appConfigurationProvider: self.appConfigurationProvider, client: self.client, restServiceProvider: self.restServiceProvider, store: self.store, eventStore: self.eventStore, coronaTestService: coronaTestService) } func requestUpdatedExposureState() { let state = exposureManager.exposureManagerState updateExposureState(state) } // MARK: - Delegate properties // swiftlint:disable:next weak_delegate lazy var taskExecutionDelegate: ENATaskExecutionDelegate! = { // will be released in `deinit` TaskExecutionHandler( riskProvider: self.riskProvider, restServiceProvider: restServiceProvider, exposureManager: exposureManager, plausibleDeniabilityService: self.plausibleDeniabilityService, contactDiaryStore: self.contactDiaryStore, eventStore: self.eventStore, eventCheckoutService: self.eventCheckoutService, store: self.store, exposureSubmissionDependencies: self.exposureSubmissionServiceDependencies, healthCertificateService: self.healthCertificateService ) }() lazy var notificationManager: NotificationManager = { let notificationManager = NotificationManager( coronaTestService: coronaTestService, eventCheckoutService: eventCheckoutService, healthCertificateService: healthCertificateService, showHome: { [weak self] in // We don't need the Route parameter in the NotificationManager self?.showHome() }, showTestResultFromNotification: { [weak self] route in Log.debug("Will open test result from notification") guard let self = self else { return } if self.didSetupUI { Log.debug("UI is already setup, will call showHome()") self.showHome(route) } else { Log.debug("new route is set: \(route)") self.route = route } }, showHealthCertificate: { [weak self] route in // We must NOT call self?.showHome(route) here because we do not target the home screen. Only set the route. The rest is done automatically by the startup process of the app. // Works only for notifications tapped when the app is closed. When inside the app, the notification will trigger nothing. Log.debug("new route is set: \(route.routeInformation)") self?.route = route }, showHealthCertifiedPerson: { [weak self] route in guard let self = self else { return } /* The booster notifications can be fired when the app is running (either foreground or background) or when the app is killed in case the app is running then we need to show the Home using the route of the booster notifications in case the app is killed and then reopened then we should just set the route into the health certified person, as the showHome flow will begin anyway at the startup process of the app */ if self.didSetupUI { self.showHome(route) } else { Log.debug("new route is set: \(route.routeInformation)") self.route = route } } ) return notificationManager }() // MARK: - Protocol ENAExposureManagerObserver func exposureManager( _: ENAExposureManager, didChangeState newState: ExposureManagerState ) { let message = """ New status of EN framework: Authorized: \(newState.authorized) enabled: \(newState.enabled) status: \(newState.status) authorizationStatus: \(ENManager.authorizationStatus) """ Log.info(message, log: .api) updateExposureState(newState) } // MARK: - Protocol CoordinatorDelegate /// Resets all stores and notifies the Onboarding and resets all pending notifications func coordinatorUserDidRequestReset(exposureSubmissionService: ExposureSubmissionService) { // Reset key value store. Preserve some values. do { /// Following values are excluded from reset: /// - PPAC API Token /// - App installation date /// /// read values from the current store let ppacEdusApiToken = store.ppacApiTokenEdus let installationDate = store.appInstallationDate let newKey = try KeychainHelper().generateDatabaseKey(persistForKeychainKey: SecureStore.encryptionKeyKeychainKey) store.wipeAll(key: newKey) /// write excluded values back to the 'new' store store.ppacApiTokenEdus = ppacEdusApiToken store.appInstallationDate = installationDate Analytics.collect(.submissionMetadata(.lastAppReset(Date()))) } catch { fatalError("Creating new database key failed") } // Reset packages store downloadedPackagesStore.reset() downloadedPackagesStore.open() // Reset exposureManager exposureManager.reset { self.exposureManager.observeExposureNotificationStatus(observer: self) NotificationCenter.default.post(name: .isOnboardedDidChange, object: nil) } // Remove all pending notifications UNUserNotificationCenter.current().removeAllPendingNotificationRequests() // Reset contact diary contactDiaryStore.reset() // Reset event store eventStore.reset() coronaTestService.updatePublishersFromStore() healthCertificateService.updatePublishersFromStore() } // MARK: - Protocol ExposureStateUpdating func updateExposureState(_ state: ExposureManagerState) { riskProvider.exposureManagerState = state riskProvider.requestRisk(userInitiated: false) coordinator.updateExposureState(state) enStateHandler?.updateExposureState(state) } // MARK: - Protocol ENStateHandlerUpdating func updateEnState(_ state: ENStateHandler.State) { Log.info("AppDelegate got EnState update: \(state)", log: .api) coordinator.updateEnState(state) } // MARK: - Private private var exposureDetection: ExposureDetection? private let consumer = RiskConsumer() private var postOnboardingRoute: Route? private var route: Route? private var didSetupUI = false private var appLaunchedFromUserActivityURL = false private lazy var exposureDetectionExecutor: ExposureDetectionExecutor = { ExposureDetectionExecutor( client: self.client, downloadedPackagesStore: self.downloadedPackagesStore, store: self.store, exposureDetector: self.exposureManager ) }() /// - Parameter launchOptions: Launch options passed on app launch /// - Returns: `true` if `launchOptions` contains user activity of type `NSUserActivityTypeBrowsingWeb`, returns `false` otherwhise. private func appLaunchedFromUserActicityURL(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { guard let activityDictionary = launchOptions?[.userActivityDictionary] as? [AnyHashable: Any] else { return false } for key in activityDictionary.keys { if let userActivity = activityDictionary[key] as? NSUserActivity, userActivity.activityType == NSUserActivityTypeBrowsingWeb, userActivity.webpageURL != nil { return true } } return false } private func showError(_ riskProviderError: RiskProviderError) { guard let rootController = window?.rootViewController else { return } guard let alert = makeErrorAlert( riskProviderError: riskProviderError, rootController: rootController ) else { return } func presentAlert() { rootController.present(alert, animated: true, completion: nil) } if rootController.presentedViewController != nil { rootController.dismiss( animated: true, completion: presentAlert ) } else { presentAlert() } } private func makeErrorAlert(riskProviderError: RiskProviderError, rootController: UIViewController) -> UIAlertController? { switch riskProviderError { case .failedRiskDetection(let didEndPrematurelyReason): switch didEndPrematurelyReason { case let .noExposureWindows(error, date): return makeAlertController( noExposureWindowsError: error, localizedDescription: didEndPrematurelyReason.localizedDescription, date: date, rootController: rootController ) case .wrongDeviceTime: if !self.store.wasDeviceTimeErrorShown { self.store.wasDeviceTimeErrorShown = true return rootController.setupErrorAlert(message: didEndPrematurelyReason.localizedDescription) } else { return nil } default: return nil } case .failedKeyPackageDownload(let downloadError): switch downloadError { case .noDiskSpace: return rootController.setupErrorAlert(message: downloadError.description) default: return nil } default: return nil } } private func makeAlertController(noExposureWindowsError: Error?, localizedDescription: String, date: Date, rootController: UIViewController) -> UIAlertController? { if let enError = noExposureWindowsError as? ENError { switch enError.code { case .dataInaccessible: return nil default: let openFAQ: (() -> Void)? = { guard let url = enError.faqURL else { return nil } return { LinkHelper.open(url: url) } }() return rootController.setupErrorAlert( message: localizedDescription + "\n\(date)", secondaryActionTitle: AppStrings.Common.errorAlertActionMoreInfo, secondaryActionCompletion: openFAQ ) } } else if let exposureDetectionError = noExposureWindowsError as? ExposureDetectionError { switch exposureDetectionError { case .isAlreadyRunning: return nil } } else { return rootController.setupErrorAlert( message: localizedDescription ) } } lazy var coordinator = RootCoordinator( self, coronaTestService: coronaTestService, contactDiaryStore: contactDiaryStore, eventStore: eventStore, eventCheckoutService: eventCheckoutService, otpService: otpService, ppacService: ppacService, cclService: cclService, healthCertificateService: healthCertificateService, healthCertificateRequestService: healthCertificateRequestService, healthCertificateValidationService: healthCertificateValidationService, healthCertificateValidationOnboardedCountriesProvider: healthCertificateValidationOnboardedCountriesProvider, vaccinationValueSetsProvider: vaccinationValueSetsProvider, elsService: elsService, recycleBin: recycleBin, restServiceProvider: restServiceProvider, badgeWrapper: badgeWrapper, cache: restServiceCache ) private lazy var appUpdateChecker = AppUpdateCheckHelper(appConfigurationProvider: self.appConfigurationProvider, store: self.store) private var enStateHandler: ENStateHandler? private let riskConsumer = RiskConsumer() private func setupUI() { setupNavigationBarAppearance() setupAlertViewAppearance() UIImageView.appearance().accessibilityIgnoresInvertColors = true window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = coordinator.viewController window?.makeKeyAndVisible() #if DEBUG // Speed up animations for faster UI-Tests: https://pspdfkit.com/blog/2016/running-ui-tests-with-ludicrous-speed/#update-why-not-just-disable-animations-altogether if isUITesting { window?.layer.speed = 100 } #endif } private func showUI() { coordinator.showLoadingScreen() healthCertificateService.setup( updatingWalletInfos: true, completion: { [weak self] in guard let self = self else { return } DispatchQueue.main.async { if self.store.isOnboarded { self.showHome(self.route) } else { self.postOnboardingRoute = self.route self.showOnboarding() } } } ) } private func setupNavigationBarAppearance() { let appearance = UINavigationBar.appearance() appearance.tintColor = .enaColor(for: .tint) appearance.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.enaColor(for: .textPrimary1) ] appearance.largeTitleTextAttributes = [ NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .largeTitle).scaledFont(size: 28, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.enaColor(for: .textPrimary1) ] } private func setupAlertViewAppearance() { UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = .enaColor(for: .tint) } func showHome(_ route: Route? = nil) { // On iOS 12.5 ENManager is already activated in didFinishLaunching (https://jira-ibs.wbs.net.sap/browse/EXPOSUREAPP-8919) Log.debug("showHome Flow is called with current route: \(String(describing: route?.routeInformation)))") if #available(iOS 13.5, *) { if exposureManager.exposureManagerState.status == .unknown { exposureManager.activate { [weak self] error in if let error = error { Log.error("Cannot activate the ENManager.", log: .api, error: error) } self?.presentHomeVC(route) } } else { presentHomeVC(route) } } else if NSClassFromString("ENManager") != nil { // Make sure that ENManager is available. -> iOS 12.5.x presentHomeVC(route) } } private func presentHomeVC(_ route: Route?) { enStateHandler = ENStateHandler( initialExposureManagerState: exposureManager.exposureManagerState, delegate: self ) guard let enStateHandler = self.enStateHandler else { fatalError("It should not happen.") } coordinator.showHome(enStateHandler: enStateHandler, route: route) } private func showOnboarding() { coordinator.showOnboarding() } @objc private func isOnboardedDidChange(_: NSNotification) { if store.isOnboarded { showHome(postOnboardingRoute) postOnboardingRoute = nil } else { showOnboarding() } } @objc private func backgroundRefreshStatusDidChange() { coordinator.updateDetectionMode(currentDetectionMode) } /// Checks if we should log the current app version. To avoid spam, we have two conditions: We only want to log every 24 hours or if the version number has changed (possibly also downgraded versions for testing cases). We don't need a check for ELS beeing active, because the Log is only persisted with ELS is activated in RELEASE builds. /// Internal for testing purposes. private func logCurrentAppVersion() { let clientMetadata = ClientMetadata() // Check if we have some data. if let version = clientMetadata.cwaVersion, let lastVersion = store.lastLoggedAppVersionNumber, let lastTimestamp = store.lastLoggedAppVersionTimestamp { // If we have some data, check if we should log again. let lastTimestampInHours = Calendar.current.component(.hour, from: lastTimestamp) if version != lastVersion || lastTimestampInHours > 24 { Log.info("Current CWA version number: \(String(describing: clientMetadata.cwaVersion))") store.lastLoggedAppVersionNumber = clientMetadata.cwaVersion store.lastLoggedAppVersionTimestamp = Date() } } // Otherwise, save some fresh data. else { Log.info("Current CWA version number: \(String(describing: clientMetadata.cwaVersion))") store.lastLoggedAppVersionNumber = clientMetadata.cwaVersion store.lastLoggedAppVersionTimestamp = Date() } } private func logCurrentCensoringState() { #if !RELEASE let isCensoring = UserDefaults.standard.bool(forKey: ErrorLogSubmissionService.keyElsLoggingCensoring) Log.info("Current ELS censoring state: \(isCensoring)") #endif } // MARK: Privacy Protection private var privacyProtectionWindow: UIWindow? private func showPrivacyProtectionWindow() { guard store.isOnboarded else { return } let privacyProtectionViewController = PrivacyProtectionViewController() privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds) privacyProtectionWindow?.rootViewController = privacyProtectionViewController privacyProtectionWindow?.windowLevel = .alert + 1 privacyProtectionWindow?.makeKeyAndVisible() privacyProtectionViewController.show() } private func hidePrivacyProtectionWindow() { guard let privacyProtectionViewController = privacyProtectionWindow?.rootViewController as? PrivacyProtectionViewController else { return } privacyProtectionViewController.hide { self.privacyProtectionWindow?.isHidden = true self.privacyProtectionWindow = nil } } /// Is the app able to function with the current iOS version? /// /// Due to the backport of the Exposure Notification Framework to iOS 12.5 the app has a certain range of iOS versions that aren't supported. /// /// - Returns: Returns `true` if the app is in the *disabled* state and requires the user to upgrade the os. private static func isAppDisabled() -> Bool { #if DEBUG if isUITesting && LaunchArguments.infoScreen.showUpdateOS.boolValue == true { return true } #endif if #available(iOS 13.7, *) { return false } else if #available(iOS 13.5, *) { return true } else if NSClassFromString("ENManager") != nil { return false } else { return true } } private func setupUpdateOSUI() { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UpdateOSViewController() window?.makeKeyAndVisible() } } private extension Array where Element == URLQueryItem { func valueFor(queryItem named: String) -> String? { first(where: { $0.name == named })?.value } } private var currentDetectionMode: DetectionMode { DetectionMode.fromBackgroundStatus() }
33.394636
339
0.7683
f82e9b5c1efea025f0d3b1c673eb7c6da2867e86
939
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "test", products: [ .library(name: "App", targets: ["App"]), .executable(name: "Run", targets: ["Run"]) ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")), .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")), .package(url: "https://github.com/vapor-community/postgresql-provider.git", .upToNextMajor(from: "2.1.0")), ], targets: [ .target(name: "App", dependencies: ["Vapor", "FluentProvider", "PostgreSQLProvider"], exclude: [ "Config", "Public", "Resources", ]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App", "Testing"]) ] )
33.535714
115
0.543131
566c5675ce9b8b538eb51210cea8b2586de9bf7d
376
// // BreedCell.swift // CatBreeds // // Created by Joshua Adams on 2/17/18. // Copyright © 2018 Josh Adams. All rights reserved. // import UIKit class BreedCell: UITableViewCell { @IBOutlet var photo: UIImageView! @IBOutlet var name: UILabel! internal func configure(name: String, photo: UIImage) { self.name.text = name self.photo.image = photo } }
18.8
57
0.680851
fb6cf0cb44c3ccbf61a3b3777e6c90febd373dd1
831
import UIKit class AuctionWebViewController: WebViewController { override func viewDidLoad() { super.viewDidLoad() let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) let exitImage = UIImage(named: "toolbar_close") let backwardBarItem = UIBarButtonItem(image: exitImage, style: .plain, target: self, action: #selector(exit)); let allItems = self.toolbarItems! + [flexibleSpace, backwardBarItem] toolbarItems = allItems } func exit() { let passwordVC = PasswordAlertViewController.alertView { [weak self] in _ = self?.navigationController?.popViewController(animated: true) return } self.present(passwordVC, animated: true) {} } }
34.625
127
0.66787
6195662dca52b22c54a8e6facf35c69062dc8433
1,971
// // inputMoodView.swift // moodtracker // // Created by Ishrat Lallmamode on 4/13/22. // import SwiftUI import Foundation struct inputMoodView: View { //refer to the moodStore, in here? or... @StateObject var store: moodStore = moodStore(rating: 0, dateEntered: Date(), userName: "Ishrat") @State var mood = 0 @State var todaysDate = Date.now.formatted(date: .numeric, time: .omitted) var body: some View { ZStack{ Color("#ffe8d6").ignoresSafeArea() ScrollView{ LazyVStack(spacing: 5.0) { Text("How are you feeling today on \(todaysDate)") Picker("How are you feeling?", selection: $mood) { Image(systemName: "1.circle.fill") .tag(1) Image(systemName: "2.circle.fill").tag(2) Image(systemName: "3.circle.fill").tag(3) Image(systemName: "4.circle.fill").tag(4) Image(systemName: "5.circle.fill").tag(5) } .pickerStyle(.segmented) .padding() switch mood{ case 1: one() case 2: two() case 3: middle() case 4: four() case 5: five() default: Text("") } } } } } } struct inputMoodView_Previews: PreviewProvider { static var previews: some View { inputMoodView() } }
27.760563
102
0.382547
87cab66cf843676401b1625bcfae4c5c6e9ce63a
1,888
// // ActivityIndicatorViewController.swift // StateViewControllerExample // // Created by David Ask on 2018-08-16. // Copyright © 2018 Formbound. All rights reserved. // import StateViewController import UIKit class ActivityIndicatorViewController: UIViewController { @IBOutlet private var activityIndicator: UIActivityIndicatorView! @IBOutlet private var activityIndicatorContainer: UIView! override func viewDidLoad() { super.viewDidLoad() activityIndicatorContainer.layer.cornerRadius = 5 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) activityIndicator.startAnimating() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) activityIndicator.stopAnimating() } } extension ActivityIndicatorViewController: StateViewControllerTransitioning { func stateTransitionDuration(isAppearing: Bool) -> TimeInterval { return 0.5 } func stateTransitionWillBegin(isAppearing: Bool) { if isAppearing { view.alpha = 0 activityIndicatorContainer.transform = CGAffineTransform .identity .scaledBy(x: 0.5, y: 0.5) } } func stateTransitionDidEnd(isAppearing: Bool) { view.alpha = 1 activityIndicatorContainer.transform = .identity } func animateAlongsideStateTransition(isAppearing: Bool) { if isAppearing { view.alpha = 1 activityIndicatorContainer.transform = .identity } else { view.alpha = 0 activityIndicatorContainer.transform = CGAffineTransform .identity .scaledBy(x: 1.5, y: 1.5) } } func stateTransitionDelay(isAppearing: Bool) -> TimeInterval { return isAppearing ? 0 : 0.5 } }
26.222222
77
0.659958
72d9ab20755f29f88b149eb3c575fdc2a45e6112
3,614
// // ImageService.swift // RxExample // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif protocol ImageService { func imageFromURL(_ url: URL, reachabilityService: ReachabilityService) -> Observable<DownloadableImage> } class DefaultImageService: ImageService { static let sharedImageService = DefaultImageService() // Singleton let `$`: Dependencies = Dependencies.sharedDependencies // 1st level cache private let _imageCache = NSCache<AnyObject, AnyObject>() // 2nd level cache private let _imageDataCache = NSCache<AnyObject, AnyObject>() let loadingImage = ActivityIndicator() private init() { // cost is approx memory usage _imageDataCache.totalCostLimit = 10 * MB _imageCache.countLimit = 20 } private func decodeImage(_ imageData: Data) -> Observable<Image> { return Observable.just(imageData) .observe(on:`$`.backgroundWorkScheduler) .map { data in guard let image = Image(data: data) else { // some error throw apiError("Decoding image error") } return image.forceLazyImageDecompression() } } private func _imageFromURL(_ url: URL) -> Observable<Image> { return Observable.deferred { let maybeImage = self._imageCache.object(forKey: url as AnyObject) as? Image let decodedImage: Observable<Image> // best case scenario, it's already decoded an in memory if let image = maybeImage { decodedImage = Observable.just(image) } else { let cachedData = self._imageDataCache.object(forKey: url as AnyObject) as? Data // does image data cache contain anything if let cachedData = cachedData { decodedImage = self.decodeImage(cachedData) } else { // fetch from network decodedImage = self.`$`.URLSession.rx.data(request: URLRequest(url: url)) .do(onNext: { data in self._imageDataCache.setObject(data as AnyObject, forKey: url as AnyObject) }) .flatMap(self.decodeImage) .trackActivity(self.loadingImage) } } return decodedImage.do(onNext: { image in self._imageCache.setObject(image, forKey: url as AnyObject) }) } } /** Service that tries to download image from URL. In case there were some problems with network connectivity and image wasn't downloaded, automatic retry will be fired when networks becomes available. After image is successfully downloaded, sequence is completed. */ func imageFromURL(_ url: URL, reachabilityService: ReachabilityService) -> Observable<DownloadableImage> { return _imageFromURL(url) .map { DownloadableImage.content(image: $0) } .retryOnBecomesReachable(DownloadableImage.offlinePlaceholder, reachabilityService: reachabilityService) .startWith(.content(image: Image())) } }
34.75
143
0.574156
0a1ed7de269c70cbe7a3501c395d81242a59d4e7
1,240
// // CanvasUITests.swift // CanvasUITests // // Created by Joey Dafforn on 2/19/18. // Copyright © 2018 Joey Dafforn. All rights reserved. // import XCTest class CanvasUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.513514
182
0.66129
acfeb6b6b1264a2dfd14b9113a35c6e69b6df043
2,172
// // AppDelegate.swift // After // // Created by Tatsuya Tobioka on 2017/11/29. // Copyright © 2017 tnantoka. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.212766
285
0.755525
e0f6cac90ed2dcb57cf027941b2981e63af49078
31,507
//===----------------------------------------------------------------------===// // // 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 Dispatch import _NIODataStructures import NIOCore private struct EmbeddedScheduledTask { let id: UInt64 let task: () -> Void let failFn: (Error) -> () let readyTime: NIODeadline let insertOrder: UInt64 init(id: UInt64, readyTime: NIODeadline, insertOrder: UInt64, task: @escaping () -> Void, _ failFn: @escaping (Error) -> ()) { self.id = id self.readyTime = readyTime self.insertOrder = insertOrder self.task = task self.failFn = failFn } func fail(_ error: Error) { self.failFn(error) } } extension EmbeddedScheduledTask: Comparable { static func < (lhs: EmbeddedScheduledTask, rhs: EmbeddedScheduledTask) -> Bool { if lhs.readyTime == rhs.readyTime { return lhs.insertOrder < rhs.insertOrder } else { return lhs.readyTime < rhs.readyTime } } static func == (lhs: EmbeddedScheduledTask, rhs: EmbeddedScheduledTask) -> Bool { return lhs.id == rhs.id } } /// An `EventLoop` that is embedded in the current running context with no external /// control. /// /// Unlike more complex `EventLoop`s, such as `SelectableEventLoop`, the `EmbeddedEventLoop` /// has no proper eventing mechanism. Instead, reads and writes are fully controlled by the /// entity that instantiates the `EmbeddedEventLoop`. This property makes `EmbeddedEventLoop` /// of limited use for many application purposes, but highly valuable for testing and other /// kinds of mocking. /// /// Time is controllable on an `EmbeddedEventLoop`. It begins at `NIODeadline.uptimeNanoseconds(0)` /// and may be advanced by a fixed amount by using `advanceTime(by:)`, or advanced to a point in /// time with `advanceTime(to:)`. /// /// - warning: Unlike `SelectableEventLoop`, `EmbeddedEventLoop` **is not thread-safe**. This /// is because it is intended to be run in the thread that instantiated it. Users are /// responsible for ensuring they never call into the `EmbeddedEventLoop` in an /// unsynchronized fashion. public final class EmbeddedEventLoop: EventLoop { /// The current "time" for this event loop. This is an amount in nanoseconds. /* private but tests */ internal var _now: NIODeadline = .uptimeNanoseconds(0) private var scheduledTaskCounter: UInt64 = 0 private var scheduledTasks = PriorityQueue<EmbeddedScheduledTask>() /// Keep track of where promises are allocated to ensure we can identify their source if they leak. private var _promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:] // The number of the next task to be created. We track the order so that when we execute tasks // scheduled at the same time, we may do so in the order in which they were submitted for // execution. private var taskNumber: UInt64 = 0 private func nextTaskNumber() -> UInt64 { defer { self.taskNumber += 1 } return self.taskNumber } /// - see: `EventLoop.inEventLoop` public var inEventLoop: Bool { return true } /// Initialize a new `EmbeddedEventLoop`. public init() { } /// - see: `EventLoop.scheduleTask(deadline:_:)` @discardableResult public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> { let promise: EventLoopPromise<T> = makePromise() self.scheduledTaskCounter += 1 let task = EmbeddedScheduledTask(id: self.scheduledTaskCounter, readyTime: deadline, insertOrder: self.nextTaskNumber(), task: { do { promise.succeed(try task()) } catch let err { promise.fail(err) } }, promise.fail) let taskId = task.id let scheduled = Scheduled(promise: promise, cancellationTask: { self.scheduledTasks.removeFirst { $0.id == taskId } }) scheduledTasks.push(task) return scheduled } /// - see: `EventLoop.scheduleTask(in:_:)` @discardableResult public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> { return scheduleTask(deadline: self._now + `in`, task) } /// On an `EmbeddedEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. This means that /// `task` will be run the next time you call `EmbeddedEventLoop.run`. public func execute(_ task: @escaping () -> Void) { self.scheduleTask(deadline: self._now, task) } /// Run all tasks that have previously been submitted to this `EmbeddedEventLoop`, either by calling `execute` or /// events that have been enqueued using `scheduleTask`/`scheduleRepeatedTask`/`scheduleRepeatedAsyncTask` and whose /// deadlines have expired. /// /// - seealso: `EmbeddedEventLoop.advanceTime`. public func run() { // Execute all tasks that are currently enqueued to be executed *now*. self.advanceTime(to: self._now) } /// Runs the event loop and moves "time" forward by the given amount, running any scheduled /// tasks that need to be run. public func advanceTime(by increment: TimeAmount) { self.advanceTime(to: self._now + increment) } /// Runs the event loop and moves "time" forward to the given point in time, running any scheduled /// tasks that need to be run. /// /// - Note: If `deadline` is before the current time, the current time will not be advanced. public func advanceTime(to deadline: NIODeadline) { let newTime = max(deadline, self._now) while let nextTask = self.scheduledTasks.peek() { guard nextTask.readyTime <= newTime else { break } // Now we want to grab all tasks that are ready to execute at the same // time as the first. var tasks = Array<EmbeddedScheduledTask>() while let candidateTask = self.scheduledTasks.peek(), candidateTask.readyTime == nextTask.readyTime { tasks.append(candidateTask) self.scheduledTasks.pop() } // Set the time correctly before we call into user code, then // call in for all tasks. self._now = nextTask.readyTime for task in tasks { task.task() } } // Finally ensure we got the time right. self._now = newTime } internal func drainScheduledTasksByRunningAllCurrentlyScheduledTasks() { var currentlyScheduledTasks = self.scheduledTasks while let nextTask = currentlyScheduledTasks.pop() { self._now = nextTask.readyTime nextTask.task() } // Just fail all the remaining scheduled tasks. Despite having run all the tasks that were // scheduled when we entered the method this may still contain tasks as running the tasks // may have enqueued more tasks. while let task = self.scheduledTasks.pop() { task.fail(EventLoopError.shutdown) } } /// - see: `EventLoop.close` func close() throws { // Nothing to do here } /// - see: `EventLoop.shutdownGracefully` public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { run() queue.sync { callback(nil) } } public func _preconditionSafeToWait(file: StaticString, line: UInt) { // EmbeddedEventLoop always allows a wait, as waiting will essentially always block // wait() return } public func _promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) { precondition(_isDebugAssertConfiguration()) self._promiseCreationStore[futureIdentifier] = (file: file, line: line) } public func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? { precondition(_isDebugAssertConfiguration()) return self._promiseCreationStore.removeValue(forKey: futureIdentifier) } public func _preconditionSafeToSyncShutdown(file: StaticString, line: UInt) { // EmbeddedEventLoop always allows a sync shutdown. return } deinit { precondition(scheduledTasks.isEmpty, "Embedded event loop freed with unexecuted scheduled tasks!") } } @usableFromInline class EmbeddedChannelCore: ChannelCore { var isOpen: Bool = true var isActive: Bool = false var eventLoop: EventLoop var closePromise: EventLoopPromise<Void> var error: Optional<Error> private let pipeline: ChannelPipeline init(pipeline: ChannelPipeline, eventLoop: EventLoop) { closePromise = eventLoop.makePromise() self.pipeline = pipeline self.eventLoop = eventLoop self.error = nil } deinit { assert(!self.isOpen && !self.isActive, "leaked an open EmbeddedChannel, maybe forgot to call channel.finish()?") isOpen = false closePromise.succeed(()) } /// Contains the flushed items that went into the `Channel` (and on a regular channel would have hit the network). @usableFromInline var outboundBuffer: CircularBuffer<NIOAny> = CircularBuffer() /// Contains the unflushed items that went into the `Channel` @usableFromInline var pendingOutboundBuffer: MarkedCircularBuffer<(NIOAny, EventLoopPromise<Void>?)> = MarkedCircularBuffer(initialCapacity: 16) /// Contains the items that travelled the `ChannelPipeline` all the way and hit the tail channel handler. On a /// regular `Channel` these items would be lost. @usableFromInline var inboundBuffer: CircularBuffer<NIOAny> = CircularBuffer() @usableFromInline func localAddress0() throws -> SocketAddress { throw ChannelError.operationUnsupported } @usableFromInline func remoteAddress0() throws -> SocketAddress { throw ChannelError.operationUnsupported } @usableFromInline func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) { guard self.isOpen else { promise?.fail(ChannelError.alreadyClosed) return } isOpen = false isActive = false promise?.succeed(()) // As we called register() in the constructor of EmbeddedChannel we also need to ensure we call unregistered here. self.pipeline.syncOperations.fireChannelInactive() self.pipeline.syncOperations.fireChannelUnregistered() eventLoop.execute { // ensure this is executed in a delayed fashion as the users code may still traverse the pipeline self.removeHandlers(pipeline: self.pipeline) self.closePromise.succeed(()) } } @usableFromInline func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { promise?.succeed(()) } @usableFromInline func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { isActive = true promise?.succeed(()) self.pipeline.syncOperations.fireChannelActive() } @usableFromInline func register0(promise: EventLoopPromise<Void>?) { promise?.succeed(()) self.pipeline.syncOperations.fireChannelRegistered() } @usableFromInline func registerAlreadyConfigured0(promise: EventLoopPromise<Void>?) { isActive = true register0(promise: promise) self.pipeline.syncOperations.fireChannelActive() } @usableFromInline func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.pendingOutboundBuffer.append((data, promise)) } @usableFromInline func flush0() { self.pendingOutboundBuffer.mark() while self.pendingOutboundBuffer.hasMark, let dataAndPromise = self.pendingOutboundBuffer.popFirst() { self.addToBuffer(buffer: &self.outboundBuffer, data: dataAndPromise.0) dataAndPromise.1?.succeed(()) } } @usableFromInline func read0() { // NOOP } public final func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) { promise?.fail(ChannelError.operationUnsupported) } @usableFromInline func channelRead0(_ data: NIOAny) { addToBuffer(buffer: &inboundBuffer, data: data) } public func errorCaught0(error: Error) { if self.error == nil { self.error = error } } private func addToBuffer<T>(buffer: inout CircularBuffer<T>, data: T) { buffer.append(data) } } /// `EmbeddedChannel` is a `Channel` implementation that does neither any /// actual IO nor has a proper eventing mechanism. The prime use-case for /// `EmbeddedChannel` is in unit tests when you want to feed the inbound events /// and check the outbound events manually. /// /// Please remember to call `finish()` when you are no longer using this /// `EmbeddedChannel`. /// /// To feed events through an `EmbeddedChannel`'s `ChannelPipeline` use /// `EmbeddedChannel.writeInbound` which accepts data of any type. It will then /// forward that data through the `ChannelPipeline` and the subsequent /// `ChannelInboundHandler` will receive it through the usual `channelRead` /// event. The user is responsible for making sure the first /// `ChannelInboundHandler` expects data of that type. /// /// `EmbeddedChannel` automatically collects arriving outbound data and makes it /// available one-by-one through `readOutbound`. /// /// - note: `EmbeddedChannel` is currently only compatible with /// `EmbeddedEventLoop`s and cannot be used with `SelectableEventLoop`s from /// for example `MultiThreadedEventLoopGroup`. /// - warning: Unlike other `Channel`s, `EmbeddedChannel` **is not thread-safe**. This /// is because it is intended to be run in the thread that instantiated it. Users are /// responsible for ensuring they never call into an `EmbeddedChannel` in an /// unsynchronized fashion. `EmbeddedEventLoop`s notes also apply as /// `EmbeddedChannel` uses an `EmbeddedEventLoop` as its `EventLoop`. public final class EmbeddedChannel: Channel { /// `LeftOverState` represents any left-over inbound, outbound, and pending outbound events that hit the /// `EmbeddedChannel` and were not consumed when `finish` was called on the `EmbeddedChannel`. /// /// `EmbeddedChannel` is most useful in testing and usually in unit tests, you want to consume all inbound and /// outbound data to verify they are what you expect. Therefore, when you `finish` an `EmbeddedChannel` it will /// return if it's either `.clean` (no left overs) or that it has `.leftOvers`. public enum LeftOverState { /// The `EmbeddedChannel` is clean, ie. no inbound, outbound, or pending outbound data left on `finish`. case clean /// The `EmbeddedChannel` has inbound, outbound, or pending outbound data left on `finish`. case leftOvers(inbound: [NIOAny], outbound: [NIOAny], pendingOutbound: [NIOAny]) /// `true` if the `EmbeddedChannel` was `clean` on `finish`, ie. there is no unconsumed inbound, outbound, or /// pending outbound data left on the `Channel`. public var isClean: Bool { if case .clean = self { return true } else { return false } } /// `true` if the `EmbeddedChannel` if there was unconsumed inbound, outbound, or pending outbound data left /// on the `Channel` when it was `finish`ed. public var hasLeftOvers: Bool { return !self.isClean } } /// `BufferState` represents the state of either the inbound, or the outbound `EmbeddedChannel` buffer. These /// buffers contain data that travelled the `ChannelPipeline` all the way. /// /// If the last `ChannelHandler` explicitly (by calling `fireChannelRead`) or implicitly (by not implementing /// `channelRead`) sends inbound data into the end of the `EmbeddedChannel`, it will be held in the /// `EmbeddedChannel`'s inbound buffer. Similarly for `write` on the outbound side. The state of the respective /// buffer will be returned from `writeInbound`/`writeOutbound` as a `BufferState`. public enum BufferState { /// The buffer is empty. case empty /// The buffer is non-empty. case full([NIOAny]) /// Returns `true` is the buffer was empty. public var isEmpty: Bool { if case .empty = self { return true } else { return false } } /// Returns `true` if the buffer was non-empty. public var isFull: Bool { return !self.isEmpty } } /// `WrongTypeError` is throws if you use `readInbound` or `readOutbound` and request a certain type but the first /// item in the respective buffer is of a different type. public struct WrongTypeError: Error, Equatable { /// The type you expected. public let expected: Any.Type /// The type of the actual first element. public let actual: Any.Type public init(expected: Any.Type, actual: Any.Type) { self.expected = expected self.actual = actual } public static func == (lhs: WrongTypeError, rhs: WrongTypeError) -> Bool { return lhs.expected == rhs.expected && lhs.actual == rhs.actual } } /// Returns `true` if the `EmbeddedChannel` is 'active'. /// /// An active `EmbeddedChannel` can be closed by calling `close` or `finish` on the `EmbeddedChannel`. /// /// - note: An `EmbeddedChannel` starts _inactive_ and can be activated, for example by calling `connect`. public var isActive: Bool { return channelcore.isActive } /// - see: `Channel.closeFuture` public var closeFuture: EventLoopFuture<Void> { return channelcore.closePromise.futureResult } @usableFromInline /*private but usableFromInline */ lazy var channelcore: EmbeddedChannelCore = EmbeddedChannelCore(pipeline: self._pipeline, eventLoop: self.eventLoop) /// - see: `Channel._channelCore` public var _channelCore: ChannelCore { return channelcore } /// - see: `Channel.pipeline` public var pipeline: ChannelPipeline { return _pipeline } /// - see: `Channel.isWritable` public var isWritable: Bool = true /// Synchronously closes the `EmbeddedChannel`. /// /// Errors in the `EmbeddedChannel` can be consumed using `throwIfErrorCaught`. /// /// - parameters: /// - acceptAlreadyClosed: Whether `finish` should throw if the `EmbeddedChannel` has been previously `close`d. /// - returns: The `LeftOverState` of the `EmbeddedChannel`. If all the inbound and outbound events have been /// consumed (using `readInbound` / `readOutbound`) and there are no pending outbound events (unflushed /// writes) this will be `.clean`. If there are any unconsumed inbound, outbound, or pending outbound /// events, the `EmbeddedChannel` will returns those as `.leftOvers(inbound:outbound:pendingOutbound:)`. public func finish(acceptAlreadyClosed: Bool) throws -> LeftOverState { do { try close().wait() } catch let error as ChannelError { guard error == .alreadyClosed && acceptAlreadyClosed else { throw error } } self.embeddedEventLoop.drainScheduledTasksByRunningAllCurrentlyScheduledTasks() self.embeddedEventLoop.run() try throwIfErrorCaught() let c = self.channelcore if c.outboundBuffer.isEmpty && c.inboundBuffer.isEmpty && c.pendingOutboundBuffer.isEmpty { return .clean } else { return .leftOvers(inbound: Array(c.inboundBuffer), outbound: Array(c.outboundBuffer), pendingOutbound: c.pendingOutboundBuffer.map { $0.0 }) } } /// Synchronously closes the `EmbeddedChannel`. /// /// This method will throw if the `Channel` hit any unconsumed errors or if the `close` fails. Errors in the /// `EmbeddedChannel` can be consumed using `throwIfErrorCaught`. /// /// - returns: The `LeftOverState` of the `EmbeddedChannel`. If all the inbound and outbound events have been /// consumed (using `readInbound` / `readOutbound`) and there are no pending outbound events (unflushed /// writes) this will be `.clean`. If there are any unconsumed inbound, outbound, or pending outbound /// events, the `EmbeddedChannel` will returns those as `.leftOvers(inbound:outbound:pendingOutbound:)`. public func finish() throws -> LeftOverState { return try self.finish(acceptAlreadyClosed: false) } private var _pipeline: ChannelPipeline! /// - see: `Channel.allocator` public var allocator: ByteBufferAllocator = ByteBufferAllocator() /// - see: `Channel.eventLoop` public var eventLoop: EventLoop { return self.embeddedEventLoop } /// Returns the `EmbeddedEventLoop` that this `EmbeddedChannel` uses. This will return the same instance as /// `EmbeddedChannel.eventLoop` but as the concrete `EmbeddedEventLoop` rather than as `EventLoop` existential. public var embeddedEventLoop: EmbeddedEventLoop = EmbeddedEventLoop() /// - see: `Channel.localAddress` public var localAddress: SocketAddress? = nil /// - see: `Channel.remoteAddress` public var remoteAddress: SocketAddress? = nil /// `nil` because `EmbeddedChannel`s don't have parents. public let parent: Channel? = nil /// If available, this method reads one element of type `T` out of the `EmbeddedChannel`'s outbound buffer. If the /// first element was of a different type than requested, `EmbeddedChannel.WrongTypeError` will be thrown, if there /// are no elements in the outbound buffer, `nil` will be returned. /// /// Data hits the `EmbeddedChannel`'s outbound buffer when data was written using `write`, then `flush`ed, and /// then travelled the `ChannelPipeline` all the way too the front. For data to hit the outbound buffer, the very /// first `ChannelHandler` must have written and flushed it either explicitly (by calling /// `ChannelHandlerContext.write` and `flush`) or implicitly by not implementing `write`/`flush`. /// /// - note: Outbound events travel the `ChannelPipeline` _back to front_. /// - note: `EmbeddedChannel.writeOutbound` will `write` data through the `ChannelPipeline`, starting with last /// `ChannelHandler`. @inlinable public func readOutbound<T>(as type: T.Type = T.self) throws -> T? { return try _readFromBuffer(buffer: &channelcore.outboundBuffer) } /// If available, this method reads one element of type `T` out of the `EmbeddedChannel`'s inbound buffer. If the /// first element was of a different type than requested, `EmbeddedChannel.WrongTypeError` will be thrown, if there /// are no elements in the outbound buffer, `nil` will be returned. /// /// Data hits the `EmbeddedChannel`'s inbound buffer when data was send through the pipeline using `fireChannelRead` /// and then travelled the `ChannelPipeline` all the way too the back. For data to hit the inbound buffer, the /// last `ChannelHandler` must have send the event either explicitly (by calling /// `ChannelHandlerContext.fireChannelRead`) or implicitly by not implementing `channelRead`. /// /// - note: `EmbeddedChannel.writeInbound` will fire data through the `ChannelPipeline` using `fireChannelRead`. @inlinable public func readInbound<T>(as type: T.Type = T.self) throws -> T? { return try _readFromBuffer(buffer: &channelcore.inboundBuffer) } /// Sends an inbound `channelRead` event followed by a `channelReadComplete` event through the `ChannelPipeline`. /// /// The immediate effect being that the first `ChannelInboundHandler` will get its `channelRead` method called /// with the data you provide. /// /// - parameters: /// - data: The data to fire through the pipeline. /// - returns: The state of the inbound buffer which contains all the events that travelled the `ChannelPipeline` // all the way. @inlinable @discardableResult public func writeInbound<T>(_ data: T) throws -> BufferState { pipeline.fireChannelRead(NIOAny(data)) pipeline.fireChannelReadComplete() try throwIfErrorCaught() return self.channelcore.inboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.inboundBuffer)) } /// Sends an outbound `writeAndFlush` event through the `ChannelPipeline`. /// /// The immediate effect being that the first `ChannelOutboundHandler` will get its `write` method called /// with the data you provide. Note that the first `ChannelOutboundHandler` in the pipeline is the _last_ handler /// because outbound events travel the pipeline from back to front. /// /// - parameters: /// - data: The data to fire through the pipeline. /// - returns: The state of the outbound buffer which contains all the events that travelled the `ChannelPipeline` // all the way. @inlinable @discardableResult public func writeOutbound<T>(_ data: T) throws -> BufferState { try writeAndFlush(NIOAny(data)).wait() return self.channelcore.outboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.outboundBuffer)) } /// This method will throw the error that is stored in the `EmbeddedChannel` if any. /// /// The `EmbeddedChannel` will store an error some error travels the `ChannelPipeline` all the way past its end. public func throwIfErrorCaught() throws { if let error = channelcore.error { channelcore.error = nil throw error } } @inlinable func _readFromBuffer<T>(buffer: inout CircularBuffer<NIOAny>) throws -> T? { if buffer.isEmpty { return nil } let elem = buffer.removeFirst() guard let t = self._channelCore.tryUnwrapData(elem, as: T.self) else { throw WrongTypeError(expected: T.self, actual: type(of: self._channelCore.tryUnwrapData(elem, as: Any.self)!)) } return t } /// Create a new instance. /// /// During creation it will automatically also register itself on the `EmbeddedEventLoop`. /// /// - parameters: /// - handler: The `ChannelHandler` to add to the `ChannelPipeline` before register or `nil` if none should be added. /// - loop: The `EmbeddedEventLoop` to use. public convenience init(handler: ChannelHandler? = nil, loop: EmbeddedEventLoop = EmbeddedEventLoop()) { let handlers = handler.map { [$0] } ?? [] self.init(handlers: handlers, loop: loop) } /// Create a new instance. /// /// During creation it will automatically also register itself on the `EmbeddedEventLoop`. /// /// - parameters: /// - handlers: The `ChannelHandler`s to add to the `ChannelPipeline` before register. /// - loop: The `EmbeddedEventLoop` to use. public init(handlers: [ChannelHandler], loop: EmbeddedEventLoop = EmbeddedEventLoop()) { self.embeddedEventLoop = loop self._pipeline = ChannelPipeline(channel: self) try! self._pipeline.syncOperations.addHandlers(handlers) // This will never throw... try! register().wait() } /// - see: `Channel.setOption` @inlinable public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> EventLoopFuture<Void> { self.setOptionSync(option, value: value) return self.eventLoop.makeSucceededVoidFuture() } @inlinable internal func setOptionSync<Option: ChannelOption>(_ option: Option, value: Option.Value) { // No options supported fatalError("no options supported") } /// - see: `Channel.getOption` @inlinable public func getOption<Option: ChannelOption>(_ option: Option) -> EventLoopFuture<Option.Value> { return self.eventLoop.makeSucceededFuture(self.getOptionSync(option)) } @inlinable internal func getOptionSync<Option: ChannelOption>(_ option: Option) -> Option.Value { if option is ChannelOptions.Types.AutoReadOption { return true as! Option.Value } fatalError("option \(option) not supported") } /// Fires the (outbound) `bind` event through the `ChannelPipeline`. If the event hits the `EmbeddedChannel` which /// happens when it travels the `ChannelPipeline` all the way to the front, this will also set the /// `EmbeddedChannel`'s `localAddress`. /// /// - parameters: /// - address: The address to fake-bind to. /// - promise: The `EventLoopPromise` which will be fulfilled when the fake-bind operation has been done. public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) { promise?.futureResult.whenSuccess { self.localAddress = address } pipeline.bind(to: address, promise: promise) } /// Fires the (outbound) `connect` event through the `ChannelPipeline`. If the event hits the `EmbeddedChannel` /// which happens when it travels the `ChannelPipeline` all the way to the front, this will also set the /// `EmbeddedChannel`'s `remoteAddress`. /// /// - parameters: /// - address: The address to fake-bind to. /// - promise: The `EventLoopPromise` which will be fulfilled when the fake-bind operation has been done. public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) { promise?.futureResult.whenSuccess { self.remoteAddress = address } pipeline.connect(to: address, promise: promise) } } extension EmbeddedChannel { public struct SynchronousOptions: NIOSynchronousChannelOptions { @usableFromInline internal let channel: EmbeddedChannel fileprivate init(channel: EmbeddedChannel) { self.channel = channel } @inlinable public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) throws { self.channel.setOptionSync(option, value: value) } @inlinable public func getOption<Option: ChannelOption>(_ option: Option) throws -> Option.Value { return self.channel.getOptionSync(option) } } public final var syncOptions: NIOSynchronousChannelOptions? { return SynchronousOptions(channel: self) } }
41.239529
154
0.66071
1c68f8bb55e010f9d9718e75446732096fedcd2d
7,307
import Foundation import XCTest @testable import SpotifyWebAPI import RegularExpressions #if canImport(FoundationNetworking) import FoundationNetworking #endif public class SpotifyTestObserver: NSObject, XCTestObservation { public static var isRegisteredAsObserver = false public func testBundleWillStart(_ testBundle: Bundle) { // print("\n\ntestBundleWillStart: \(testBundle)\n\n") } public func testBundleDidFinish(_ testBundle: Bundle) { // print("\n\ntestBundleDidFinish: \(testBundle)\n\n") DistributedLock.releaseAllLocks() if let failingTestsString = self.makeFailingTestsString() { if let logFile = SpotifyAPITestCase.logFile { try? failingTestsString.append(to: logFile) } print(failingTestsString) } } func makeFailingTestsString() -> String? { if SpotifyAPITestCase.failingTests.isEmpty { return nil } #if canImport(ObjectiveC) let tests = SpotifyAPITestCase.failingTests .compactMap { test -> (testCase: String, testMethod: String)? in // each string in `failingTests` has the format // "-[<test-case> <test-method>]" guard let match = try! test.regexMatch(#"-\[(\w+) (\w+)\]"#), match.groups.count >= 2, let testCase = match.groups[0]?.match, let testMethod = match.groups[1]?.match else { return nil } return (testCase: testCase, testMethod: testMethod) } #else let tests = SpotifyAPITestCase.failingTests .compactMap { test -> (testCase: String, testMethod: String)? in // each string in `failingTests` has the format // "<test-case>.<test-method>", so we split the string // on the period let tests = test.split(separator: ".").map(String.init) if tests.count != 2 { return nil } return (testCase: tests[0], testMethod: tests[1]) } #endif let sortedTests = tests.sorted { lhs, rhs in lhs.testCase < rhs.testCase } let failingTestsFilter = sortedTests .map { test in "\(test.testCase)/\(test.testMethod)" } .joined(separator: "|") let reTestCommand = """ to re-run failing tests: swift test --filter "\(failingTestsFilter)" """ var testsListString = "" var currentTestCase: String? = nil for test in sortedTests { if test.testCase != currentTestCase { print("\n\(test.testCase)", to: &testsListString) currentTestCase = test.testCase } print(" - \(test.testMethod)", to: &testsListString) } let finalMessage = """ --------- FAILING TESTS --------- \(testsListString) \(reTestCommand) """ return finalMessage } /// Only executes once per process. func globalSetup() { XCTestObservationCenter.shared.addTestObserver(self) Self.isRegisteredAsObserver = true SpotifyAPILogHandler.bootstrap() } public override init() { super.init() self.globalSetup() } } /// The base class for **all** test cases in this package. Overrides /// `record(_:)` to record issues and`setUp()` to install a test observer. open class SpotifyAPITestCase: XCTestCase { public static var failingTests: [String] = [] /// The file that issues will be logged to during tests. public static let logFile: URL? = { if let folder = SpotifyDecodingError.dataDumpFolder { let dateString = DateFormatter .millisecondsTime.string(from: Date()) return folder.appendingPathComponent( "test log \(dateString).txt", isDirectory: false ) } return nil }() public static func selectNetworkAdaptor() { if Bool.random() { print( "URLSession._defaultNetworkAdaptor = " + "URLSession.__defaultNetworkAdaptor" ) URLSession._defaultNetworkAdaptor = URLSession.__defaultNetworkAdaptor } else { print( "URLSession._defaultNetworkAdaptor = NetworkAdaptorManager" + ".shared.networkAdaptor(request:)" ) URLSession._defaultNetworkAdaptor = NetworkAdaptorManager .shared.networkAdaptor(request:) } } open override class func setUp() { if !SpotifyTestObserver.isRegisteredAsObserver { _ = SpotifyTestObserver() } Self.selectNetworkAdaptor() } #if canImport(ObjectiveC) open override func record(_ issue: XCTIssue) { super.record(issue) let context = issue.sourceCodeContext let symbolNames = context.callStack .compactMap { frame -> String? in guard let name = frame.symbolInfo?.symbolName, !name.starts(with: "@objc") else { return nil } return name } .joined(separator: "\n") let filePath = context.location?.fileURL.path ?? "" let line = (context.location?.lineNumber) .flatMap(String.init) ?? "" let locationString = "\(filePath):\(line)" let testName = self.name let message = """ ------------------------------------------------ \(locationString) \(testName) \(issue.compactDescription) call-stack: \(symbolNames) ------------------------------------------------ """ if let logFile = Self.logFile { try? message.append(to: logFile) } if !Self.failingTests.contains(testName) { Self.failingTests.append(testName) } } #else override open func recordFailure( withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool ) { super.recordFailure( withDescription: description, inFile: filePath, atLine: lineNumber, expected: expected ) let testName = self.name let message = """ ------------------------------------------------ \(filePath):\(lineNumber) \(testName) \(description) ------------------------------------------------ """ if let logFile = Self.logFile { try? message.append(to: logFile) } if !Self.failingTests.contains(testName) { Self.failingTests.append(testName) } } #endif }
28.542969
82
0.514438
f74fa00885542754f3e233b1f35554f08fd5d713
1,587
import Quick import Nimble import Mockingjay @testable import brain class InteractorTests: QuickSpec { struct Response: Decodable { var title: String var message: String } struct InvalidResponse: Decodable { var invalidField: String } override func spec() { super.spec() let responseJSON: [String : Any] = ["title": "title from json", "message": "message from json"] describe("interactor") { describe("#execute") { let url = "www.google.com.br" context("when successful request") { beforeEach { self.stub(http(.get, uri: url), json(responseJSON)) } context("right parser") { it("returns parsed response") { let subject = Interactor<Response>(url: url) var response: Response? subject.execute(onSuccess: { (result) in response = result }, onError: { XCTFail() }) expect(response).toEventuallyNot(beNil(), timeout: 5.5, pollInterval: 0.5) } } context("wrong parser") { it("returns true") { let subject = Interactor<InvalidResponse>(url: url) var onErrorCalled = false subject.execute(onSuccess: { (result) in XCTFail() }, onError: { onErrorCalled = true }) expect(onErrorCalled).toEventually(beTrue(), timeout: 5.5, pollInterval: 0.5) } } } } } } }
24.796875
99
0.52489
f4a3cf8bdd661bd7773d94045f70291d76a2e945
11,048
// // AddressViewController.swift // Walayem // // Created by MAC on 4/24/18. // Copyright © 2018 Inception Innovation. All rights reserved. // import UIKit class AddressViewController: UIViewController, UITextFieldDelegate { // MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var streetTextField: UITextField! @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var extraTextField: UITextField! @IBOutlet weak var saveButton: UIButton! var cityPickerView = UIPickerView() var cities = [String]() var user: User? var address: Address? // MARK: Actions @IBAction func close(_ sender: UIBarButtonItem){ dismiss(animated: true, completion: nil) } @IBAction func saveAddress(_ sender: UIButton) { let name = nameTextField.text ?? "" let street = streetTextField.text ?? "" let city = cityTextField.text ?? "" let extra = extraTextField.text ?? "" if name.isEmpty{ showAlert("Error", "Please enter an address name") }else if street.isEmpty{ showAlert("Error", "Please enter a street address") }else if city.isEmpty{ showAlert("Error", "Please enter your city") }else{ if address == nil{ createAddress(name: name, city: city, street: street, extra: extra) }else{ editAddress(name: name, city: city, street: street, extra: extra) } } } override func viewDidLoad() { super.viewDidLoad() user = User().getUserDefaults() navigationItem.title = "New Address" if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } setViews() setupCityPickerView() getCities() nameTextField.delegate = self streetTextField.delegate = self extraTextField.delegate = self //updateSaveButtonState() if let address = address{ navigationItem.title = address.name navigationItem.leftBarButtonItem = nil nameTextField.text = address.name cityTextField.text = address.city streetTextField.text = address.street extraTextField.text = address.extra } Utils.setupNavigationBar(nav: self.navigationController!) nameTextField.textColor = UIColor.textColor nameTextField.placeHolderColor = UIColor.placeholderColor streetTextField.textColor = UIColor.textColor streetTextField.placeHolderColor = UIColor.placeholderColor cityTextField.textColor = UIColor.textColor cityTextField.placeHolderColor = UIColor.placeholderColor extraTextField.textColor = UIColor.textColor extraTextField.placeHolderColor = UIColor.placeholderColor } override func viewWillLayoutSubviews() { nameTextField.addBottomBorderWithColor(color: UIColor.silver, width: 1) streetTextField.addBottomBorderWithColor(color: UIColor.silver, width: 1) cityTextField.addBottomBorderWithColor(color: UIColor.silver, width: 1) extraTextField.addBottomBorderWithColor(color: UIColor.silver, width: 1) saveButton.roundCorners([.topLeft, .topRight], radius: 20) } // MARK: Private methods private func setViews(){ let nameImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20 + 10, height: 20)) nameImageView.image = UIImage(named: "information") nameImageView.tintColor = UIColor.colorPrimary nameImageView.contentMode = .left nameTextField.leftViewMode = .always nameTextField.leftView = nameImageView let streetImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20 + 10, height: 20)) streetImageView.image = UIImage(named: "locationPin") streetImageView.contentMode = .left streetImageView.tintColor = UIColor.colorPrimary streetTextField.leftViewMode = .always streetTextField.leftView = streetImageView let cityImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20 + 10, height: 20)) cityImageView.image = UIImage(named: "city") cityImageView.contentMode = .left cityTextField.leftViewMode = .always cityTextField.leftView = cityImageView let descriptionImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20 + 10, height: 20)) descriptionImageView.image = UIImage(named: "notes") descriptionImageView.contentMode = .left descriptionImageView.tintColor = UIColor.colorPrimary extraTextField.leftViewMode = .always extraTextField.leftView = descriptionImageView } private func getCities(){ let fields = ["id", "name"] let sort = "name ASC" OdooClient.sharedInstance().searchRead(model: "walayem.city", domain: [], fields: fields, offset: 0, limit: 500, order: sort) { (result, error) in if error != nil{ let errmsg = error?.userInfo[NSLocalizedDescriptionKey] as! String print(errmsg) return } let records = result!["records"] as! [Any] for record in records{ if let record = record as? [String: Any]{ let cityName = record["name"] as! String self.cities.append(cityName) } } self.cityPickerView.reloadAllComponents() } } private func setupCityPickerView(){ let toolbar = UIToolbar() toolbar.sizeToFit() toolbar.tintColor = UIColor.colorPrimary let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(setCity)) toolbar.setItems([done], animated: false) cityPickerView.delegate = self cityPickerView.dataSource = self cityTextField.inputAccessoryView = toolbar cityTextField.inputView = cityPickerView } @objc private func setCity(){ if cities.count > 0{ let city = cities[cityPickerView.selectedRow(inComponent: 0)] cityTextField.text = city } cityTextField.resignFirstResponder() } private func createAddress(name: String, city: String, street: String, extra: String){ let activityIndicator = showActivityIndicator() let params = ["address_name": name, "street": street, "city": city, "street2": extra, "partner_id": user?.partner_id as Any] as [String : Any] RestClient().request(WalayemApi.createAddress, params) { (result, error) in activityIndicator.stopAnimating() if error != nil{ return } let record = result!["result"] as! [String: Any] let id = record["id"] as! Int self.address = Address(id: id, name: name, city: city, street: street, extra: extra) let alert = UIAlertController(title: "", message: "Address successfully created", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in self.performSegue(withIdentifier: "unwindToAddressList", sender: self) })) self.present(alert, animated: true, completion: nil) } } private func editAddress(name: String, city: String, street: String, extra: String){ let activityIndicator = showActivityIndicator() let params = ["address_name": name, "street": street, "city": city, "street2": extra, "partner_id": user?.partner_id as Any, "address_id": address!.id] as [String : Any] RestClient().request(WalayemApi.editAddress, params) { (result, error) in activityIndicator.stopAnimating() if error != nil{ return } self.address?.name = name self.address?.city = city self.address?.street = street self.address?.extra = extra let alert = UIAlertController(title: "", message: "Address successfully updated", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in self.performSegue(withIdentifier: "unwindToAddressList", sender: self) })) self.present(alert, animated: true, completion: nil) } } private func updateSaveButtonState(){ let name = nameTextField.text ?? "" let street = streetTextField.text ?? "" let city = cityTextField.text ?? "" if !name.isEmpty && !street.isEmpty && !city.isEmpty{ saveButton.isEnabled = true }else{ saveButton.isEnabled = false } } private func showAlert(_ title: String, _ msg: String){ let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } private func showActivityIndicator() -> UIActivityIndicatorView{ let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.hidesWhenStopped = true let rightBarButton = UIBarButtonItem(customView: activityIndicator) self.navigationItem.setRightBarButton(rightBarButton, animated: true) activityIndicator.startAnimating() return activityIndicator } // MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension AddressViewController: UIPickerViewDelegate, UIPickerViewDataSource{ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return cities.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return cities[row] } }
37.578231
154
0.61088
e9d69bc9704aa799e08f4b4b73ff18549fb9db2d
2,112
import Vapor import FluentProvider import Foundation import Multipart final class UserController { let photoController: PhotoController init(drop: Droplet) { photoController = PhotoController(drop: drop) } func show(_ request: Request, user: User) throws -> ResponseRepresentable { try updateSessionToken(for: user) return user } func update(_ request: Request, user: User) throws -> ResponseRepresentable { let photo = try updatePhoto(by: request, for: user) try user.update(for: request) if photo != nil { user.photo = photo } try user.save() try updateSessionToken(for: user) return user } func updateSessionToken(for user: User) throws { do { try user.updateSessionToken() } catch { throw Abort.badRequest } } } extension UserController: ResourceRepresentable { func makeResource() -> Resource<User> { return Resource( show: show, update: update ) } } extension UserController: EmptyInitializable { convenience init() throws { try self.init() } } extension UserController { func updatePhoto(by request: Request, for user: User) throws -> String? { guard let userId = user.id?.string else { throw Abort.badRequest } // get photo from formData if let bytes = request.formData?[RequestKeys.photo]?.bytes, let filename = request.formData?[RequestKeys.photo]?.filename { try photoController.savePhoto(for: userId, photoBytes: bytes, filename: filename) return filename } // get photo from body as base64EncodedString if let photoString = request.json?[RequestKeys.photo]?.string { return try photoController.savePhoto(for: userId, photoAsString: photoString) } // get photo by url download if let photoURL = request.json?[RequestKeys.photoURL]?.string { return try photoController.downloadAndSavePhoto(for: userId, with: photoURL) } return nil } } extension UserController { struct RequestKeys { static let photo = "photo" static let photoURL = "photoURL" } }
22.231579
87
0.679924
698e2ded529ef98baa1ee441864c249773a2d0ca
409
import XCTest @testable import Template final class TemplateTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(Template().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
25.5625
87
0.647922
48746072945b63cabff29e2bcbdd4c0263ae0469
1,421
// // WeatherInfo.swift // CustomRows // // Created by Edgar Nzokwe on 7/28/21. // import Foundation struct WeatherInfo: Identifiable { var id = UUID() var image: String var temp: Int var city: String } let weatherData: [WeatherInfo] = [ WeatherInfo(image: "snow", temp: 5, city:"New York"), WeatherInfo(image: "cloud", temp:5, city:"Kansas City"), WeatherInfo(image: "sun.max", temp: 80, city:"San Francisco"), WeatherInfo(image: "snow", temp: 5, city:"Chicago"), WeatherInfo(image: "cloud.rain", temp: 49, city:"Washington DC"), WeatherInfo(image: "cloud.heavyrain", temp: 60, city:"Seattle"), WeatherInfo(image: "sun.min", temp: 75, city:"Baltimore"), WeatherInfo(image: "sun.dust", temp: 65, city:"Austin"), WeatherInfo(image: "sunset", temp: 78, city:"Houston"), WeatherInfo(image: "moon", temp: 80, city:"Boston"), WeatherInfo(image: "moon.circle", temp: 45, city:"denver"), WeatherInfo(image: "cloud.snow", temp: 8, city:"Philadelphia"), WeatherInfo(image: "cloud.hail", temp: 5, city:"Memphis"), WeatherInfo(image: "cloud.sleet", temp:5, city:"Nashville"), WeatherInfo(image: "sun.max", temp: 80, city:"San Francisco"), WeatherInfo(image: "cloud.sun", temp: 5, city:"Atlanta"), WeatherInfo(image: "wind", temp: 88, city:"Las Vegas"), WeatherInfo(image: "cloud.rain", temp: 60, city:"Phoenix"), ]
38.405405
70
0.641098
6a1e7f8045b271eddeb4bdc3a5cdc96c0ff4f8ed
1,324
/// Errors that can be thrown while working with Vapor. public struct DatabaseKitError: Error { #warning("use enum?") /// See `Debuggable`. public static let readableName = "DatabaseKit Error" /// See `Debuggable`. public let identifier: String /// See `Debuggable`. public var reason: String /// See `Debuggable`. public var suggestedFixes: [String] /// See `Debuggable`. public var possibleCauses: [String] /// Creates a new `DatabaseKitError`. init( identifier: String, reason: String, suggestedFixes: [String] = [], possibleCauses: [String] = [], file: String = #file, function: String = #function, line: UInt = #line, column: UInt = #column ) { self.identifier = identifier self.reason = reason self.suggestedFixes = suggestedFixes self.possibleCauses = possibleCauses } } /// For printing un-handleable errors. func ERROR(_ string: @autoclosure () -> String, file: StaticString = #file, line: Int = #line) { print("[DatabaseKit] \(string()) [\(file.description.split(separator: "/").last!):\(line)]") } /// Only includes the supplied closure in non-release builds. internal func debugOnly(_ body: () -> Void) { assert({ body(); return true }()) }
28.782609
96
0.617825
fc75f8b2918da02b39692493df80ccc861e66a6d
1,912
// // Protocols.swift // Pods // // Created by Felix Dumit on 9/14/15. // // import CoreSpotlight @available(iOS 9.0, *) /** * Protocol that enables types to be saved to spotlight search */ public protocol SpotlightConvertable { /// title displayed in search var title: String? {get} /// content description displayed in search var contentDescription: String? {get} /// unique idenfitier var identifier: String {get} //optional var itemType: String {get} var thumbnailImage: UIImage? {get} func configure(searchableItem item: CSSearchableItem) } /** * Protocol that enables automatic handling when app is opened from a spotlight search * Implement this if your type requires code to be executed in the same queue as consumer of call */ public protocol SpotlightRetrievable: SpotlightConvertable { /** Function required for retrieving back the object from a given unique identifier. - parameter identifier: unique idenfitier of type to be fetched - returns: closure that retrieves object. The function will be called in a background thread and the returned closure will then be called in the main thread. This is relevant if your objects are not thread self (e.g. Realm.Object) */ static func retrieveItem(with identifier: String) throws -> (() throws -> Self?) } /** * Protocol that enables automatic handling when app is opened from a spotlight search * Implement this protocol if the retrieval of an item given an id is done in sync and is thread safe. */ public protocol SpotlightSyncRetrievable: SpotlightRetrievable { /** Function required for retrieving back the object from a given unique identifier. - parameter identifier: unique idenfitier of type to be fetched - returns: retrieved item */ static func retrieveItem(with identifier: String) throws -> Self? }
30.83871
120
0.715481
72e69a9d7c56240a61239a4c76a830fdfadea464
2,533
// // Shooter.swift // Touch Bar Space Invaders (macOS) // // Created by Elijah Sawyers on 1/14/21. // import Foundation /// Describes an object that can shoot bullets. protocol Shooter { /// Defines the interval on which it takes the `Shooter` to reload. /// /// For example, if the interval is `1.0`, the shoot method will only add /// a new `bullet` to the `bullets` array if it's been greater than or /// equal to one second. var reloadTime: TimeInterval { get } /// Whether or not the `reloadTime` has passed so that the /// `Shooter` is able to shoot. var hasReloaded: Bool { get } /// When the last bullet was shot. var dateOfLastBullet: Date? { get set } /// How far the bullet moves when calling `updateBulletPositions`. var bulletVelocity: Double { get } /// Stores all bullets that have been shot. var bullets: [Bullet] { get set } /// Adds a new bullet to the bullets array. mutating func shoot(withBarrelAt x: Double, _ y: Double) /// Update each bullet's position by `bulletVelocity`. mutating func updateBulletPositions() /// Removes a bullet from the bullet array. mutating func bulletMadeContact(_ bullet: Bullet) } /// Default implementations for the `Shooter` protocol. extension Shooter { var reloadTime: TimeInterval { 1.0 } var hasReloaded: Bool { if let dateOfLastBullet = dateOfLastBullet { let timePassed = Date().timeIntervalSince(dateOfLastBullet) return timePassed >= reloadTime } return true } mutating func shoot(withBarrelAt x: Double, _ y: Double) { if hasReloaded { bullets.append(Bullet( x: x, y: y )) dateOfLastBullet = Date() } } mutating func updateBulletPositions() { // Remove the first bullet if it's out of gameplay bounds. if let bullet = bullets.first, bullet.y < 0 - Double(BulletSize.height) || bullet.y > Double(GameWindowHeight) + Double(BulletSize.height) { bullets.removeFirst() } // Otherwise, update each bullet's position. bullets.enumerated().forEach { index, _ in bullets[index].move(by: bulletVelocity) } } mutating func bulletMadeContact(_ bullet: Bullet) { bullets.removeAll { currentBullet in currentBullet == bullet } } }
29.453488
77
0.60679
f5aef3dce61ddd5b16807acf17a98c937b74a327
165
// // BaseConfig.swift // TestLib // // Created by Marco Celestino on 30/03/2021. // import Foundation struct BaseConfig: Decodable{ let base_url: String }
12.692308
45
0.684848
de92e74905441abe0d1ca172b210eb8dd919bbc5
606
// // SampleViewModel.swift // SimpleMVVM // // Created by Michel Tabari on 2/12/17. // Copyright © 2017 Michel Tabari. All rights reserved. // import RxSwift struct SampleViewModel { var textFieldContent = Variable<String>("") var isValidObservable: Observable<(Bool, Bool)>! init() { setup() } mutating func setup() { isValidObservable = textFieldContent.asObservable().map { content in let messageShouldShow = content.characters.count >= 3 return (content.characters.count >= 3, messageShouldShow) } } }
23.307692
69
0.622112
26618af0fa3cc972badb4aeeb30d4d918902b3af
2,854
import Foundation import azureSwiftRuntime public protocol WebAppsGetVnetConnection { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var name : String { get set } var vnetName : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (VnetInfoProtocol?, Error?) -> Void) -> Void ; } extension Commands.WebApps { // GetVnetConnection gets a virtual network the app (or deployment slot) is connected to by name. internal class GetVnetConnectionCommand : BaseCommand, WebAppsGetVnetConnection { public var resourceGroupName : String public var name : String public var vnetName : String public var subscriptionId : String public var apiVersion = "2016-08-01" public init(resourceGroupName: String, name: String, vnetName: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.name = name self.vnetName = vnetName self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{name}"] = String(describing: self.name) self.pathParameters["{vnetName}"] = String(describing: self.vnetName) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(VnetInfoData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (VnetInfoProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: VnetInfoData?, error: Error?) in completionHandler(result, error) } } } }
46.032258
167
0.632796
71e153a3ebac8a0a2aa56cd5a9859742dfff00d6
856
// // GenerateProblem.swift // RandomArithmetics // // Created by Yonny Hao on 16/8/6. // Copyright © 2016年 example. All rights reserved. // import Foundation func randomNaturalNum(under: UInt32) -> UInt32{ return arc4random_uniform(under - 1) + 1 } #if os(iOS) || os(OSX) public func nextAddition() -> ArithmeticProblem{ return ArithmeticProblem(leftOperand: randomNaturalNum(20), op: .Add, rightOperand: randomNaturalNum(20)) } #endif #if os(iOS) || os(tvOS) public func nextSubtraction() -> ArithmeticProblem{ return ArithmeticProblem(leftOperand: randomNaturalNum(20), op: .Minus, rightOperand: randomNaturalNum(20)) } #endif #if os(iOS) || os(watchOS) public func nextMultiplication() -> ArithmeticProblem{ return ArithmeticProblem(leftOperand: randomNaturalNum(10), op: .Multiply, rightOperand: randomNaturalNum(10)) } #endif
27.612903
114
0.738318
218ddb97800ec388ecd34898b67f00f9dac909a6
250
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct c<d{class a<a var d{map()a{
27.777778
87
0.74
d659f8ab577f64348333af2413b9c67bde39dad9
7,669
// Copyright (c) 2020 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 MobiusCore import MobiusTest import XCLogParser import XCTest import TSCBasic import TSCUtility @testable import XCMetricsClient final class CacheLogsEffectHandlerTests: XCTestCase { final class MockLogManager: LogManager { var xcodeLogsURL: Set<URL> { return Set(xcodeLogs.map { URL(fileURLWithPath: $0.path.pathString) }) } var cachedLogsURL: Set<URL> { return Set(cachedLogs.map { URL(fileURLWithPath: $0.path.pathString) }) } var newlyCachedLogsURL: Set<URL> { return Set(newlyCachedLogs.map { URL(fileURLWithPath: $0.path.pathString) }) } private let xcodeLogs = Set(arrayLiteral: try! TemporaryFile.newFile(prefix: "log1", suffix: ".xcactivitylog"), try! TemporaryFile.newFile(prefix: "log2", suffix: ".xcactivitylog"), try! TemporaryFile.newFile(prefix: "log3", suffix: ".xcactivitylog"), try! TemporaryFile.newFile(prefix: "log4", suffix: ".xcactivitylog") ) private let cachedLogs = Set(arrayLiteral: try! TemporaryFile.newFile(prefix: "log10", suffix: ".xcactivitylog"), try! TemporaryFile.newFile(prefix: "log20", suffix: ".xcactivitylog"), try! TemporaryFile.newFile(prefix: "log30", suffix: ".xcactivitylog") ) private let newlyCachedLogs = Set(arrayLiteral: try! TemporaryFile.newFile(prefix: "log100", suffix: ".xcactivitylog") ) func retrieveXcodeLogs(in buildDirectory: String, timeout: Int) throws -> (currentLog: URL?, otherLogs: Set<URL>) { return (nil, xcodeLogsURL) } func retrieveCachedLogs() throws -> Set<URL> { return cachedLogsURL } func cacheLogs(_ xcodeLogs: Set<URL>, cachedLogs: Set<URL>, retries: Int) throws -> Set<URL> { return xcodeLogs.subtracting(cachedLogs) } var cachedLogsInLegacyDirectory = Set<URL>() func retrieveCachedLogsInLegacyDirectory() throws -> Set<URL> { return cachedLogsInLegacyDirectory } func evictLogs() throws -> Set<URL> { return [] } func saveFailedRequest(url: URL, data: Data) throws -> URL { fatalError() } func removeUploadedFailedRequest(url: URL) throws { } func tagLogAsUploaded(logURL: URL) throws -> URL { fatalError() } var logsToUploadToReturn = [URL]() func retrieveLogRequestsToUpload() throws -> [URL] { return logsToUploadToReturn } } private var effectHandler: CacheLogsEffectHandler! private var effectCallback: EffectCallback<MetricsUploaderEvent>! private var send: ((MetricsUploaderEvent) -> Void)? private var mockLogManager = MockLogManager() override func setUp() { super.setUp() effectHandler = CacheLogsEffectHandler(logManager: mockLogManager, uploadCurrentLogOnly: false) effectCallback = EffectCallback<MetricsUploaderEvent>( onSend: { event in if let send = self.send { send(event) } }, onEnd: {}) } func testCacheLogsCachesPreviousLogs() { send = { event in if case .logsCached(let currentLog, let previousLogs, _) = event { XCTAssertNil(currentLog) XCTAssertEqual(previousLogs, self.mockLogManager.xcodeLogsURL) } else { XCTFail("Expected .logsCached, got: \(event)") } } _ = effectHandler.handle((currentLog: nil, previousLogs: mockLogManager.xcodeLogsURL, cachedLogs: mockLogManager.cachedLogsURL, projectName: "Project Name"), effectCallback) XCTAssertTrue(effectCallback.ended) } func testCacheLogsNotCachesPreviousLogsIfUploadCurrentLogOnly() { effectHandler = CacheLogsEffectHandler(logManager: mockLogManager, uploadCurrentLogOnly: true) send = { event in if case .logsCached(let currentLog, let previousLogs, _) = event { XCTAssertNil(currentLog) XCTAssertEqual(previousLogs, []) } else { XCTFail("Expected .logsCached, got: \(event)") } } _ = effectHandler.handle((currentLog: nil, previousLogs: mockLogManager.xcodeLogsURL, cachedLogs: mockLogManager.cachedLogsURL, projectName: "Project Name"), effectCallback) XCTAssertTrue(effectCallback.ended) } func testCacheLogsCachesCurrentLog() { let currentLogURL = try! TemporaryFile.newFile(prefix: "log1", suffix: ".xcactivitylog").url var receivedEvent: MetricsUploaderEvent? send = { receivedEvent = $0 } _ = effectHandler.handle((currentLog: currentLogURL, previousLogs: [], cachedLogs: mockLogManager.cachedLogsURL, projectName: "Project Name"), effectCallback) if case .some(.logsCached(let currentLog, let otherLogs, _)) = receivedEvent { XCTAssertEqual(currentLog, currentLogURL) XCTAssertEqual(otherLogs, []) } else { XCTFail("Expected .logsCached") } XCTAssertTrue(effectCallback.ended) } func testCacheLogsReportsNotAlreadyCachedLog() { let alreadyCachedLogURL = try! TemporaryFile.newFile(prefix: "log1", suffix: ".xcactivitylog").url let uploadRequestFileURL = alreadyCachedLogURL .deletingLastPathComponent() .appendingPathComponent(LogManagerImplementation.failedRequestsDirectoryName) .appendingPathComponent(alreadyCachedLogURL.lastPathComponent) let fakeRequest = UploadBuildMetricsRequest() try! FileManager.default.createDirectory( at: uploadRequestFileURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [:] ) try! fakeRequest.serializedData().write(to: uploadRequestFileURL) mockLogManager.logsToUploadToReturn = [uploadRequestFileURL] var receivedEvent: MetricsUploaderEvent? send = { receivedEvent = $0 } _ = effectHandler.handle((currentLog: nil, previousLogs: [], cachedLogs: mockLogManager.cachedLogsURL, projectName: "Project Name"), effectCallback) if case .some(.logsCached(let currentLog, let otherLogs, let uploadRequests)) = receivedEvent { XCTAssertNil(currentLog) XCTAssertEqual(otherLogs, []) XCTAssertEqual(uploadRequests, [MetricsUploadRequest(fileURL: uploadRequestFileURL, request: fakeRequest)]) } else { XCTFail("Expected .logsCached ") } XCTAssertTrue(effectCallback.ended) } }
39.127551
181
0.650411
616d127552cc1a0fd6383cf51c9e30ec52ca33d7
6,775
// // MZShortcutsDataManager.swift // Muzzley-iOS // // Created by Jorge Mendes on 10/02/16. // Copyright © 2016 Muzzley. All rights reserved. // import UIKit let MZShortcutsDataManagerErrorDomain = "MZShortcutsDataManagerErrorDomain"; class MZShortcutsDataManager { var shortcuts: [MZShortcut] = [MZShortcut]() class var sharedInstance : MZShortcutsDataManager { struct Singleton { static let instance = MZShortcutsDataManager() } return Singleton.instance } func getShortcuts(_ completion: @escaping (_ result: [MZShortcut]?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.setupAuthorization(accessToken: MZSession.sharedInstance.authInfo!.accessToken) MZShortcutsWebService.sharedInstance.getShortcutsCurrentUser([KEY_USER: MZSession.sharedInstance.authInfo!.userId]) { (results, error) -> Void in if error == nil { if(results is NSDictionary) { self.shortcuts = [MZShortcut]() for shortcut in results!.value(forKey: MZShortcutsWebService.key_shortcuts) as! NSArray { self.shortcuts.append(MZShortcut(dictionary: shortcut as! NSDictionary)) } completion(self.shortcuts, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } } func setShortcutOrder(_ shortcutIds: [String], completion: @escaping (_ result: Bool?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.setupAuthorization(accessToken: MZSession.sharedInstance.authInfo!.accessToken) MZShortcutsWebService.sharedInstance.setShortcutOrder([KEY_USER: MZSession.sharedInstance.authInfo!.userId, "params": ["order": shortcutIds]], completion: { (result, error) -> Void in if error == nil { completion(true, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } }) } func deleteShortcut(_ shortcutId: String, completion: @escaping (_ result: Bool?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.deleteShortcut([KEY_USER: MZSession.sharedInstance.authInfo!.userId, "shortcut_id": shortcutId], completion: { (result, error) -> Void in if error == nil { completion(result as? Bool, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } }) } func createShortcut(_ shortcutVM: MZWorker, inWatch: Bool, completion: @escaping (_ result: NSDictionary?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.createShortcut([KEY_USER: MZSession.sharedInstance.authInfo!.userId, "params": self.getParametersToCreateUpdate(shortcutVM, inWatch: inWatch)], completion: { (result, error) -> Void in if error == nil { if result is NSDictionary { completion(result as? NSDictionary, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } }) } func editShortcut(_ shortcutId: NSString, shortcutVM: MZWorker, inWatch: Bool, completion: @escaping (_ result: NSDictionary?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.editShortcut([KEY_USER: MZSession.sharedInstance.authInfo!.userId, "shortcut_id": shortcutId, "params": self.getParametersToCreateUpdate(shortcutVM, inWatch: inWatch)], completion: { (result, error) -> Void in if error == nil { if result is NSDictionary { completion(result as? NSDictionary, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } }) } fileprivate func getParametersToCreateUpdate(_ worker:MZWorker, inWatch: Bool) -> [String: AnyObject] { var parameters = [String: AnyObject]() parameters[MZWorkersWebService.key_label] = worker.label as AnyObject parameters[MZShortcutsWebService.key_showInWatch] = NSNumber(value: inWatch as Bool) if !worker.actionDevices.isEmpty { parameters[MZWorkersWebService.key_actions] = self.getWorkerRules(worker.actionDevices) as AnyObject } return parameters } fileprivate func getWorkerRules(_ workerDevices: [MZBaseWorkerDevice]) -> [NSDictionary] { var itemsDict = [NSDictionary]() for workerDevice in workerDevices { for item in workerDevice.items as [MZBaseWorkerItem] { itemsDict.append(item.dictionaryRepresentation) } } return itemsDict } func executeShortcutForCurrentUser(_ shortcutID: String, completion: @escaping (_ result: AnyObject?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.executeShortcut([KEY_USER: MZSession.sharedInstance.authInfo!.userId, MZShortcutsWebService.key_shortcutId: shortcutID], completion: completion) } func getSuggestedShortcuts(_ completion: @escaping (_ result: [MZShortcut]?, _ error : NSError?) -> Void) { MZShortcutsWebService.sharedInstance.getSuggestedShortcutsCurrentUser([KEY_USER: MZSession.sharedInstance.authInfo!.userId]) { (results, error) -> Void in if error == nil { if(results is NSDictionary) { self.shortcuts = [MZShortcut]() for shortcut in results!.object(forKey:[MZShortcutsWebService.key_shortcuts_suggestion]) as! NSArray { self.shortcuts.append(MZShortcut(dictionary: shortcut as! NSDictionary)) } completion(self.shortcuts, nil) } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } else { completion(nil, NSError(domain: MZShortcutsDataManagerErrorDomain, code: 0, userInfo: nil)) } } } }
46.724138
254
0.637638
1e8198048f0bcd7c5d8f9211d0374cacd40a83c7
16,331
// // BIP32Keystore.swift // web3swift // // Created by Alexander Vlasov on 11.01.2018. // Copyright © 2018 Bankex Foundation. All rights reserved. // import Foundation private extension Dictionary where Value: Equatable { func key(of value: Value) -> Key? { for (key,_value) in self where _value == value { return key } return nil } } /** BIP32 Keystore (HDWallet) */ public class BIP32Keystore: AbstractKeystore { /// Returns array of contained addresses public var addresses: [Address] { guard !paths.isEmpty else { return [] } var allAccounts = [Address]() for (_, address) in paths { allAccounts.append(address) } return allAccounts } /// Returns true public var isHDKeystore: Bool = true /// Searches for the account's encrypted private key and decrypts it using password. /// /// - Parameter password: Password that used to decrypt your key. /// - Parameter account: Account that you need /// - Returns: private key for given address public func UNSAFE_getPrivateKeyData(password: String, account: Address) throws -> Data { guard let key = self.paths.key(of: account) else { throw AbstractKeystoreError.invalidAccountError } guard let decryptedRootNode = try? self.getPrefixNodeData(password), decryptedRootNode != nil else { throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") } guard let rootNode = HDNode(decryptedRootNode!) else { throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") } guard rootNode.depth == (rootPrefix.components(separatedBy: "/").count - 1) else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } // guard rootNode.depth == HDNode.defaultPathPrefix.components(separatedBy: "/").count - 1 else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } guard let index = UInt32(key.components(separatedBy: "/").last!) else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } let keyNode = try rootNode.derive(index: index, derivePrivateKey: true) guard let privateKey = keyNode.privateKey else { throw AbstractKeystoreError.invalidAccountError } return privateKey } // -------------- /// Json representation of the HDWallet public var keystoreParams: KeystoreParamsBIP32? // public var mnemonics: String? /// Paths dictionary in format "HDPath: Address" public var paths: [String: Address] = [String: Address]() /// HDPath prefix. default: "m/44'/60'/0'/0" (Metamask prefix) public var rootPrefix: String /// Init with json file public convenience init?(_ jsonString: String) { self.init(jsonString.lowercased().data) } /// Init with json file public init?(_ jsonData: Data) { guard var keystoreParams = try? JSONDecoder().decode(KeystoreParamsBIP32.self, from: jsonData) else { return nil } if keystoreParams.version != 3 { return nil } if keystoreParams.crypto.version != nil && keystoreParams.crypto.version != "1" { return nil } if !keystoreParams.isHDWallet { return nil } for (p, ad) in keystoreParams.pathToAddress { paths[p] = Address(ad) } if keystoreParams.rootPath == nil { keystoreParams.rootPath = HDNode.defaultPathPrefix } self.keystoreParams = keystoreParams rootPrefix = keystoreParams.rootPath! } /// Init with mnemonics /// - Parameter mnemonics: Mnemonics that needs to generate your account /// - Parameter password: Password used to encrypt your private key /// - Parameter prefixPath: HDNode path. default: "m/44'/60'/0'/0" (Metamask prefix) /// Shouldn't throw if you generate your mnemonics public convenience init(mnemonics: Mnemonics, password: String = "BANKEXFOUNDATION", prefixPath: String = HDNode.defaultPathMetamaskPrefix) throws { var seed = mnemonics.seed() defer { Data.zero(&seed) } try self.init(seed: seed, password: password, prefixPath: prefixPath) } /// Init with seed /// - Parameter seed: Seed that need to generate your account /// - Parameter password: Password used to encrypt your private key /// - Parameter prefixPath: HDNode path. default: "m/44'/60'/0'/0" (Metamask prefix) public init(seed: Data, password: String = "BANKEXFOUNDATION", prefixPath: String = HDNode.defaultPathMetamaskPrefix) throws { let prefixNode = try HDNode(seed: seed).derive(path: prefixPath, derivePrivateKey: true) rootPrefix = prefixPath try createNewAccount(parentNode: prefixNode, password: password) } /** Creates new sub account using the same seed (mnemonics) So for HDPath "m/44'/60'/0'/0". Will generate sub account "m/44'/60'/0'/1". Also automatically searches in current paths. So it wouldn't skip any index or create an existing account. */ public func createNewChildAccount(password: String = "BANKEXFOUNDATION") throws { guard let decryptedRootNode = try? self.getPrefixNodeData(password), decryptedRootNode != nil else { throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") } guard let rootNode = HDNode(decryptedRootNode!) else { throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") } let prefixPath = rootPrefix guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } try createNewAccount(parentNode: rootNode, password: password) } /// Creates new account using custom HDNode public func createNewAccount(parentNode: HDNode, password: String = "BANKEXFOUNDATION", aesMode: String = "aes-128-cbc") throws { var newIndex = UInt32(0) for (p, _) in paths { guard let idx = UInt32(p.components(separatedBy: "/").last!) else { continue } if idx >= newIndex { newIndex = idx + 1 } } let newNode = try parentNode.derive(index: newIndex, derivePrivateKey: true, hardened: false) let newAddress = try Web3Utils.publicToAddress(newNode.publicKey) let prefixPath = rootPrefix var newPath: String if newNode.isHardened { newPath = prefixPath + "/" + String(newNode.index % HDNode.hardenedIndexPrefix) + "'" } else { newPath = prefixPath + "/" + String(newNode.index) } paths["usdp" + newPath] = newAddress guard let serializedRootNode = parentNode.serialize(serializePublic: false) else { throw AbstractKeystoreError.keyDerivationError } try encryptDataToStorage(password, data: serializedRootNode, aesMode: aesMode) } /// Creates sub account using custom HDNode public func createNewCustomChildAccount(password: String = "BANKEXFOUNDATION", path: String) throws { guard let decryptedRootNode = try? self.getPrefixNodeData(password), decryptedRootNode != nil else { throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") } guard let rootNode = HDNode(decryptedRootNode!) else { throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") } let prefixPath = rootPrefix var pathAppendix: String? if path.hasPrefix(prefixPath) { pathAppendix = String(path[path.index(after: (path.range(of: prefixPath)?.upperBound)!)]) guard pathAppendix != nil else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } if pathAppendix!.hasPrefix("/") { pathAppendix = pathAppendix?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } } else { if path.hasPrefix("/") { pathAppendix = path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } } guard pathAppendix != nil else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else { throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") } let newNode = try rootNode.derive(path: pathAppendix!, derivePrivateKey: true) let newAddress = try Web3Utils.publicToAddress(newNode.publicKey) var newPath: String if newNode.isHardened { newPath = prefixPath + "/" + pathAppendix!.trimmingCharacters(in: CharacterSet(charactersIn: "'")) + "'" } else { newPath = prefixPath + "/" + pathAppendix! } paths[newPath] = newAddress guard let serializedRootNode = rootNode.serialize(serializePublic: false) else { throw AbstractKeystoreError.keyDerivationError } try encryptDataToStorage(password, data: serializedRootNode, aesMode: keystoreParams!.crypto.cipher) } fileprivate func encryptDataToStorage(_ password: String, data: Data?, dkLen: Int = 32, N: Int = 4096, R: Int = 6, P: Int = 1, aesMode: String = "aes-128-cbc") throws { if data == nil { throw AbstractKeystoreError.encryptionError("Encryption without key data") } if data?.count != 82 { throw AbstractKeystoreError.encryptionError("Invalid expected data length") } let saltLen = 32 let saltData = Data.random(length: saltLen) guard let derivedKey = scrypt(password: password, salt: saltData, length: dkLen, N: N, R: R, P: P) else { throw AbstractKeystoreError.keyDerivationError } let last16bytes = derivedKey[(derivedKey.count - 16) ... (derivedKey.count - 1)] let encryptionKey = derivedKey[0 ... 15] let IV = Data.random(length: 16) var aesCipher: AES? switch aesMode { case "aes-128-cbc": aesCipher = AES(key: encryptionKey.bytesWeb, blockMode: CBC(iv: IV.bytesWeb), padding: .pkcs7) case "aes-128-ctr": aesCipher = AES(key: encryptionKey.bytesWeb, blockMode: CTR(iv: IV.bytesWeb), padding: .pkcs7) default: aesCipher = nil } if aesCipher == nil { throw AbstractKeystoreError.aesError } guard let encryptedKey = try aesCipher?.encrypt(data!.bytesWeb) else { throw AbstractKeystoreError.aesError } let encryptedKeyData = Data(bytes: encryptedKey) var dataForMAC = Data() dataForMAC.append(last16bytes) dataForMAC.append(encryptedKeyData) let mac = dataForMAC.keccak256() let kdfparams = KdfParamsV3(salt: saltData.hex, dklen: dkLen, n: N, p: P, r: R, c: nil, prf: nil) let cipherparams = CipherParamsV3(iv: IV.hex) let crypto = CryptoParamsV3(ciphertext: encryptedKeyData.hex, cipher: aesMode, cipherparams: cipherparams, kdf: "scrypt", kdfparams: kdfparams, mac: mac.hex, version: nil) var pathToAddress = [String: String]() for (path, address) in paths { pathToAddress[path] = address.address } var keystorePars = KeystoreParamsBIP32(crypto: crypto, id: UUID().uuidString.lowercased(), version: 3) keystorePars.pathToAddress = pathToAddress keystorePars.rootPath = rootPrefix keystoreParams = keystorePars } /// Update password for your private key public func regenerate(oldPassword: String, newPassword: String, dkLen _: Int = 32, N _: Int = 4096, R _: Int = 6, P _: Int = 1) throws { var keyData = try getPrefixNodeData(oldPassword) if keyData == nil { throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") } defer { Data.zero(&keyData!) } try encryptDataToStorage(newPassword, data: keyData!, aesMode: keystoreParams!.crypto.cipher) } fileprivate func getPrefixNodeData(_ password: String) throws -> Data? { guard let keystorePars = keystoreParams else { return nil } guard let saltData = Data.fromHex(keystorePars.crypto.kdfparams.salt) else { return nil } let derivedLen = keystorePars.crypto.kdfparams.dklen var passwordDerivedKey: Data? switch keystorePars.crypto.kdf { case "scrypt": guard let N = keystorePars.crypto.kdfparams.n else { return nil } guard let P = keystorePars.crypto.kdfparams.p else { return nil } guard let R = keystorePars.crypto.kdfparams.r else { return nil } passwordDerivedKey = scrypt(password: password, salt: saltData, length: derivedLen, N: N, R: R, P: P) case "pbkdf2": guard let algo = keystorePars.crypto.kdfparams.prf else { return nil } let hashVariant = try HmacVariant(algo) guard let c = keystorePars.crypto.kdfparams.c else { return nil } guard let derivedArray = try? BetterPBKDF(password: Array(password.utf8), salt: saltData.bytesWeb, iterations: c, keyLength: derivedLen, variant: hashVariant) else { return nil } passwordDerivedKey = Data(bytes: derivedArray) default: return nil } guard let derivedKey = passwordDerivedKey else { return nil } var dataForMAC = Data() let derivedKeyLast16bytes = derivedKey[(derivedKey.count - 16) ... (derivedKey.count - 1)] dataForMAC.append(derivedKeyLast16bytes) guard let cipherText = Data.fromHex(keystorePars.crypto.ciphertext) else { return nil } guard cipherText.count % 32 == 0 else { return nil } dataForMAC.append(cipherText) let mac = dataForMAC.keccak256() guard let calculatedMac = Data.fromHex(keystorePars.crypto.mac), mac.constantTimeComparisonTo(calculatedMac) else { return nil } let cipher = keystorePars.crypto.cipher let decryptionKey = derivedKey[0 ... 15] guard let IV = Data.fromHex(keystorePars.crypto.cipherparams.iv) else { return nil } var decryptedPK: Array<UInt8>? switch cipher { case "aes-128-ctr": let aesCipher = AES(key: decryptionKey.bytesWeb, blockMode: CTR(iv: IV.bytesWeb), padding: .pkcs7) decryptedPK = try aesCipher.decrypt(cipherText.bytesWeb) case "aes-128-cbc": let aesCipher = AES(key: decryptionKey.bytesWeb, blockMode: CBC(iv: IV.bytesWeb), padding: .pkcs7) decryptedPK = try? aesCipher.decrypt(cipherText.bytesWeb) default: return nil } guard decryptedPK != nil else { return nil } guard decryptedPK?.count == 82 else { return nil } return Data(bytes: decryptedPK!) } /// Returns Json file that you can store and export public func serialize() throws -> Data? { guard let params = self.keystoreParams else { return nil } let data = try JSONEncoder().encode(params) return data } /// Returns your root node string public func serializeRootNodeToString(password: String = "BANKEXFOUNDATION") throws -> String { guard let decryptedRootNode = try? self.getPrefixNodeData(password), decryptedRootNode != nil else { throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") } guard let rootNode = HDNode(decryptedRootNode!) else { throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") } guard let string = rootNode.serializeToString(serializePublic: false) else { throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") } return string } } /// HDWallet Json parameters (Native representation) public struct KeystoreParamsBIP32: Decodable, Encodable { var crypto: CryptoParamsV3 var id: String? var version: Int = 32 var isHDWallet: Bool var pathToAddress: [String: String] var rootPath: String? init(crypto cr: CryptoParamsV3, id i: String, version ver: Int, rootPath: String? = nil) { crypto = cr id = i version = ver isHDWallet = true pathToAddress = [String: String]() self.rootPath = rootPath } }
50.875389
191
0.664503
e96bcd8983b2ed24cb51b5c2e2cc0fa6194076db
104
import PackageDescription let package = Package( name: "RotationalCipher" //"rotational-cipher" )
17.333333
51
0.740385
697c8124926623a4f6dc7d4061250660841e1d27
8,858
// // NetSendAU.swift // VST3NetSend // // Created by Vlad Gorlov on 15.07.17. // Copyright © 2017 Vlad Gorlov. All rights reserved. // import AVFoundation import mcxMediaAU import mcxMediaExtensions public final class NetSendAU: NSObject { private var au: AVAudioUnit? private var timeStamp = AudioTimeStamp() private var isActive: Bool = false private var buffer: AVAudioPCMBuffer? private var sampleRate: Double = 44100 private var blockSize: UInt32 = 512 private var numberOfChannels: UInt32 = 2 private var vstBufferList: UnsafeMutablePointer<AudioBufferList>? public override init() { super.init() let desc = AudioComponentDescription(type: kAudioUnitType_Effect, subType: kAudioUnitSubType_NetSend) let sema = DispatchSemaphore(value: 1) AVAudioUnit.instantiate(with: desc, options: [.loadInProcess]) { [weak self] avAU, error in if let e = error { log.error(.media, e) } else if let avAU = avAU { self?.au = avAU } else { fatalError() } sema.signal() } if sema.wait(timeout: .now() + 1) == .timedOut { log.info(.media, "Timout waiting for `AVAudioUnit.instantiate` callback.") } timeStamp.mFlags = [.sampleTimeValid] timeStamp.mSampleTime = 0 setTransmissionFormatIndex(kAUNetSendPresetFormat_PCMFloat32) setPortNumber(52800) setServiceName("WaveLabs VST3NetSend") setPassword("") setupStreamFormat(sampleRate: sampleRate, blockSize: blockSize, numChannels: numberOfChannels) setupRenderCallback() } deinit { setActive(false) au = nil } } extension NetSendAU { @objc public func setupProcessing(_ setupInfo: NetSendProcessSetup) { sampleRate = setupInfo.sampleRate blockSize = setupInfo.maxSamplesPerBlock setupStreamFormat(sampleRate: sampleRate, blockSize: blockSize, numChannels: numberOfChannels) } @objc public func setActive(_ shouldActivate: Bool) { guard let au = au?.audioUnit else { return } if shouldActivate, !isActive { guard AudioUnitInitialize(au) == noErr else { log.error(.media, "Unable to initialize AUNetSend instance.") return } isActive = true } else if isActive { guard AudioUnitUninitialize(au) == noErr else { log.error(.media, "Unable to uninitialize AUNetSend instance.") return } isActive = false } } @objc public func render(numberOfFrames: UInt32, bufferList: UnsafeMutablePointer<AudioBufferList>) { guard let au = au?.audioUnit, let buffer = buffer else { return } assert(numberOfFrames <= buffer.frameCapacity) buffer.frameLength = numberOfFrames vstBufferList = bufferList var actionFlags = AudioUnitRenderActionFlags(rawValue: 0) let status = AudioUnitRender(au, &actionFlags, &timeStamp, 0, numberOfFrames, buffer.mutableAudioBufferList) assert(status == noErr) timeStamp.mSampleTime += Float64(numberOfFrames) } @objc public func setNumberOfChannels(_ numChannels: UInt32) { numberOfChannels = numChannels setupStreamFormat(sampleRate: sampleRate, blockSize: blockSize, numChannels: numberOfChannels) } @objc public func setServiceName(_ serviceName: String) { guard let au = au?.audioUnit else { return } setProperty("ServiceName") { try AudioUnitSettings.setProperty(for: au, propertyID: kAUNetSendProperty_ServiceName, scope: .global, element: 0, data: serviceName as CFString) } } @objc public func setPassword(_ password: String) { guard let au = au?.audioUnit else { return } setProperty("Password") { try AudioUnitSettings.setProperty(for: au, propertyID: kAUNetSendProperty_Password, scope: .global, element: 0, data: password as CFString) } } @objc public func setTransmissionFormatIndex(_ formatIndex: UInt32) { guard let au = au?.audioUnit else { return } assert(formatIndex < kAUNetSendNumPresetFormats) setProperty("TransmissionFormatIndex") { try AudioUnitSettings.setProperty(for: au, propertyID: kAUNetSendProperty_TransmissionFormatIndex, scope: .global, element: 0, data: formatIndex) } } @objc public func setDisconnect(_ flag: UInt32) { guard let au = au?.audioUnit else { return } setProperty("Disconnect") { try AudioUnitSettings.setProperty(for: au, propertyID: kAUNetSendProperty_Disconnect, scope: .global, element: 0, data: flag) } } @objc public func setPortNumber(_ port: UInt32) { guard let au = au?.audioUnit else { return } setProperty("PortNum") { try AudioUnitSettings.setProperty(for: au, propertyID: kAUNetSendProperty_PortNum, scope: .global, element: 0, data: port) } } @objc public func getStatus() -> Int { var result: Float32 = -1 guard let au = au?.audioUnit else { return Int(result) } getParameter("Status") { result = try AudioUnitSettings.getParameter(for: au, parameterID: kAUNetSendParam_Status, scope: .global, element: 0) } return Int(result) } } extension NetSendAU { private func setProperty(_ name: String, closure: () throws -> Void) { do { try closure() } catch { log.error(.media, "Unable to set property `\(name)`.") } } private func getParameter(_ name: String, closure: () throws -> Void) { do { try closure() } catch { log.error(.media, "Unable to get parameter `\(name)`.") } } private func setupRenderCallback() { guard let au = au?.audioUnit else { return } let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) let callback = AURenderCallbackStruct(inputProc: renderCallback, inputProcRefCon: context) setProperty("SetRenderCallback") { try AudioUnitSettings.setProperty(for: au, propertyID: kAudioUnitProperty_SetRenderCallback, scope: .input, element: 0, data: callback) } } fileprivate func render(flags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, timestamp: UnsafePointer<AudioTimeStamp>, busNumber: UInt32, numberOfFrames: UInt32, data: UnsafeMutablePointer<AudioBufferList>?) -> OSStatus { guard let vstBufferList = vstBufferList, let data = data else { return kAudioUnitErr_Uninitialized } let ablVST = UnsafeMutableAudioBufferListPointer(vstBufferList) let ablAU = UnsafeMutableAudioBufferListPointer(data) guard ablVST.count == ablAU.count else { return kAudioUnitErr_FormatNotSupported } for index in 0 ..< ablVST.count { let abVST = ablVST[index] let abAU = ablAU[index] assert(abAU.mDataByteSize == abVST.mDataByteSize) memcpy(abAU.mData, abVST.mData, Int(abAU.mDataByteSize)) } return noErr } private func setupStreamFormat(sampleRate: Double, blockSize: UInt32, numChannels: UInt32) { guard let au = au?.audioUnit else { return } guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: numChannels, interleaved: false) else { fatalError() } let sd = format.streamDescription.pointee setProperty("StreamFormat (Input)") { try AudioUnitSettings.setProperty(for: au, propertyID: kAudioUnitProperty_StreamFormat, scope: .input, element: 0, data: sd) } setProperty("StreamFormat (Output)") { try AudioUnitSettings.setProperty(for: au, propertyID: kAudioUnitProperty_StreamFormat, scope: .output, element: 0, data: sd) } guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: blockSize) else { fatalError() } self.buffer = buffer } } private let renderCallback: AURenderCallback = { inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData in let thisRef: Unmanaged<NetSendAU> = Unmanaged.fromOpaque(inRefCon) let this = thisRef.takeUnretainedValue() return this.render(flags: ioActionFlags, timestamp: inTimeStamp, busNumber: inBusNumber, numberOfFrames: inNumberFrames, data: ioData) }
35.862348
129
0.637277
79d5784bcff19c7a24be7d8d5090690bc37aa48d
1,033
// // BuAgentSchedulePublishedScheduleReference.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class BuAgentSchedulePublishedScheduleReference: Codable { /** The globally unique identifier for the object. */ public var _id: String? /** The start week date for this schedule. Dates are represented as an ISO-8601 string. For example: yyyy-MM-dd */ public var weekDate: Date? /** The number of weeks encompassed by the schedule */ public var weekCount: Int? /** The URI for this object */ public var selfUri: String? public init(_id: String?, weekDate: Date?, weekCount: Int?, selfUri: String?) { self._id = _id self.weekDate = weekDate self.weekCount = weekCount self.selfUri = selfUri } public enum CodingKeys: String, CodingKey { case _id = "id" case weekDate case weekCount case selfUri } }
22.955556
118
0.634076
62589f03ae2bff3bdedfceffd9f21b62b689b1ba
122
import XCTest import SainiUtilsTests var tests = [XCTestCaseEntry]() tests += SainiUtilsTests.allTests() XCTMain(tests)
15.25
35
0.786885
ebc6c6e2ab89c6a76d2cac14fa8a3a5a708daada
216
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a{typealias d:d class A{ func a{{}{}}
27
87
0.75
cc2db5f0a05c58bdaddec4566c46b95f422d988e
693
// // UICollection+Extension.swift // News // // Created by zlf on 2018/5/10. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit extension UICollectionView { func ym_registerCell <T: UICollectionViewCell> (cell: T.Type) where T: RegistterCellOrNib{ if let nib = T.nib { register(nib, forCellWithReuseIdentifier: T.identifier) }else { register(cell, forCellWithReuseIdentifier: T.identifier) } } func ym_dequeueReuseableCell <T: UICollectionViewCell> (indexPath: IndexPath) -> T where T: RegistterCellOrNib { return dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as! T } }
28.875
116
0.678211
ff3d65fb14f43e014968d597bec0361be6522001
906
// // ZActivityViewStyle.swift // UIBase // // Created by 郭春茂 on 2021/4/23. // import Foundation public class ZActivityViewStyle : UIViewStyle { public var itemWidth: CGFloat = 56 public var itemPaddingX: CGFloat = 16 public var itemPaddingY: CGFloat = 12 public var itemPadding: CGFloat = 2 public var buttonApperance = ZButtonAppearance(.textLinkThin, textColor: StateListColor(singleColor: .bluegrey_700), iconPosition: .top, height: 66, textSize: 12, iconSize: 40, iconPadding: 8).normalized() public override init() { super.init() } }
31.241379
107
0.454746
624f100a4245a3c70b660a049e7447256bafc203
454
// // CompleteOrderView.swift // TeslaOrderForm // // Created by Craig Clayton on 1/24/20. // Copyright © 2020 Cocoa Academy. All rights reserved. // import SwiftUI struct CompleteOrderView: View { @EnvironmentObject var order:OrderViewModel var body: some View { Text("Complete Order View") } } struct CompleteOrderView_Previews: PreviewProvider { static var previews: some View { CompleteOrderView() } }
18.916667
56
0.682819
20f5dbf1bfdc84c15c3ebf450aefef00009ba5b4
611
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import battery_plus_macos import path_provider_macos import shared_preferences_macos import sqflite func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { BatteryPlusMacosPlugin.register(with: registry.registrar(forPlugin: "BatteryPlusMacosPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) }
32.157895
98
0.833061
fc472f8f44bfb46426952cb122d26ffe2fd313c1
653
// 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 // RUN: not %target-swift-frontend %s -typecheck // Issue found by https://github.com/benshan (Ben Shanfelder) import Cocoa protocol A: class { var target: AnyObject? { set } // FIXME: Missing "get" wrt extension on NSControl leads to crash. } class B: NSObject { } extension NSControl: A {}
28.391304
101
0.728943
bf21880e4f0dba09af4fe8929ea0aeae429dcefa
1,116
// // 392-IsSubsequence.swift // Greedy // // Created by Csy on 2019/3/31. // Copyright © 2019 CXL. All rights reserved. // /** 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 示例 1: s = "abc", t = "ahbgdc" 返回 true. 示例 2: s = "axc", t = "ahbgdc" 返回 false. */ import Foundation class IsSubsequence { func isSubsequence(_ s: String, _ t: String) -> Bool { let sLength = s.count let tLength = t.count if sLength == 0 { return true } if tLength == 0 { return false } // 字符串转换成数组 let sChars = Array(s) let tChars = Array(t) // 找到相同的就一起递增 var i = 0 var j = 0 while i < sLength && j < tLength{ if sChars[i] == tChars[j] { i += 1 j += 1 } else { j += 1 } } return (i == sLength) } }
18.6
84
0.466846
9b24894cf913c4b0c30b55a30cb930f1d4cd8c6c
672
// // Constants.swift // MovieExplorer // // Created by Ahmad Ansari on 17/04/2019. // Copyright © 2019 Ahmad Ansari. All rights reserved. // import Foundation struct Constants { // MARK: - Logger Constants static let loggerFormat = "$D[HH:mm:ss]$d $L: $M" // MARK: - Database Constants static let XCDataModelFile = "MovieDB" // MARK: - Service Constants static let defaultPageSize = 20 static let defaultPosterSize = 92 static let defaultBackdropSize = 500 static let releaseDateFormat = "yyyy-MM-dd" // MARK: - UI Constants static let dateDisplayFormat = "dd MMMM yyyy" }
24
61
0.626488