repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
steelwheels/Coconut
CoconutData/Source/File/CNFilePath.swift
1
5592
/** * @file CNFilePath.swift * @brief Define CNFilePath class * @par Copyright * Copyright (C) 2015 Steel Wheels Project */ import Foundation /** * Define methods to operate the file URL */ public class CNFilePath { public enum FilePathError { case ok(_ url: URL) case error(_ error: NSError) } public enum FilePathsError { case ok(_ urls: [URL]) case error(_ error: NSError) } public class func URLForBundleFile(bundleName bname: String?, fileName fname: String?, ofType type: String?) -> FilePathError { let mainbundle = Bundle.main if let bundlepath = mainbundle.path(forResource: bname, ofType: "bundle") { if let resourcebundle = Bundle(path: bundlepath) { if let resourcepath = resourcebundle.path(forResource: fname, ofType: type){ if let url = URL(string: "file://" + resourcepath) { return .ok(url) } } return .error(NSError.fileError(message: "File \"\(name(fname))\" of type \"\(name(type))\" is not found")) } else { return .error(NSError.fileError(message: "Failed to allocate bundle \"\(bundlepath)\"")) } } else { return .error(NSError.fileError(message: "\(name(bname)).bundle is not found")) } } public class func URLForResourceFile(fileName fname: String, fileExtension fext: String, subdirectory subdir: String?, forClass fclass: AnyClass?) -> URL? { let bundle: Bundle if let cls = fclass { bundle = Bundle(for: cls) } else { bundle = Bundle.main } if let dir = subdir { return bundle.url(forResource: fname, withExtension: fext, subdirectory: dir) } else { return bundle.url(forResource: fname, withExtension: fext) } } public class func URLForResourceDirectory(directoryName dname: String, subdirectory subdir: String?, forClass fclass: AnyClass?) -> URL? { let bundle: Bundle if let cls = fclass { bundle = Bundle(for: cls) } else { bundle = Bundle.main } if let dir = subdir { return bundle.url(forResource: dname, withExtension: nil, subdirectory: dir) } else { return bundle.url(forResource: dname, withExtension: nil) } } public class func URLsForResourceFiles(fileExtension fext: String, subdirectory subdir: String?, forClass fclass: AnyClass?) -> FilePathsError { let bundle: Bundle if let cls = fclass { bundle = Bundle(for: cls) } else { bundle = Bundle.main } if let result = bundle.urls(forResourcesWithExtension: fext, subdirectory: subdir) { return .ok(result) } else { let err: NSError if let dir = subdir { err = NSError.fileError(message: "Failed to read bundle for ext \(fext) in subdir \(dir)") } else { err = NSError.fileError(message: "Failed to read bundle for ext \(fext)") } return .error(err) } } public class func URLsForResourceFiles(fileExtension fext: String, subdirectory subdir: String?, bundleName bname: String) -> FilePathsError { let mainbundle = Bundle.main if let bundlepath = mainbundle.path(forResource: bname, ofType: "bundle") { if let bundle = Bundle(path: bundlepath) { if let result = bundle.urls(forResourcesWithExtension: fext, subdirectory: subdir) { return .ok(result) } else { let err: NSError if let dir = subdir { err = NSError.fileError(message: "Failed to read bundle \(bname) for ext \(fext) in subdir \(dir)") } else { err = NSError.fileError(message: "Failed to read bundle \(bname) for ext \(fext)") } return .error(err) } } } return .error(NSError.fileError(message: "Failed to find bundle \(bname)")) } public class func URLforApplicationSupportDirectory(subDirectory subdir: String?) -> URL { let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true) var dir: String if path.count > 0 { dir = path[0] } else { dir = NSHomeDirectory() + "/Application Support" } if let sub = subdir { dir += "/" + sub } return URL(fileURLWithPath: dir, isDirectory: true) } public class func URLForApplicationSupportFile(fileName fname: String, fileExtension fext: String, subdirectory subdir: String?) -> URL { var baseurl = URLforApplicationSupportDirectory(subDirectory: subdir) baseurl.appendPathComponent(fname + "." + fext) return baseurl } public class func URLforTempDirectory() -> URL { return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) } /* reference: https://qiita.com/masakihori/items/8d4af538b040c65a8871 */ public class func UTIForFile(URL url: URL) -> String? { guard let r = try? url.resourceValues(forKeys: [.typeIdentifierKey]) else { return nil } return r.typeIdentifier } public class func relativePathUnderBaseURL(fullPath fpath: URL, basePath bpath: URL) -> String? { let fcomp = fpath.pathComponents let bcomp = bpath.pathComponents if bcomp.count < fcomp.count { /* Check they have same path */ for i in 0..<bcomp.count { if fcomp[i] != bcomp[i] { CNLog(logLevel: .error, message: "Not matched path (0): \(fpath.path) <-> \(bpath.path)", atFunction: #function, inFile: #file) return nil } } /* Make relative comp */ var newcomp: Array<String> = [] for i in bcomp.count ..< fcomp.count { newcomp.append(fcomp[i]) } let newpath = newcomp.joined(separator: "/") return newpath } else { CNLog(logLevel: .error, message: "Not matched path (1): \(fpath.path) <-> \(bpath.path)", atFunction: #function, inFile: #file) return nil } } private class func name(_ name: String?) -> String { if let str = name { return str } else { return "<unknown>" } } }
lgpl-2.1
d0230bffbe992935b034184ab0a336ef
30.772727
157
0.6799
3.451852
false
false
false
false
WTGrim/WTOfo_Swift
Ofo_Swift/Ofo_Swift/ViewController.swift
1
11385
// // ViewController.swift // Ofo_Swift // // Created by Dwt on 2017/9/22. // Copyright © 2017年 Dwt. All rights reserved. // import UIKit import SWRevealViewController import FTIndicator class ViewController: UIViewController , MAMapViewDelegate, AMapSearchDelegate, AMapNaviWalkManagerDelegate{ //底部控制台 @IBOutlet weak var functionView: UIView! @IBOutlet weak var panelView: UIView! @IBOutlet weak var scanBtn: ScanButton! var controlPanelLayer:CAShapeLayer! var mapView:MAMapView! var search:AMapSearchAPI! var minePin:MinePinAnnotation! var minePinView:MAPinAnnotationView! var searchNear = true var currentAnnotations : [MAPointAnnotation] = [] var start, end : CLLocationCoordinate2D! var walkManager : AMapNaviWalkManager! override func viewDidLoad() { super.viewDidLoad() setupUI() } //定位 @IBAction func locationClick(_ sender: UIButton) { searchNear = true searchNearBike() } } //Mark:-自定义的相关方法 extension ViewController{ fileprivate func setupUI() { navigationItem.titleView = UIImageView(image:UIImage.init(named: "Login_Logo_117x25_")) navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.tintColor = UIColor.black //高德地图 mapView = MAMapView(frame:view.bounds) mapView.delegate = self mapView.zoomLevel = 17 mapView.showsUserLocation = true mapView.userTrackingMode = .follow view.addSubview(mapView) search = AMapSearchAPI() search.delegate = self walkManager = AMapNaviWalkManager() walkManager.delegate = self view.bringSubview(toFront: panelView) if let revealVC = revealViewController(){ revealVC.rearViewRevealWidth = 280 navigationItem.leftBarButtonItem?.target = revealVC navigationItem.leftBarButtonItem?.action = #selector(SWRevealViewController.revealToggle(_:)) view.addGestureRecognizer(revealVC.panGestureRecognizer()) } //绘制控制面板 controlPanelLayer = CAShapeLayer() controlPanelLayer.lineWidth = 1.0 controlPanelLayer.fillColor = UIColor.white.cgColor let color = UIColor.white color.set() let path = UIBezierPath() path.lineWidth = 1.0 path.lineCapStyle = .round path.lineJoinStyle = .round path.move(to: CGPoint(x: 0, y: panelView.bounds.height)) path.addLine(to: CGPoint(x: 0, y: 40)) path.addQuadCurve(to: CGPoint(x:panelView.bounds.width, y:40), controlPoint: CGPoint(x:panelView.bounds.width / 2.0, y:-40)) path.addLine(to: CGPoint(x: panelView.bounds.width, y: panelView.bounds.height)) path.close() path.fill() controlPanelLayer.path = path.cgPath controlPanelLayer.shadowOffset = CGSize(width: 0, height: -5) controlPanelLayer.shadowOpacity = 0.1 controlPanelLayer.shadowColor = UIColor.black.cgColor panelView.layer.insertSublayer(controlPanelLayer, below: functionView.layer) scanBtn.addTarget(self, action: #selector(scanClick), for: .touchUpInside) scanBtn.layer.shadowOffset = CGSize(width: 4, height: 10) scanBtn.layer.shadowColor = UIColor(red: 217/255.0, green: 197/255.0, blue: 47/255.0, alpha: 1).cgColor scanBtn.layer.shadowOpacity = 0.2 } //用餐馆模拟成小黄车 fileprivate func searchCustomLocation(_ center:CLLocationCoordinate2D) { let request = AMapPOIAroundSearchRequest() request.location = AMapGeoPoint.location(withLatitude: CGFloat(center.latitude), longitude: CGFloat(center.longitude)) request.keywords = "餐馆" request.radius = 600 request.requireExtension = true search.aMapPOIAroundSearch(request) } //搜索周边小黄车 fileprivate func searchNearBike() { searchCustomLocation(mapView.userLocation.coordinate) } //大头针动画 fileprivate func pinAnimation() { let frame = minePinView.frame minePinView.frame = frame.offsetBy(dx: 0, dy: -20) UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { self.minePinView.frame = frame }) { (completed) in } } @objc fileprivate func scanClick(){ print("点击扫描") } } //Mark:-相关代理 extension ViewController{ //poi检索完成后的回调 func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) { guard response.count > 0 else { print("没有小黄车") return } var annotations : [MAPointAnnotation] = [] annotations = response.pois.map{ let annotation = MAPointAnnotation() annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees($0.location.latitude), longitude: CLLocationDegrees($0.location.longitude)) if $0.distance < 50 {//红包车 annotation.title = "红包区域开锁小黄车" annotation.subtitle = "骑行10分钟可获得现金红包" }else{ annotation.title = "正常可用" } return annotation } //先删除当前的annotation mapView.removeAnnotations(currentAnnotations) currentAnnotations = annotations mapView.addAnnotations(annotations) if searchNear {//第一次搜索 显示地图缩放动画, 其他没有动画 mapView.showAnnotations(annotations, animated: true) searchNear = !searchNear } } //自定义大头针 func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! { //用户的位置,不需要自定义 if annotation is MAUserLocation{ return nil } if annotation is MinePinAnnotation{//如果是我的位置 let pinId = "minePin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: pinId) as? MAPinAnnotationView if pinView == nil{ pinView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: pinId) } pinView?.image = UIImage(named:"homePage_wholeAnchor_24x37_") pinView?.canShowCallout = false minePinView = pinView return pinView } let reuseId = "annotationId" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MAPinAnnotationView if annotationView == nil{ annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) } if annotation.title == "正常可用" { annotationView?.image = UIImage(named: "HomePage_nearbyBike_33x36_") }else{ annotationView?.image = UIImage(named:"HomePage_nearbyBikeRedPacket_33x36_") } annotationView?.canShowCallout = true // annotationView?.animatesDrop = true return annotationView } //地图初始化完成,设置用户位置大头针 func mapInitComplete(_ mapView: MAMapView!) { minePin = MinePinAnnotation() minePin.coordinate = mapView.centerCoordinate minePin.lockedScreenPoint = CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2) minePin.isLockedToScreen = true mapView.addAnnotation(minePin) mapView.showAnnotations([minePin], animated: true) //搜索 searchNear = true searchNearBike() } //用户移动地图,重新搜索 func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) { if wasUserAction{ mapView.removeOverlays(mapView.overlays) minePin.isLockedToScreen = true pinAnimation() searchCustomLocation(mapView.centerCoordinate) } } //添加地图标注动画 func mapView(_ mapView: MAMapView!, didAddAnnotationViews views: [Any]!) { let views = views as! [MAAnnotationView] for view in views { guard view.annotation is MAPointAnnotation else{ continue } view.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { view.transform = .identity }, completion: { (completed) in }) } } //选中标注 func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) { start = minePin.coordinate end = view.annotation.coordinate let startPoint = AMapNaviPoint.location(withLatitude: CGFloat(start.latitude), longitude: CGFloat(start.longitude))! let endPoint = AMapNaviPoint.location(withLatitude: CGFloat(end.latitude), longitude: CGFloat(end.longitude))! walkManager.calculateWalkRoute(withStart: [startPoint], end: [endPoint]) } //绘制路线 func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! { if overlay is MAPolyline{ minePin.isLockedToScreen = false mapView.visibleMapRect = overlay.boundingMapRect let render = MAPolylineRenderer(overlay: overlay) render?.lineWidth = 4.0 render?.strokeColor = UIColor.green return render } return nil } //Mark:-AMapNaviWalkViewDelegate 导航代理 func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) { print("路线规划成功") var cordinates = walkManager.naviRoute!.routeCoordinates!.map { return CLLocationCoordinate2D(latitude: CLLocationDegrees($0.latitude), longitude: CLLocationDegrees($0.longitude)) } let polyline = MAPolyline(coordinates: &cordinates, count: UInt(cordinates.count)) mapView.removeOverlays(mapView.overlays) mapView.add(polyline) //提示时间和距离 let time = walkManager.naviRoute!.routeTime / 60 var timeDes = "1分钟以内" if time > 0 { timeDes = time.description + "分钟" } let hintTitle = "步行" + timeDes let hintSubTitle = "距离" + walkManager.naviRoute!.routeLength.description + "米" FTIndicator.setIndicatorStyle(.dark) FTIndicator.showNotification(with: UIImage(named:"clock_24x24_"), title: hintTitle, message: hintSubTitle) } func walkManager(_ walkManager: AMapNaviWalkManager, onCalculateRouteFailure error: Error) { print("路线规划失败",error) } }
mit
fe33d6a8b0955a3ebeda4f6b0137832e
33.888179
162
0.625
4.731369
false
false
false
false
yankodimitrov/SignalKit
SignalKit/Extensions/NSNotificationCenterExtensions.swift
1
792
// // NSNotificationCenterExtensions.swift // SignalKit // // Created by Yanko Dimitrov on 3/6/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import Foundation public extension SignalEventType where Sender: NSNotificationCenter { /// Observe the notification center for a given notification public func notification(name: String, fromObject: AnyObject? = nil) -> Signal<NSNotification> { let signal = Signal<NSNotification>() let observer = NotificationObserver(center: sender, name: name, object: fromObject) observer.notificationCallback = { [weak signal] in signal?.sendNext($0) } signal.disposableSource = observer return signal } }
mit
06945ad0e7111651118ce3a3cbd3b13c
26.275862
100
0.642225
5.203947
false
false
false
false
sarah-j-smith/Quest
Quest/GameStateViewController.swift
1
5385
// // GameStateViewController.swift // SwiftAdventure // // Created by Sarah Smith on 2/01/2015. // Copyright (c) 2015 Sarah Smith. All rights reserved. // import Foundation import Cocoa var GameStateObservingCtx = 0 /** The root view controller for the game editor */ class GameStateViewController : NSViewController, NSTextFieldDelegate, QuestController { @IBOutlet var gameStateObjectController : NSObjectController! @IBOutlet var gameTitleTextField : NSTextField! @IBOutlet var gameTitleLabel : NSTextField! @IBOutlet var gameTitleBox : NSView! @IBOutlet var editTitleButton : NSButton! @IBOutlet var editGameButton: NSButton! var isObserved = false var boundViewController : NSViewController? var bindingPath : String! deinit { NSLog("deinit GameStateViewController") } override func viewDidLoad() { gameTitleTextField.hidden = true startObserving() } override func viewWillDisappear() { stopObserving() } override func viewWillAppear() { if let bvc = boundViewController { bvc.unbind(bindingPath) } } @IBAction func editGameTitle(sender : AnyObject) { let w = view.window! if gameTitleTextField.hidden { gameTitleTextField.hidden = false w.makeFirstResponder(gameTitleTextField) } else { gameTitleTextField.hidden = true editTitleButton.state = NSOffState w.makeFirstResponder(view) } } @IBAction func editingFinished(sender : AnyObject) { gameTitleTextField.hidden = true editTitleButton.state = NSOffState let w = view.window! w.makeFirstResponder(view) } @IBAction func editGame(sender : AnyObject) { let rvc = rootViewController()! NSLog("Creating RoomListViewController") let roomListViewController = RoomListViewController(nibName:"RoomListView", bundle: nil)! NSLog("About to switch to view") bindViewController(roomListViewController, binding: "selection") rvc.addChildViewController(roomListViewController) rvc.switchToView(roomListViewController, transition: NSViewControllerTransitionOptions.SlideForward) } func bindViewController(viewController: NSViewController, binding: String) { boundViewController = viewController bindingPath = binding NSLog("Binding representedObject") viewController.bind("representedObject", toObject:gameStateObjectController, withKeyPath:binding, options: nil) } func unbindViewController() { if let bvc = boundViewController { bvc.unbind(bindingPath) boundViewController = nil } } // MARK: QuestController compliance var drillDownShouldBeEnabled = true var configureShouldBeEnabled = true func drillDownAction() -> Bool { editGame(self) return true } func configureAction() -> Bool { editGameTitle(self) return true } // MARK: Observing func startObserving() { if isObserved { NSLog("Game already observed") } else { self.addObserver(self, forKeyPath: "representedObject.gameName", options: NSKeyValueObservingOptions.Old, context: &GameStateObservingCtx) isObserved = true } } func stopObserving() { if isObserved { self.removeObserver(self, forKeyPath: "representedObject.gameName", context: &GameStateObservingCtx) isObserved = false } else { NSLog("Cannot stop observing - not listed as observed") } } func change(keyPath : String, ofObject object: NSObject, toValue: AnyObject?) { NSLog("Changed object: \(object) to be \(toValue)") object.setValue(toValue, forKeyPath: keyPath) } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if (context != &GameStateObservingCtx) { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) return } var oldValue: NSObject? = change[NSKeyValueChangeOldKey] as? NSObject if (oldValue == NSNull()) { NSLog("GameState oldValue is nil") oldValue = nil } else { if let oldNameStr = oldValue as? String { if let gameState = gameStateObjectController.content as? GameState { if oldNameStr != gameState.gameName { NSLog("Game name changed from \(oldNameStr) to \(gameState.gameName)") let undo = self.undoManager! undo.prepareWithInvocationTarget(self).change(keyPath, ofObject: object as NSObject, toValue: oldValue) undo.setActionName("Edit Name") } } } } } }
mit
d3a645d447e1a103ba936deccbe2af35
27.497354
127
0.602043
5.37962
false
false
false
false
pengjinning/AppKeFu_iOS_Demo_V4
AppKeFuDemo7Swift/AppKeFuDemo7Swift/Controllers/KFTagsTableViewController.swift
1
4958
// // TagsTableViewController.swift // AppKeFuDemo7Swift // // Created by jack on 16/8/5. // Copyright © 2016年 appkefu.com. All rights reserved. // import Foundation class KFTagsTableViewController: UITableViewController { override init(style: UITableViewStyle) { super.init(style: style) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "用户标签" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData(); } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 7; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" //tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) //var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier); if(cell == nil){ cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier); } cell!.accessoryType = UITableViewCellAccessoryType.disclosureIndicator; if ((indexPath as NSIndexPath).row == 0) { cell!.textLabel?.text = "1.用户昵称" cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagNickname() != nil ? AppKeFuLib.sharedInstance().getTagNickname() : "1"; } else if ((indexPath as NSIndexPath).row == 1) { cell!.textLabel?.text = "2.性别"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagSex() != nil ? AppKeFuLib.sharedInstance().getTagSex(): "2" } else if ((indexPath as NSIndexPath).row == 2) { cell!.textLabel?.text = "3.语言"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagLanguage() != nil ? AppKeFuLib.sharedInstance().getTagLanguage(): "3" } else if ((indexPath as NSIndexPath).row == 3) { cell!.textLabel?.text = "4.城市"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagCity() != nil ? AppKeFuLib.sharedInstance().getTagCity() : "4" } else if ((indexPath as NSIndexPath).row == 4) { cell!.textLabel?.text = "5.省份"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagProvince() != nil ? AppKeFuLib.sharedInstance().getTagProvince() : "5" } else if ((indexPath as NSIndexPath).row == 5) { cell!.textLabel?.text = "6.国家"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagCountry() != nil ? AppKeFuLib.sharedInstance().getTagCountry() : "6" } else if ((indexPath as NSIndexPath).row == 6) { cell!.textLabel?.text = "7.其他"; cell!.detailTextLabel?.text = AppKeFuLib.sharedInstance().getTagOther() != nil ? AppKeFuLib.sharedInstance().getTagOther() : "7" } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell: UITableViewCell = tableView.cellForRow(at: indexPath)! let tagsChangeVC: KFTagsChangeTableViewController = KFTagsChangeTableViewController.init(style: UITableViewStyle.grouped) if ((indexPath as NSIndexPath).row == 0) { tagsChangeVC.tag = "NICKNAME"; } else if ((indexPath as NSIndexPath).row == 1) { tagsChangeVC.tag = "SEX"; } else if ((indexPath as NSIndexPath).row == 2) { tagsChangeVC.tag = "LANGUAGE"; } else if ((indexPath as NSIndexPath).row == 3) { tagsChangeVC.tag = "CITY"; } else if ((indexPath as NSIndexPath).row == 4) { tagsChangeVC.tag = "PROVINCE"; } else if ((indexPath as NSIndexPath).row == 5) { tagsChangeVC.tag = "COUNTRY"; } else if ((indexPath as NSIndexPath).row == 6) { tagsChangeVC.tag = "OTHER"; } tagsChangeVC.value = cell.detailTextLabel?.text; self.navigationController?.pushViewController(tagsChangeVC, animated: true) } }
mit
bf8d47dd1f3d796b7d03603531965480
31.124183
147
0.5941
4.658768
false
false
false
false
zisko/swift
test/IRGen/big_types_corner_cases_as_library.swift
1
798
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir -parse-as-library | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // UNSUPPORTED: resilient_stdlib public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden %swift.opaque* @"$S33big_types_corner_cases_as_library9BigStructVwCP" // CHECK: [[RETVAL:%.*]] = bitcast %T33big_types_corner_cases_as_library9BigStructV* {{.*}} to %swift.opaque* // CHECK: ret %swift.opaque* [[RETVAL]] let bigStructGlobalArray : [BigStruct] = [ BigStruct() ]
apache-2.0
ea784622346b010385bff9e805a8a6ba
37
206
0.677945
3.069231
false
false
false
false
alexmiragall/Gourmet-iOS
Gourmet/Gourmet/repositories/RestaurantMapper.swift
1
1287
// // RestaurantMapper.swift // gourmet // // Created by Alejandro Miragall Arnal on 24/3/16. // Copyright © 2016 Alejandro Miragall Arnal. All rights reserved. // import Foundation import Firebase class RestaurantMapper { func map(snapshot: FDataSnapshot) -> Restaurant { let restaurant: Restaurant = Restaurant() restaurant.name = snapshot.value.objectForKey("name") as? String restaurant.description = snapshot.value.objectForKey("description") as? String restaurant.address = snapshot.value.objectForKey("address") as? String restaurant.photo = snapshot.value?.objectForKey("photo") as? String restaurant.lat = snapshot.value?.objectForKey("lat") as? Double restaurant.lon = snapshot.value?.objectForKey("lon") as? Double return restaurant } func mapInverse(restaurant: Restaurant) -> Dictionary<String, AnyObject> { var dictionary = Dictionary<String, AnyObject>() dictionary["name"] = restaurant.name dictionary["description"] = restaurant.description dictionary["address"] = restaurant.address dictionary["photo"] = restaurant.photo dictionary["lat"] = restaurant.lat dictionary["lon"] = restaurant.lon return dictionary } }
mit
ba89747475dd8e9932ceaeef384e7680
36.852941
86
0.683515
4.693431
false
false
false
false
vermont42/Conjugar
Conjugar/TestAnalyticsService.swift
1
669
// // TestAnalyticsService.swift // Conjugar // // Created by Joshua Adams on 11/25/18. // Copyright © 2018 Josh Adams. All rights reserved. // import Foundation class TestAnalyticsService: AnalyticsServiceable { private var fire: (String) -> () init(fire: @escaping (String) -> () = { analytic in print(analytic) }) { self.fire = fire } func recordEvent(_ eventName: String, parameters: [String: String]?, metrics: [String: Double]?) { var analytic = eventName if let parameters = parameters { analytic += " " for (key, value) in parameters { analytic += key + ": " + value + " " } } fire(analytic) } }
agpl-3.0
7187910b0c47709ea1e1a80d959a6985
22.857143
100
0.618263
3.731844
false
true
false
false
pkl728/ZombieInjection
ZombieInjection/ZombieRealmDataService.swift
1
3653
// // ZombieRealmDataService.swift // ZombieInjection // // Created by Patrick Lind on 6/13/17. // Copyright © 2017 Patrick Lind. All rights reserved. // import Foundation import RealmSwift class ZombieRealmDataService: ZombieDataServiceProtocol { let realm = try! Realm() func get(_ id: Int) -> Zombie? { guard let object = realm.object(ofType: Zombie.RealmObject.self, forPrimaryKey: id) else { return nil } return object.originalValue() } func get(_ predicate: (Zombie) throws -> Bool) -> Zombie? { guard let allItems = try? realm.objects(Zombie.RealmObject.self) else { return nil } var newItems: Array<Zombie> = [] for var item in allItems { newItems.append(item.originalValue()) } guard let itemToReturn = try? newItems.filter(predicate).first else { return nil } return itemToReturn } func getAll() -> Array<Zombie>? { var resultsToReturn: Array<Zombie> = [] let results: Array<Zombie.RealmObject> = Array(realm.objects(Zombie.RealmObject.self)) results.forEach { resultsToReturn.append($0.originalValue()) } return resultsToReturn } func getAll(_ predicate: (Zombie) throws -> Bool) -> Array<Zombie>? { guard let results = try? realm.objects(Zombie.RealmObject.self) else { return nil } var resultsToReturn: Array<Zombie> = [] for result in results { resultsToReturn.append(result.originalValue()) } return resultsToReturn } func contains(_ predicate: (Zombie) throws -> Bool) -> Bool { guard let results = try? realm.objects(Zombie.RealmObject.self) else { return false } var resultsToCheck: Array<Zombie> = [] for result in results { resultsToCheck.append(result.originalValue()) } let isPresent = try? resultsToCheck.contains(where: predicate) return isPresent ?? false } func insert(_ item: Zombie) { try? realm.write { realm.add(item.realmObject) } } func insertAll(_ itemsToInsert: Array<Zombie>) { try? realm.write { var realmItemsToInsert: Array<Object> = [] itemsToInsert.forEach { realmItemsToInsert.append($0.realmObject) } realm.add(realmItemsToInsert) } } func delete(_ item: Zombie) { try? realm.write { realm.delete(item.realmObject) } } func deleteAll(_ predicate: (Zombie) throws -> Bool) { guard let items = try? realm.objects(Zombie.RealmObject.self) else { return } try? realm.write { realm.delete(items) } } func deleteAll() { try? realm.write { realm.deleteAll() } } func update(_ item: Zombie) { try? realm.write { realm.add(item.realmObject, update: true) } } func count() -> Int { return realm.objects(Zombie.RealmObject.self).count } func count(_ predicate: (Zombie) throws -> Bool) -> Int { guard let items = try? realm.objects(Zombie.RealmObject.self) else { return 0 } var itemsToCount: Array<Zombie> = [] for item in items { itemsToCount.append(item.originalValue()) } let count = try? itemsToCount.filter(predicate).count return count ?? 0 } }
mit
10b0127567e2f72c766cf48728c28218
27.53125
98
0.562979
4.576441
false
false
false
false
multinerd/Mia
Mia/Testing/UITableView/CollapsibleTableViewSections/CollapsibleTableSectionViewController.swift
1
6320
import UIKit // MARK: - CollapsibleTableSectionDelegate @objc public protocol CollapsibleTableSectionDelegate { @objc optional func numberOfSections(_ tableView: UITableView) -> Int @objc optional func collapsibleTableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int @objc optional func collapsibleTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell @objc optional func collapsibleTableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) @objc optional func collapsibleTableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat @objc optional func collapsibleTableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat @objc optional func collapsibleTableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat @objc optional func collapsibleTableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? @objc optional func shouldCollapseByDefault(_ tableView: UITableView) -> Bool @objc optional func shouldCollapseOthers(_ tableView: UITableView) -> Bool } // MARK: - View Controller open class CollapsibleTableSectionViewController: UIViewController { public var delegate: CollapsibleTableSectionDelegate? fileprivate var _tableView: UITableView! fileprivate var _sectionsState = [ Int: Bool ]() @IBOutlet weak var tableView: UITableView! { didSet { tableView!.dataSource = self tableView!.delegate = self tableView!.estimatedRowHeight = 44.0 tableView!.rowHeight = UITableViewAutomaticDimension } } public func isSectionCollapsed(_ section: Int) -> Bool { if _sectionsState.index(forKey: section) == nil { _sectionsState[section] = delegate?.shouldCollapseByDefault?(tableView ?? _tableView!) ?? false } return _sectionsState[section]! } func getSectionsNeedReload(_ section: Int) -> [Int] { var sectionsNeedReload = [ section ] let isCollapsed = !isSectionCollapsed(section) _sectionsState[section] = isCollapsed let shouldCollapseOthers = delegate?.shouldCollapseOthers?(tableView ?? _tableView!) ?? false if !isCollapsed && shouldCollapseOthers { let filteredSections = _sectionsState.filter { !$0.value && $0.key != section } let sectionsNeedCollapse = filteredSections.map { $0.key } for item in sectionsNeedCollapse { _sectionsState[item] = true } sectionsNeedReload.append(contentsOf: sectionsNeedCollapse) } return sectionsNeedReload } override open func viewDidLoad() { super.viewDidLoad() if tableView == nil { _tableView = UITableView() _tableView.dataSource = self _tableView.delegate = self _tableView.estimatedRowHeight = 44.0 _tableView.rowHeight = UITableViewAutomaticDimension view.addSubview(_tableView) _tableView.translatesAutoresizingMaskIntoConstraints = false _tableView.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor).isActive = true _tableView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.bottomAnchor).isActive = true _tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true _tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true } } } // MARK: - View Controller DataSource and Delegate extension CollapsibleTableSectionViewController: UITableViewDataSource, UITableViewDelegate { public func numberOfSections(in tableView: UITableView) -> Int { return delegate?.numberOfSections?(tableView) ?? 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let numberOfRows = delegate?.collapsibleTableView?(tableView, numberOfRowsInSection: section) ?? 0 return isSectionCollapsed(section) ? 0 : numberOfRows } // Cell public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return delegate?.collapsibleTableView?(tableView, cellForRowAt: indexPath) ?? UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "DefaultCell") } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return delegate?.collapsibleTableView?(tableView, heightForRowAt: indexPath) ?? UITableViewAutomaticDimension } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.collapsibleTableView?(tableView, didSelectRowAt: indexPath) } // Header public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: "header", section: section, delegate: self) let title = delegate?.collapsibleTableView?(tableView, titleForHeaderInSection: section) ?? "" header.titleLabel.text = title header.arrowLabel.text = ">" header.setCollapsed(isSectionCollapsed(section)) header.section = section header.delegate = self return header } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return delegate?.collapsibleTableView?(tableView, heightForHeaderInSection: section) ?? 30.0 } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return delegate?.collapsibleTableView?(tableView, heightForFooterInSection: section) ?? 0.0 } } // MARK: - Section Header Delegate extension CollapsibleTableSectionViewController: CollapsibleTableViewHeaderDelegate { public func toggleSection(_ section: Int) { let sectionsNeedReload = getSectionsNeedReload(section) (tableView ?? _tableView!).reloadSections(IndexSet(sectionsNeedReload), with: .automatic) } }
mit
fa2408f4a55ec0b9f75a26c1fa801a19
31.57732
175
0.708703
5.597874
false
false
false
false
KSMissQXC/KS_DYZB
KS_DYZB/KS_DYZB/Classes/Tools/KSNetworkTool.swift
1
1008
// // KSNetworkTool.swift // KS_DYZB // // Created by 耳动人王 on 2016/11/2. // Copyright © 2016年 KS. All rights reserved. // import UIKit import Alamofire enum MethodType{ case get case post } //typealias FinishCallBack = (_ result : Any) -> () class KSNetworkTool { class func requestData(_ type : MethodType,URLString : String,parameters : [String : Any]? = nil,_ callBack : @escaping (_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post //发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (respose) in //获取结果 guard let result = respose.result.value else{ print(respose.result.error ?? "error") return } callBack(result) } } func loadData(_ finishedCallback : @escaping (_ jsonData : String) -> (),name : String){ } }
mit
5ed19765acfdf994998c75fdfc7c19f1
22.829268
149
0.568066
4.193133
false
false
false
false
KrishMunot/swift
test/ClangModules/enum.swift
3
6095
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil %s -verify // -- Check that we can successfully round-trip. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -D IRGEN -emit-ir %s >/dev/null // REQUIRES: objc_interop import Foundation import user_objc // NS_ENUM var mince = NSRuncingMode.mince var quince = NSRuncingMode.quince var rawMince: UInt = NSRuncingMode.mince.rawValue var rawFoo: CInt = NSUnderlyingType.foo.rawValue var rawNegativeOne: CUnsignedInt = NSUnsignedUnderlyingTypeNegativeValue.negativeOne.rawValue var rawWordBreakA: Int = NSPrefixWordBreak.banjo.rawValue var rawWordBreakB: Int = NSPrefixWordBreak.bandana.rawValue var rawWordBreak2A: Int = NSPrefixWordBreak2.breakBarBas.rawValue var rawWordBreak2B: Int = NSPrefixWordBreak2.breakBareBass.rawValue var rawWordBreak3A: Int = NSPrefixWordBreak3.break1Bob.rawValue var rawWordBreak3B: Int = NSPrefixWordBreak3.break1Ben.rawValue var singleConstant = NSSingleConstantEnum.value var myCoolWaterMelon = MyCoolEnum.waterMelon var hashMince: Int = NSRuncingMode.mince.hashValue if NSRuncingMode.mince != .quince { } var numberBehavior: NSNumberFormatterBehavior = .behaviorDefault numberBehavior = .behavior10_4 var postingStyle: NSPostingStyle = .postWhenIdle postingStyle = .postASAP func handler(_ formatter: NSByteCountFormatter) { // Ensure that the Equality protocol is properly added to an // imported ObjC enum type before the type is referenced by name if (formatter.countStyle == .file) {} } // Unfortunate consequence of treating runs of capitals as a single word. // See <rdar://problem/16768954>. var pathStyle: CFURLPathStyle = .cfurlposixPathStyle pathStyle = .cfurlWindowsPathStyle var URLOrUTI: CFURLOrUTI = .cfurlKind URLOrUTI = .cfutiKind let magnitude: Magnitude = .k2 let magnitude2: MagnitudeWords = .two let objcABI: objc_abi = .v2 let underscoreSuffix: ALL_CAPS_ENUM = .ENUM_CASE_ONE let underscoreSuffix2: ALL_CAPS_ENUM2 = .CASE_TWO var alias1 = NSAliasesEnum.bySameValue var alias2 = NSAliasesEnum.byEquivalentValue var alias3 = NSAliasesEnum.byName var aliasOriginal = NSAliasesEnum.original switch aliasOriginal { case .original: break case .differentValue: break } switch aliasOriginal { case .original: break default: break } switch aliasOriginal { case .bySameValue: break case .differentValue: break } switch aliasOriginal { case .bySameValue: break default: break } switch aliasOriginal { case NSAliasesEnum.bySameValue: break case NSAliasesEnum.differentValue: break } extension NSAliasesEnum { func test() { switch aliasOriginal { case bySameValue: break case differentValue: break } } } // Test NS_SWIFT_NAME: _ = NSXMLNodeKind.DTDKind == .invalidKind _ = NSPrefixWordBreakCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreak2Custom.problemCase == .goodCase _ = NSPrefixWordBreak2Custom.problemCase == .PrefixWordBreak2DeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreak2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReversedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReorderedCustom.problemCase == .goodCase _ = NSPrefixWordBreakReorderedCustom.problemCase == .PrefixWordBreakReorderedDeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReorderedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReordered2Custom.problemCase == .goodCase _ = NSPrefixWordBreakReordered2Custom.problemCase == .PrefixWordBreakReordered2DeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReordered2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSSwiftNameAllTheThings.Foo == .Bar _ = NSSwiftNameBad.`class` #if !IRGEN var qualifiedName = NSRuncingMode.mince var topLevelCaseName = NSRuncingMince // expected-error{{}} #endif // NS_OPTIONS var withMince: NSRuncingOptions = .enableMince var withQuince: NSRuncingOptions = .enableQuince // When there is a single enum constant, compare it against the type name to // derive the namespaced name. var singleValue: NSSingleOptions = .value // Check OptionSet conformance. var minceAndQuince: NSRuncingOptions = NSRuncingOptions.enableMince.intersect(NSRuncingOptions.enableQuince) var minceOrQuince: NSRuncingOptions = [.enableMince, .enableQuince] minceOrQuince.intersectInPlace(minceAndQuince) minceOrQuince.unionInPlace(minceAndQuince) var minceValue: UInt = minceAndQuince.rawValue var minceFromMask: NSRuncingOptions = [] // Strip leading 'k' in "kConstant". let calendarUnit: CFCalendarUnit = [.year, .weekday] // ...unless the next character is a non-identifier. let curve3D: AU3DMixerAttenuationCurve = .k3DMixerAttenuationCurve_Exponential // Match various plurals. let observingOpts: NSKeyValueObservingOptions = [.new, .old] let bluetoothProps: CBCharacteristicProperties = [.write, .writeWithoutResponse] let buzzFilter: AlertBuzzes = [.funk, .sosumi] // Match multi-capital acronym. let bitmapFormat: NSBitmapFormat = [.NSAlphaFirstBitmapFormat, .NS32BitBigEndianBitmapFormat]; let bitmapFormatR: NSBitmapFormatReversed = [.NSAlphaFirstBitmapFormatR, .NS32BitBigEndianBitmapFormatR]; let bitmapFormat2: NSBitmapFormat2 = [.NSU16a , .NSU32a] let bitmapFormat3: NSBitmapFormat3 = [.NSU16b , .NSS32b] let bitmapFormat4: NSUBitmapFormat4 = [.NSU16c , .NSU32c] let bitmapFormat5: NSABitmapFormat5 = [.NSAA16d , .NSAB32d] // Drop trailing underscores when possible. let timeFlags: CMTimeFlags = [.valid , .hasBeenRounded] let timeFlags2: CMTimeFlagsWithNumber = [._Valid, ._888] let audioComponentOpts: AudioComponentInstantiationOptions = [.loadOutOfProcess] let audioComponentFlags: AudioComponentFlags = [.sandboxSafe] let audioComponentFlags2: FakeAudioComponentFlags = [.loadOutOfProcess] let objcFlags: objc_flags = [.taggedPointer, .swiftRefcount] let optionsWithSwiftName: NSOptionsAlsoGetSwiftName = .Case
apache-2.0
de66bdb89fb0f5e34f412a622e572bad
32.674033
131
0.790484
3.662861
false
false
false
false
danwaltin/SwiftSpec
Sources/SwiftSpec/XCUnitTestGenerator.swift
1
7802
// ------------------------------------------------------------------------ // Copyright 2017 Dan Waltin // // 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. // ------------------------------------------------------------------------ // // XCUnitTestGenerator.swift // SwiftSpec // // Created by Dan Waltin on 2016-06-26. // // ------------------------------------------------------------------------ import Foundation import GherkinSwift let ignoreTag = "ignore" class XCUnitTestGenerator: UnitTestGenerator { private let builder: UnitTestBuilder init(builder: UnitTestBuilder) { self.builder = builder } func generateUnitTest(result: PickleResult, fromFeatureFilePath: String) -> String { var t = "" t = t.appendLine(builder.header()) switch result { case .success(let document): if let feature = document.feature { t = t.appendLine(builder.featureClass(feature: feature)) t = t.appendLine(builder.setupAndTearDown(feature: feature)) for s in feature.expandedScenarios() { t = t.appendLine(builder.scenario(scenario: s)) } t = t.appendLine(builder.endClass()) } case .error(let errors): t = t.appendLine(builder.parseErrorFeatureClass(featureFilePath: fromFeatureFilePath)) if errors.count == 0 { t = t.appendLine(builder.unknownError()) } else { var index = 0 for error in errors { t = t.appendLine(builder.error(index: index, parseError: error)) index += 1 } } t = t.appendLine(builder.endClass()) } return t } } class UnitTestBuilderImp : UnitTestBuilder { let ignoreTestBaseClass = "Ignore" let testCaseBaseClass = "XCTestCase" func header() -> String { return """ // // AUTOGENERATED FILE // This code was generated by SwiftSpec // // Changes to this file may cause // incorrect behaviour and will be lost // if the file is regenerated. // import XCTest import SwiftSpec """ } func featureClass(feature: Feature) -> String { let className = "\(ignorePrefix(feature))\(testEntityName(feature))" return testClassDeclaration(name: className, baseClass: superClass(feature)) } func setupAndTearDown(feature: Feature) -> String { return """ var testRunner:TestRunner! var scenarioContext:ScenarioContext! override func setUp() { super.setUp() scenarioContext = ScenarioContextImplementation() scenarioContext.featureTags = \(featureTags(feature)) testRunner = TestRunner(scenarioContext: scenarioContext) } override func tearDown() { testRunner = nil scenarioContext = nil super.tearDown() } """ } func scenario(scenario: Scenario) -> String { return "func \(ignorePrefix(scenario))test\(testEntityName(scenario))() {\n" + scenarioTags(scenario) + steps(scenario) + "}" } func endClass() -> String { return "}" } func parseErrorFeatureClass(featureFilePath: String) -> String { return testClassDeclaration(name: testEntityName(featureFilePath), baseClass: testCaseBaseClass) } func unknownError() -> String { return """ func testUnknownErrorOccurred() { XCTFail("An unknown error occurred when parsing feature file") } """ } func error(index: Int, parseError: ParseError) -> String { return """ func testParseErrorOccurred\(index)() { XCTFail("\(parseError.message)", file: "\(parseError.source.uri)", line: \(parseError.source.location.line)) } """ } // MARK: - helpers private func testClassDeclaration(name: String, baseClass: String) -> String { return "class \(name)Tests : \(baseClass) {" } private func steps(_ scenario: Scenario) -> String { if scenario.steps.count == 0 { return "" } var steps = "" steps += line("do {") var tableCounter = 0 for s in scenario.steps { if s.tableParameter != nil { tableCounter += 1 } steps += step(s, tableCounter: tableCounter) } steps += line("} catch {") steps += line("XCTFail(\"\\(error)\")") steps += line("}") return steps } private func step(_ step: Step, tableCounter: Int) -> String { let type = ".\(step.type)" let text = "\"\(step.text)\"" if step.tableParameter == nil { return line(executeStep("\(type), \(text)")) } let tableParameterName = "table\(tableCounter)" var tableParameter = tableDeclaration(step.tableParameter!, tableParameterName) tableParameter += line(executeStep("\(type), \(text), \(tableParameterName)")) return tableParameter } private func tableDeclaration(_ table: Table, _ parameterName: String) -> String { var t = line("let \(parameterName) = TableParameter(columns: \(tableParameterColumns(table)))") for row in table.rows { t += line(".addingRow(cells: \(tableRowCells(table, row)))") } return t } private func tableParameterColumns(_ table: Table) -> String { return arrayParameter(table.header.cells.map { $0.value }) } private func tableRowCells(_ table: Table, _ row: TableRow) -> String { return arrayParameter(row.cells.map {$0.value}) } private func executeStep(_ parameters: String) -> String { return "try testRunner.executeStep(\(parameters))" } private func lines(_ lines: [String]) -> String { return lines.reduce("") {$0.appendLine($1)} } private func line(_ s: String) -> String { return s.appendLine() } private func testEntityName(_ entity: HasName) -> String { return cleanedTestEntityName(entity.name) } private func testEntityName(_ path: String) -> String { let name = path.lastPathComponent().stringByDeletingPathExtension() return cleanedTestEntityName(name) } private func cleanedTestEntityName(_ name: String) -> String { return replaceSpecialCharacters(name).camelCaseify() } private func ignorePrefix(_ entity: Taggable) -> String { if containsIgnore(tags: entity.tags) { return "IGNORE_" } return "" } private func superClass(_ feature: Feature) -> String { if containsIgnore(tags: feature.tags) { return ignoreTestBaseClass } return testCaseBaseClass } private func containsIgnore(tags: [Tag]) -> Bool { return tags.map {$0.name}.contains(ignoreTag) } private func featureTags(_ taggable: Taggable) -> String { if taggable.tags.count == 0 { return "[]" } return "\(tagsArray(taggable))" } private func scenarioTags(_ taggable: Taggable) -> String { if taggable.tags.count == 0 { return "" } return line("scenarioContext.tags = \(tagsArray(taggable))") } private func tagsArray(_ taggable: Taggable) -> String { return arrayParameter(taggable.tags.map { $0.name}) } private func arrayParameter(_ items: [String]) -> String { let itemsAsStrings = items.map {"\"" + $0 + "\""} return "[" + itemsAsStrings.joined(separator: ", ") + "]" } private func replaceSpecialCharacters(_ input: String) -> String { let replacements = [ "å": "a", "ä": "a", "ö": "o", "Å": "A", "Ä": "A", "Ö": "O", "-": " "] return string(fromString: input, byReplacingCharacters: replacements) } private func string(fromString: String, byReplacingCharacters replacements: [String: String]) -> String { var toString = fromString for (from, to) in replacements { toString = toString.replacingOccurrences(of: from, with: to) } return toString } }
apache-2.0
7c629d67ea3792e766c58d283dc04ebd
25.073579
111
0.65508
3.719466
false
true
false
false
owensd/proteus
src/parser.swift
1
8758
import Foundation struct ScannerInfo { let character: Character? let line: Int let column: Int } class Scanner { var content: String var index: String.Index var current: ScannerInfo? = nil private var shouldStall = false var line: Int = 0 var column: Int = 0 init(content: String) { self.content = content self.index = content.startIndex self._defaults() } func _defaults() { self.index = content.startIndex self.line = 0 self.column = 0 self.shouldStall = false self.current = nil } func stall() { shouldStall = true } func next() -> ScannerInfo? { if shouldStall { shouldStall = false return current } if index == content.endIndex { current = nil } else { current = ScannerInfo(character: content[index], line: line, column: column) index = index.successor() if current?.character == "\n" { line++ column = 0 } else { column++ } } return current } func peek() -> ScannerInfo? { return current } func debugPrint() { print("--- SCANNER INFO ---") while let info = self.next() { print("\(info)") } print("") self._defaults() } } enum Token { case Identifier(String, line: Int, column: Int) case Keyword(String, line: Int, column: Int) case OpenParen(line: Int, column: Int) case CloseParen(line: Int, column: Int) case StringLiteral(String, line: Int, column: Int) case Terminal(line: Int, column: Int) case EOF var stringValue: String { switch self { case let .Identifier(value, _, _): return value case let .StringLiteral(value, _, _): return value case let .Keyword(value, _, _): return value default: return "" } } } func isCharacterPartOfSet(c: Character?, set: NSCharacterSet) -> Bool { guard let c = c else { return false } var isMember = true for utf16Component in String(c).utf16 { if !set.characterIsMember(utf16Component) { isMember = false; break } } return isMember } func isValidIdentifierSignalCharacter(c: Character?) -> Bool { return isCharacterPartOfSet(c, set: NSCharacterSet.letterCharacterSet()) } func isValidIdenitifierCharacter(c: Character?) -> Bool { return isCharacterPartOfSet(c, set: NSCharacterSet.letterCharacterSet()) } func isWhitespace(c: Character?) -> Bool { return isCharacterPartOfSet(c, set: NSCharacterSet.whitespaceCharacterSet()) } let keywords = ["import", "func"] class Lexer { var scanner: Scanner var current: Token? = nil init(scanner: Scanner) { self.scanner = scanner } func next() -> Token? { func work() -> Token? { if scanner.next() == nil { return .EOF } scanner.stall() while let info = scanner.next() where isWhitespace(info.character) {} scanner.stall() guard let next = scanner.next() else { return .EOF } if next.character == "\n" { return .Terminal(line: next.line, column: next.column) } else if isValidIdentifierSignalCharacter(next.character) { var content = String(next.character!) while let info = scanner.next() where isValidIdenitifierCharacter(info.character) { content.append(info.character!) } scanner.stall() if keywords.contains(content) { return .Keyword(content, line: next.line, column: next.column) } else { return .Identifier(content, line: next.line, column: next.column) } } else if next.character == "(" { return .OpenParen(line: next.line, column: next.column) } else if next.character == ")" { return .CloseParen(line: next.line, column: next.column) } else if next.character == "\"" { var content = String(next.character!) while let info = scanner.next() where info.character != "\"" { content.append(info.character!) } content.append(scanner.peek()!.character!) return .StringLiteral(content, line: next.line, column: next.column) } return nil } if case .EOF? = self.current { self.current = nil } else { self.current = work() } return self.current } func tokenize() -> [Token] { var tokens = [Token]() while let token = self.next() { tokens.append(token) } return tokens } func peek() -> Token? { return current } func debugPrint() { print("--- TOKENS ---") while let token = self.next() { print("\(token)") } print("") self.scanner._defaults() self.current = nil } } enum Error : ErrorType { case InvalidSyntax(String) case Generic(String) } enum Declaration { case Function(name: Token, arguments: [(Token, Token)], returnType: Token, body: [Statement]) } enum Statement { case Import(package: Token) case Function(name: Token, params: [Token]) } class Parser { let lexer: Lexer init(lexer: Lexer) { self.lexer = lexer } func parse() throws -> [Statement] { var parsed = [Statement]() while let _ = lexer.next() { if let importStatement = try parseImport(lexer) { parsed.append(importStatement) } else if let functionInvocationStatement = try parseFunctionInvocationStatement(lexer) { parsed.append(functionInvocationStatement) } } return parsed } } func parseImport(lexer: Lexer) throws -> Statement? { guard let keywordToken = lexer.peek() else { return nil } guard case let .Keyword(keyword, _, _) = keywordToken where keyword == "import" else { return nil } guard let identifierToken = lexer.next() else { throw Error.InvalidSyntax("Expected identifier") } guard case .Identifier(_, _, _) = identifierToken else { throw Error.InvalidSyntax("Expected identifier") } guard case .Terminal(_, _)? = lexer.next() else { throw Error.InvalidSyntax("Expected terminal") } return .Import(package: identifierToken) } func parseFunctionInvocationStatement(lexer: Lexer) throws -> Statement? { guard let identifierToken = lexer.peek() else { return nil } guard case .Identifier = identifierToken else { return nil } guard let openParenToken = lexer.next() else { return nil } guard case .OpenParen = openParenToken else { return nil } var params = [Token]() while let nextToken = lexer.next() { switch nextToken { case .CloseParen: if case .Terminal? = lexer.next() { return .Function(name: identifierToken, params: params) } else { throw Error.InvalidSyntax("Invalid function invocation") } case .StringLiteral: params.append(nextToken) default: throw Error.InvalidSyntax("Invalid function invocation") } } throw Error.InvalidSyntax("Invalid function invocation") } func convertASTToC(ast: [Statement]) throws -> String { var code = "" func isImport(statement: Statement) -> Bool { if case .Import = statement { return true } else { return false } } for importStatement in ast.filter({isImport($0)}) { if case let .Import(package) = importStatement { if package.stringValue == "stdlib" { code += "#include <stdlib.h>\n" code += "#include <stdio.h>\n" } } } // TODO(owensd): Need a mechanism to actually dictate we have the main function. code += "int main(int argc, char **argv) {\n" for statement in ast.filter({!isImport($0)}) { if case let .Function(identifier, params) = statement { if identifier.stringValue == "print" { code += "printf(" code += (params.map { $0.stringValue } as NSArray).componentsJoinedByString(",") code += ");" } } } code += "\nreturn 0;\n}\n" return code }
mit
8c976ccfb2fda03393a06299cc45274e
26.283489
111
0.556748
4.530781
false
false
false
false
ahoppen/swift
stdlib/public/core/Result.swift
6
6771
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A value that represents either a success or a failure, including an /// associated value in each case. @frozen public enum Result<Success, Failure: Error> { /// A success, storing a `Success` value. case success(Success) /// A failure, storing a `Failure` value. case failure(Failure) /// Returns a new result, mapping any success value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a success. The following example transforms /// the integer success value of a result into a string: /// /// func getNextInteger() -> Result<Int, Error> { /* ... */ } /// /// let integerResult = getNextInteger() /// // integerResult == .success(5) /// let stringResult = integerResult.map { String($0) } /// // stringResult == .success("5") /// /// - Parameter transform: A closure that takes the success value of this /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new success value if this instance represents a success. @inlinable public func map<NewSuccess>( _ transform: (Success) -> NewSuccess ) -> Result<NewSuccess, Failure> { switch self { case let .success(success): return .success(transform(success)) case let .failure(failure): return .failure(failure) } } /// Returns a new result, mapping any failure value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a failure. The following example transforms /// the error value of a result by wrapping it in a custom `Error` type: /// /// struct DatedError: Error { /// var error: Error /// var date: Date /// /// init(_ error: Error) { /// self.error = error /// self.date = Date() /// } /// } /// /// let result: Result<Int, Error> = // ... /// // result == .failure(<error value>) /// let resultWithDatedError = result.mapError { DatedError($0) } /// // result == .failure(DatedError(error: <error value>, date: <date>)) /// /// - Parameter transform: A closure that takes the failure value of the /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new failure value if this instance represents a failure. @inlinable public func mapError<NewFailure>( _ transform: (Failure) -> NewFailure ) -> Result<Success, NewFailure> { switch self { case let .success(success): return .success(success) case let .failure(failure): return .failure(transform(failure)) } } /// Returns a new result, mapping any success value using the given /// transformation and unwrapping the produced result. /// /// Use this method to avoid a nested result when your transformation /// produces another `Result` type. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an result type. /// /// func getNextInteger() -> Result<Int, Error> { /// .success(4) /// } /// func getNextAfterInteger(_ n: Int) -> Result<Int, Error> { /// .success(n + 1) /// } /// /// let result = getNextInteger().map { getNextAfterInteger($0) } /// // result == .success(.success(5)) /// /// let result = getNextInteger().flatMap { getNextAfterInteger($0) } /// // result == .success(5) /// /// - Parameter transform: A closure that takes the success value of the /// instance. /// - Returns: A `Result` instance, either from the closure or the previous /// `.failure`. @inlinable public func flatMap<NewSuccess>( _ transform: (Success) -> Result<NewSuccess, Failure> ) -> Result<NewSuccess, Failure> { switch self { case let .success(success): return transform(success) case let .failure(failure): return .failure(failure) } } /// Returns a new result, mapping any failure value using the given /// transformation and unwrapping the produced result. /// /// - Parameter transform: A closure that takes the failure value of the /// instance. /// - Returns: A `Result` instance, either from the closure or the previous /// `.success`. @inlinable public func flatMapError<NewFailure>( _ transform: (Failure) -> Result<Success, NewFailure> ) -> Result<Success, NewFailure> { switch self { case let .success(success): return .success(success) case let .failure(failure): return transform(failure) } } /// Returns the success value as a throwing expression. /// /// Use this method to retrieve the value of this result if it represents a /// success, or to catch the value if it represents a failure. /// /// let integerResult: Result<Int, Error> = .success(5) /// do { /// let value = try integerResult.get() /// print("The value is \(value).") /// } catch { /// print("Error retrieving the value: \(error)") /// } /// // Prints "The value is 5." /// /// - Returns: The success value, if the instance represents a success. /// - Throws: The failure value, if the instance represents a failure. @inlinable public func get() throws -> Success { switch self { case let .success(success): return success case let .failure(failure): throw failure } } } extension Result where Failure == Swift.Error { /// Creates a new result by evaluating a throwing closure, capturing the /// returned value as a success, or any thrown error as a failure. /// /// - Parameter body: A throwing closure to evaluate. @_transparent public init(catching body: () throws -> Success) { do { self = .success(try body()) } catch { self = .failure(error) } } } extension Result: Equatable where Success: Equatable, Failure: Equatable { } extension Result: Hashable where Success: Hashable, Failure: Hashable { } extension Result: Sendable where Success: Sendable { }
apache-2.0
a648d60757b9413fc6e78868613b63a0
33.902062
80
0.616896
4.31824
false
false
false
false
lady12/firefox-ios
Storage/SQL/SchemaTable.swift
34
2154
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation // A table for holding info about other tables (also holds info about itself :)). This is used // to let us handle table upgrades when the table is first accessed, rather than when the database // itself is created. class SchemaTable: GenericTable<TableInfo> { override var name: String { return "tableList" } override var version: Int { return 1 } override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL UNIQUE, " + "version INTEGER NOT NULL" } override func getInsertAndArgs(inout item: TableInfo) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.name) args.append(item.version) return ("INSERT INTO \(name) (name, version) VALUES (?,?)", args) } override func getUpdateAndArgs(inout item: TableInfo) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.version) args.append(item.name) return ("UPDATE \(name) SET version = ? WHERE name = ?", args) } override func getDeleteAndArgs(inout item: TableInfo?) -> (String, [AnyObject?])? { var args = [AnyObject?]() var sql = "DELETE FROM \(name)" if let table = item { args.append(table.name) sql += " WHERE name = ?" } return (sql, args) } override var factory: ((row: SDRow) -> TableInfo)? { return { row -> TableInfo in return TableInfoWrapper(name: row["name"] as! String, version: row["version"] as! Int) } } override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? { var args = [AnyObject?]() if let filter: AnyObject = options?.filter { args.append(filter) return ("SELECT name, version FROM \(name) WHERE name = ?", args) } return ("SELECT name, version FROM \(name)", args) } }
mpl-2.0
1ea1dee80398e4b6f43d608246ec768f
37.464286
98
0.610956
4.248521
false
false
false
false
Rostmen/TimelineController
RZTimelineCollection/RZPostPlaceholderView.swift
1
2626
// // RZPostPlaceholderView.swift // RZTimelineCollection // // Created by Rostyslav Kobizsky on 12/23/14. // Copyright (c) 2014 Rozdoum. All rights reserved. // import UIKit class RZPostPlaceholderView: UIView { /** * Returns the activity indicator view for this placeholder view, or `nil` if it does not exist. */ private var _activityIndicatorView: UIActivityIndicatorView? var activityIndicatorView: UIActivityIndicatorView? { get { return _activityIndicatorView }} /** * Returns the image view for this placeholder view, or `nil` if it does not exist. */ private var _imageView: UIImageView? var imageView: UIImageView? { get { return _imageView }} override init(frame: CGRect) { super.init(frame: frame) self.userInteractionEnabled = false self.clipsToBounds = true self.contentMode = UIViewContentMode.ScaleAspectFill } convenience init(frame: CGRect, backgroundColor: UIColor) { self.init(frame: frame) self.backgroundColor = backgroundColor } convenience init(frame: CGRect, backgroundColor: UIColor, activityIndicatorView: UIActivityIndicatorView) { self.init(frame: frame, backgroundColor: backgroundColor) self.addSubview(activityIndicatorView) _activityIndicatorView = activityIndicatorView _activityIndicatorView?.center = center _activityIndicatorView?.startAnimating() _imageView = nil } convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle) { let lightGrayColor = UIColor.lightGrayColor() let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) let frame = CGRect(x: 0, y: 0, width: 200, height: 120) spinner.color = lightGrayColor.darkeningColorWithValue(0.4) self.init(frame: frame, backgroundColor: lightGrayColor, activityIndicatorView: spinner) } convenience init(frame: CGRect, imageView anImageView: UIImageView, backgroundColor: UIColor) { self.init(frame: frame, backgroundColor: backgroundColor) self.addSubview(anImageView) _imageView = imageView _imageView?.center = center _activityIndicatorView = nil } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { if _activityIndicatorView != nil { _activityIndicatorView?.center = self.center } if _imageView != nil { _imageView?.center = self.center } } }
apache-2.0
a177d0895a200db03b34f7a4c016689b
34.486486
111
0.680122
5.179487
false
false
false
false
AlexZd/SwiftUtils
Pod/Utils/CLPlacemark+Helpers.swift
1
998
// // CLPlacemark+Helpers.swift // Pods // // Created by Alex Zdorovets on 3/14/17. // // import MapKit import Contacts extension CLPlacemark { public var fullAddress: String { if let addressDic = self.addressDictionary, let lines = addressDic["FormattedAddressLines"] as? [String] { return lines.joined(separator: ", ") } else if #available(iOS 9.0, *) { let postalAddress = CNMutablePostalAddress() postalAddress.street = self.thoroughfare ?? "" postalAddress.city = self.locality ?? "" postalAddress.state = self.administrativeArea ?? "" postalAddress.postalCode = self.postalCode ?? "" postalAddress.country = self.country ?? "" postalAddress.isoCountryCode = self.isoCountryCode ?? "" return CNPostalAddressFormatter.string(from: postalAddress, style: .mailingAddress) } else { return "Address not available" } } }
mit
126a0616f3ea057a03012d734c108a92
32.266667
114
0.614228
4.707547
false
false
false
false
FrancisBaileyH/Garden-Wall
Garden Wall/HomeViewController.swift
1
4360
// // ViewController.swift // Garden Wall // // Created by Francis Bailey on 2015-11-25. // Copyright © 2015 Francis Bailey. All rights reserved. // import UIKit import GBVersionTracking class HomeViewController: UIViewController { @IBOutlet weak var buildLabel: UILabel! let menu = [ ["Enable Adblocking"], ["Manage Whitelisted Websites", "Manage Custom Rules", "View Blocker List"] ] /* * Hide the navigation bar on the Home View only */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBarHidden = false } override func viewDidLoad() { super.viewDidLoad() buildLabel.text = "Version " + GBVersionTracking.currentVersion() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func showSettingsPopup() { let alert = UIAlertController(title: nil, message: "Enable ad blocking by pressing \"Go to Settings\" and navigating to Safari → Content Blockers and enabling Garden Wall.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil)) alert.addAction(UIAlertAction(title: "Go to Settings", style: UIAlertActionStyle.Default, handler: { (_) -> Void in let settingsUrl = NSURL(string: "prefs:root=Safari") if let url = settingsUrl { UIApplication.sharedApplication().openURL(url) } })) self.presentViewController(alert, animated: true, completion: nil) } } extension HomeViewController: UITableViewDelegate { /* * Show new controller based on which menu item was selected */ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: // open safari popup showSettingsPopup() break case 1: handleMenuSectionAction(indexPath.row) break default: break } tableView.deselectRowAtIndexPath(indexPath, animated: true) } /* * Handle a menu item selection and segue to corresponding view */ func handleMenuSectionAction(row: Int) { var segueId: String? switch row { case 0: segueId = "whitelistManagementSegue" break case 1: segueId = "advancedManagementSegue" break case 2: segueId = "fileViewerSegue" break default: segueId = nil } if let id = segueId { self.performSegueWithIdentifier(id, sender: nil) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu[section].count } /* * Configure basic table layout and view settings */ func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 20 } } extension HomeViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine; return menu.count } /* * Initialize Menu Item Cells */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell", forIndexPath: indexPath) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel!.text = menu[indexPath.section][indexPath.row] return cell } }
mit
bb974d9e438a19946fc17258150c6552
23.897143
227
0.590085
5.887838
false
false
false
false
Witcast/witcast-ios
Pods/PullToRefreshKit/Source/Classes/Right.swift
1
7646
// // Right.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/12. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit open class DefaultRefreshRight:UIView, RefreshableLeftRight, Tintable { open let imageView:UIImageView = UIImageView() open let textLabel:UILabel = UILabel().SetUp { $0.font = UIFont.systemFont(ofSize: 14) } fileprivate var textDic = [RefreshKitLeftRightText:String]() /** You can only call this function before pull */ open func setText(_ text:String,mode:RefreshKitLeftRightText){ textDic[mode] = text textLabel.text = textDic[.scrollToAction] } override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) addSubview(textLabel) textLabel.autoresizingMask = .flexibleHeight textLabel.numberOfLines = 0 imageView.frame = CGRect(x: 0, y: 0,width: 20, height: 20) let image = UIImage(named: "arrow_left", in: Bundle(for: DefaultRefreshHeader.self), compatibleWith: nil) imageView.image = image imageView.becomeTintable() textDic[.scrollToAction] = PullToRefreshKitRightString.scrollToViewMore textDic[.releaseToAction] = PullToRefreshKitRightString.releaseToViewMore textLabel.text = textDic[.scrollToAction] } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() textLabel.frame = CGRect(x: 30,y: 0,width: 20,height: frame.size.height) imageView.center = CGPoint(x: 10,y: frame.size.height/2) } // MARK: - RefreshableLeftRight Protocol - open func heightForRefreshingState() -> CGFloat { return PullToRefreshKitConst.defaultLeftWidth } open func percentUpdateDuringScrolling(_ percent:CGFloat){ if percent > 1.0{ guard self.imageView.transform == CGAffineTransform.identity else{ return } UIView.animate(withDuration: 0.4, animations: { self.imageView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi+0.000001) }) textLabel.text = textDic[.releaseToAction] } if percent <= 1.0{ guard self.imageView.transform == CGAffineTransform(rotationAngle: -CGFloat.pi+0.000001) else{ return } textLabel.text = textDic[.scrollToAction] UIView.animate(withDuration: 0.4, animations: { self.imageView.transform = CGAffineTransform.identity }) } } open func didCompleteEndRefershingAnimation() { imageView.transform = CGAffineTransform.identity textLabel.text = textDic[.scrollToAction] } open func didBeginRefreshing() { } // MARK: Tintable func setThemeColor(themeColor: UIColor) { imageView.tintColor = themeColor textLabel.textColor = themeColor } } class RefreshRightContainer:UIView{ // MARK: - Propertys - enum RefreshHeaderState { case idle case pulling case refreshing case willRefresh } var refreshAction:(()->())? var attachedScrollView:UIScrollView! weak var delegate:RefreshableLeftRight? fileprivate var _state:RefreshHeaderState = .idle var state:RefreshHeaderState{ get{ return _state } set{ guard newValue != _state else{ return } _state = newValue switch newValue { case .refreshing: DispatchQueue.main.async(execute: { self.delegate?.didBeginRefreshing() self.refreshAction?() self.endRefreshing() self.delegate?.didCompleteEndRefershingAnimation() }) default: break } } } // MARK: - Init - override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit(){ self.isUserInteractionEnabled = true self.backgroundColor = UIColor.clear self.autoresizingMask = .flexibleWidth } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life circle - override func draw(_ rect: CGRect) { super.draw(rect) if self.state == .willRefresh { self.state = .refreshing } } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) guard newSuperview is UIScrollView else{ return; } attachedScrollView = newSuperview as? UIScrollView addObservers() self.frame = CGRect(x: attachedScrollView.contentSize.width,y: 0,width: self.frame.width, height: self.frame.height) } deinit{ removeObservers() } // MARK: - Private - fileprivate func addObservers(){ attachedScrollView?.addObserver(self, forKeyPath:PullToRefreshKitConst.KPathOffSet, options: [.old,.new], context: nil) attachedScrollView?.addObserver(self, forKeyPath:PullToRefreshKitConst.KPathContentSize, options:[.old,.new] , context: nil) } fileprivate func removeObservers(){ attachedScrollView?.removeObserver(self, forKeyPath: PullToRefreshKitConst.KPathOffSet,context: nil) attachedScrollView?.removeObserver(self, forKeyPath: PullToRefreshKitConst.KPathOffSet,context: nil) } func handleScrollOffSetChange(_ change: [NSKeyValueChangeKey : Any]?){ if state == .refreshing { return; } let offSetX = attachedScrollView.contentOffset.x let contentWidth = attachedScrollView.contentSize.width let contentInset = attachedScrollView.contentInset let scrollViewWidth = attachedScrollView.bounds.width if attachedScrollView.isDragging { let percent = (offSetX + scrollViewWidth - contentInset.left - contentWidth)/self.frame.width self.delegate?.percentUpdateDuringScrolling(percent) if state == .idle && percent > 1.0 { self.state = .pulling }else if state == .pulling && percent <= 1.0{ state = .idle } }else if state == .pulling{ beginRefreshing() } } func handleContentSizeChange(_ change: [NSKeyValueChangeKey : Any]?){ self.frame = CGRect(x: self.attachedScrollView.contentSize.width,y: 0,width: self.frame.size.width,height: self.frame.size.height) } // MARK: - KVO - override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard self.isUserInteractionEnabled else{ return; } if keyPath == PullToRefreshKitConst.KPathOffSet { handleScrollOffSetChange(change) } guard !self.isHidden else{ return; } if keyPath == PullToRefreshKitConst.KPathContentSize { handleContentSizeChange(change) } } // MARK: - API - func beginRefreshing(){ if self.window != nil { self.state = .refreshing }else{ if state != .refreshing{ self.state = .willRefresh } } } func endRefreshing(){ self.state = .idle } }
apache-2.0
38a76d36dd3bae1f906e87911245675f
34.221198
151
0.617035
4.943726
false
false
false
false
idikic/mac-address-resolver-mvvm-swift
10_MODEL/MACAddressStore.swift
1
2708
// // MACAddressStore.swift // M.A.C. // // Created by iki on 17/07/14. // Copyright (c) 2014 Iki. All rights reserved. // class MACAddressStore: NSObject { // MARK: Singleton // More about singleton patterns is Swift can be found here: // https://github.com/hpique/SwiftSingleton class var sharedStore : MACAddressStore { struct Singleton { static let instance = MACAddressStore() } return Singleton.instance } var _privateItems = [MACAddressItem]() var allItems: [MACAddressItem] { return _privateItems } // MARK: Lifecycle private override init() { super.init() let unarchivedItems : AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithFile(itemArchivedPath) if unarchivedItems != nil { _privateItems = unarchivedItems as Array<MACAddressItem> } } // MARK: Public Interface func createItem(macAddress: String!, completionHandler:(macAddressItem: MACAddressItem?) -> ()) { Downloader.downloadJSON(macAddress) { (parsedJSON) in println(parsedJSON) let item = MACAddressItem(macAddress: macAddress) item?.company = parsedJSON[0]["company"].stringValue item?.address1 = parsedJSON[0]["addressL1"].stringValue item?.address2 = parsedJSON[0]["addressL2"].stringValue item?.country = parsedJSON[0]["country"].stringValue self._privateItems.append(item!) completionHandler(macAddressItem: item) } } func removeItem(macAddressItem: MACAddressItem!) { for (index, element) in enumerate(_privateItems) { if element === macAddressItem { _privateItems.removeAtIndex(index) } } } func removeItemAt(index: Int) { _privateItems.removeAtIndex(index) } func saveChanges() -> Bool { let path = itemArchivedPath return NSKeyedArchiver.archiveRootObject(_privateItems, toFile: path) } // MARK: Internal Helpers // computed property private var itemArchivedPath: String { get { let documentDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentDirectory = documentDirectories[0] as String return documentDirectory.stringByAppendingPathComponent("items.archive") } } // mock data func loadMockData() { var macAddressItem = MACAddressItem(macAddress: "00:11:00:22:33:44:00 - TEST") _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) _privateItems.append(macAddressItem!) } }
mit
465f0cbf4b1eaabcdb900358e5aac7de
29.088889
108
0.703102
4.339744
false
false
false
false
defineifelse/2048-Swift
2048-Swift/2048-Swift/GameModel.swift
1
10435
// // GameModel.swift // 2048-Swift // // Created by Pan on 02/09/2017. // Copyright © 2017 Yo. All rights reserved. // import Foundation protocol GameProtocol : class { func scoreDidChange(game: GameModel, score: Int) func tilesDidChange(game: GameModel, actions: [TileAction]) func gameDidGetNumber(game: GameModel, number: Int) func gameDidOver(game: GameModel) } class GameModel: NSObject { private let dimension: Int private let gameType: GameType private let difficulty: Difficulty private var tiles: [[TileObject]] unowned let delegate : GameProtocol private var maxNumber: Int = 0 { didSet { delegate.gameDidGetNumber(game: self, number: maxNumber) } } private var score : Int = 0 { didSet { delegate.scoreDidChange(game: self, score: score) } } init(gameType gt:GameType, dimension ds: Int, difficulty dif: Difficulty, delegate dg: GameProtocol) { gameType = gt dimension = ds difficulty = dif delegate = dg score = 0 tiles = [[TileObject]]() for _ in 0..<dimension { var rows = [TileObject]() for _ in 0..<dimension { let initialValue = TileObject() rows.append(initialValue) } tiles.append(rows) } } func start() { let inserts = [insertTileRandom()!, insertTileRandom()!] delegate.tilesDidChange(game: self, actions: inserts) } func reset() { self.score = 0 for i in 0..<dimension { for j in 0..<dimension { let tile = tiles[i][j] tile.value = 0; tile.state = .empty } } } func isGameover() -> Bool { if getEmptyPositions() != nil { return false } let directions: [MoveDirection] = [.left, .right, .up, .down] for d in directions { if isMoveAvailable(direction: d) { return false } } return true } private func isMoveAvailable(direction: MoveDirection) -> Bool { let newTiles = transposeTilesForLeftMove(direction: direction) var range = dimension - 1 if gameType == .powerOf3 { range = dimension - 2 } for row in newTiles { for i in 0..<range { switch gameType { case .powerOf2: if row[i].value == row[i+1].value { return true } case .powerOf3: if ((row[i].value == row[i+1].value) && (row[i+1].value == row[i+2].value)) { return true } case .fibonacci: if (row[i].value != row[i+1].value) && (min(row[i].value, row[i+1].value)*2 > max(row[i].value, row[i+1].value)) { return true } } } } return false } func insertTileRandom() -> TileAction? { let randomVal = Int(arc4random_uniform(100)) switch gameType { case .powerOf2: return insertTileRandom(value: randomVal < 90 ? 2 : 4) case .powerOf3: return insertTileRandom(value: randomVal < 90 ? 3 : 9) case .fibonacci: return insertTileRandom(value: randomVal < 40 ? 2 : 3) } } private func insertTileRandom(value v: Int) -> TileAction? { if let emptyPositions = getEmptyPositions() { let randomIdx = arc4random_uniform(UInt32(emptyPositions.count-1)) let pos = emptyPositions[Int(randomIdx)] let tile = tiles[pos.row][pos.col] tile.value = v; tile.state = .single(pos) return .insert(at: pos, value: v) } return nil } private func getEmptyPositions() -> [Position]? { var emptyPositions: [Position] = [] for i in 0..<dimension { for j in 0..<dimension { if (tiles[i][j].value == 0) { emptyPositions.append(Position(row: i, col: j)) } } } return emptyPositions.isEmpty ? nil : emptyPositions } func moveTiles(direction: MoveDirection) { //transpose matrix if(direction != .left ) { tiles = transposeTilesForLeftMove(direction: direction) } //move left, merge every row for i in 0..<dimension { tiles[i] = mergeRowsLeft(row: tiles[i]) } //restore matrix if(direction == .up ) { tiles = transposeTilesForLeftMove(direction: .down) }else if(direction == .down) { tiles = transposeTilesForLeftMove(direction: .up) }else if(direction == .right) { tiles = transposeTilesForLeftMove(direction: .right) } var maxValue = 0 var actionScore = 0 var actions = [TileAction]() for i in 0..<dimension { for j in 0..<dimension { let here = Position(row: i, col: j) let tile = tiles[i][j] if (tile.value == 0) { continue } switch tile.state { case let .single(pos): actions.append(.move(from: pos, to: here, dismissed: false)) if(pos != here) { actionScore += 1 } case let .combined2(pos1, pos2): actions.append(.move(from: pos1, to: here, dismissed: true)) actions.append(.move(from: pos2, to: here, dismissed: true)) actions.append(.merge(at: here, value: tile.value)) actionScore += tile.value case let .combined3(pos1, pos2, pos3): actions.append(.move(from: pos1, to: here, dismissed: true)) actions.append(.move(from: pos2, to: here, dismissed: true)) actions.append(.move(from: pos3, to: here, dismissed: true)) actions.append(.merge(at: here, value: tile.value)) actionScore += tile.value default: break } tile.state = .single(here) //update tile state maxValue = max(maxValue, tile.value) } } if actionScore > 0 { score += actionScore if let insert = insertTileRandom() { actions.append(insert) } if (difficulty == .normal || difficulty == .hard) { if let insert = insertTileRandom() { actions.append(insert) } } if difficulty == .hard { if let insert = insertTileRandom() { actions.append(insert) } } delegate.tilesDidChange(game: self, actions: actions) } if maxValue > maxNumber { maxNumber = maxValue } if isGameover() { delegate.gameDidOver(game: self) } } private func mergeRowsLeft(row: [TileObject]) -> [TileObject] { //remove empty tile var newRow = row.filter{ $0.value > 0 } //move left and merge var index = 0 var range = newRow.count - 1 if gameType == .powerOf3 { range = newRow.count - 2 } while(index < range) { switch gameType { case .powerOf2: let tile = newRow[index]; let nextTile = newRow[index+1] if case let .single(pos1) = tile.state, case let .single(pos2) = nextTile.state, tile.value == nextTile.value { tile.value += nextTile.value; tile.state = .combined2(pos1, pos2) nextTile.value = 0; nextTile.state = .empty index += 2 }else { index += 1 } case .powerOf3: let tile1 = newRow[index]; let tile2 = newRow[index+1]; let tile3 = newRow[index+2] if case let .single(pos1) = tile1.state, case let .single(pos2) = tile2.state, case let .single(pos3) = tile3.state, (tile1.value == tile2.value) && (tile2.value == tile3.value) { tile1.value += tile2.value + tile3.value; tile1.state = .combined3(pos1, pos2, pos3) tile2.value = 0; tile2.state = .empty; tile3.value = 0; tile3.state = .empty index += 3 }else { index += 1 } case .fibonacci: let tile = newRow[index]; let nextTile = newRow[index+1] if case let .single(pos1) = tile.state, case let .single(pos2) = nextTile.state, tile.value != nextTile.value, min(tile.value, nextTile.value)*2 > max(tile.value, nextTile.value) { tile.value += nextTile.value; tile.state = .combined2(pos1, pos2) nextTile.value = 0; nextTile.state = .empty index += 2 }else { index += 1 } } } newRow = newRow.filter{ $0.value > 0 } //add empty tile let emptyCount = dimension - newRow.count for _ in 0..<emptyCount { newRow.append(TileObject()) } return newRow } // transpose matrix private func transposeTilesForLeftMove(direction: MoveDirection) -> [[TileObject]] { var newTiles = [[TileObject]]() switch direction { case .left: return tiles case .right: //turn it by 180 degrees, move right -> move left for i in 0..<dimension { newTiles.append(tiles[i].reversed()) } case .up: //turn it by 90 degrees in a counterclockwise direction, move up -> move left for i in 0..<dimension { var rows = [TileObject]() for j in 0..<dimension { rows.append(tiles[j][dimension-1-i]) } newTiles.append(rows) } case .down: //turn it by 90 degrees in a clockwise direction, move down -> move left for i in 0..<dimension { var rows = [TileObject]() for j in 0..<dimension { rows.append(tiles[dimension-1-j][i]) } newTiles.append(rows) } } return newTiles } }
mit
27af75e5fa2458b829729ff36518a0f9
35.610526
196
0.512938
4.331258
false
false
false
false
huonw/swift
test/IRGen/closure.swift
2
3348
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast ({ i32, i32, i32, i32 }* @"\01l__swift5_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$S7closure1a1iS2icSi_tFS2icfU_"(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$S7closure1a1iS2icSi_tFS2icfU_TA"(i64, %swift.refcounted* swiftself) // CHECK: } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$S7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$S7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_TA"(i64, %swift.refcounted* swiftself) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: [[RES:%.*]] = tail call swiftcc i64 @"$S7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @"$S7closure14captures_tuple1xx_q_tycx_q_t_tr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getTupleTypeMetadata2(i64 0, %swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call swiftcc { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
f3363ade3e1380461d1728f48bb61353
57.736842
242
0.63859
3.149577
false
false
false
false
SmallPlanetSwift/AEXML
AEXMLExample/ViewController.swift
2
6590
// // ViewController.swift // AEXMLExample // // Created by Marko Tadic on 10/16/14. // Copyright (c) 2014 ae. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // example from README.md if let xmlPath = NSBundle.mainBundle().pathForResource("example", ofType: "xml") { if let data = NSData(contentsOfFile: xmlPath) { // works only if data is successfully parsed // otherwise prints information about error with parsing var error: NSError? if let xmlDoc = AEXMLDocument(xmlData: data, error: &error) { // prints the same XML structure as original println(xmlDoc.xmlString) // prints cats, dogs for child in xmlDoc.root.children { println(child.name) } // prints Optional("Tinna") (first element) println(xmlDoc.root["cats"]["cat"].value) // prints Tinna (first element) println(xmlDoc.root["cats"]["cat"].stringValue) // prints Optional("Kika") (last element) println(xmlDoc.root["dogs"]["dog"].last?.value) // prints Betty (3rd element) println(xmlDoc.root["dogs"].children[2].stringValue) // prints Tinna, Rose, Caesar if let cats = xmlDoc.root["cats"]["cat"].all { for cat in cats { if let name = cat.value { println(name) } } } // prints Villy, Spot for dog in xmlDoc.root["dogs"]["dog"].all! { if let color = dog.attributes["color"] as? String { if color == "white" { println(dog.stringValue) } } } // prints Caesar if let cats = xmlDoc.root["cats"]["cat"].allWithAttributes(["breed" : "Domestic", "color" : "yellow"]) { for cat in cats { println(cat.stringValue) } } // prints 4 println(xmlDoc.root["cats"]["cat"].count) // prints 2 println(xmlDoc.root["dogs"]["dog"].countWithAttributes(["breed" : "Bull Terrier"])) // prints 1 println(xmlDoc.root["cats"]["cat"].countWithAttributes(["breed" : "Domestic", "color" : "darkgray"])) // prints Siberian println(xmlDoc.root["cats"]["cat"].attributes["breed"]!) // prints <cat breed="Siberian" color="lightgray">Tinna</cat> println(xmlDoc.root["cats"]["cat"].xmlStringCompact) // prints element <badexample> not found println(xmlDoc["badexample"]["notexisting"].stringValue) } else { println("description: \(error?.localizedDescription)\ninfo: \(error?.userInfo)") } } } } @IBAction func readXML(sender: UIBarButtonItem) { resetTextField() if let xmlPath = NSBundle.mainBundle().pathForResource("plant_catalog", ofType: "xml") { if let data = NSData(contentsOfFile: xmlPath) { var error: NSError? if let doc = AEXMLDocument(xmlData: data, error: &error) { var parsedText = String() // parse known structure for plant in doc["CATALOG"]["PLANT"].all! { parsedText += plant["COMMON"].stringValue + "\n" } textView.text = parsedText } else { let err = "description: \(error?.localizedDescription)\ninfo: \(error?.userInfo)" textView.text = err } } } } @IBAction func writeXML(sender: UIBarButtonItem) { resetTextField() // sample SOAP request let soapRequest = AEXMLDocument() let attributes = ["xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd" : "http://www.w3.org/2001/XMLSchema"] let envelope = soapRequest.addChild(name: "soap:Envelope", attributes: attributes) let header = envelope.addChild(name: "soap:Header") let body = envelope.addChild(name: "soap:Body") header.addChild(name: "m:Trans", value: "234", attributes: ["xmlns:m" : "http://www.w3schools.com/transaction/", "soap:mustUnderstand" : "1"]) let getStockPrice = body.addChild(name: "m:GetStockPrice") getStockPrice.addChild(name: "m:StockName", value: "AAPL") textView.text = soapRequest.xmlString } func resetTextField() { textField.resignFirstResponder() textField.text = "http://www.w3schools.com/xml/cd_catalog.xml" } @IBAction func tryRemoteXML(sender: UIButton) { if let url = NSURL(string: textField.text) { if let data = NSData(contentsOfURL: url) { var error: NSError? if let doc = AEXMLDocument(xmlData: data, error: &error) { var parsedText = String() // parse unknown structure for child in doc.root.children { parsedText += child.xmlString + "\n" } textView.text = parsedText } else { let err = "description: \(error?.localizedDescription)\ninfo: \(error?.userInfo)" textView.text = err } } } textField.resignFirstResponder() } }
mit
c681426ae78dddb43f30833a28ad2479
40.1875
150
0.464188
5.370823
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/Charts/LineLoadingView.swift
1
2797
// // LineLoadingView.swift // breadwallet // // Created by Adrian Corscadden on 2019-07-08. // Copyright © 2019 breadwallet LLC. All rights reserved. // import UIKit enum LineLoadingViewStyle { case chart case sync var color: UIColor { switch self { case .chart: return UIColor.white case .sync: return Theme.accent } } } class LineLoadingView: UIView { private var hasPerformedLayout = false private var lineLayer = CAShapeLayer() private let animationDuration: TimeInterval = 2.0 private let animationDurationOffset: TimeInterval = 1.2 private let colour: UIColor init(style: LineLoadingViewStyle) { self.colour = style.color super.init(frame: .zero) } override func layoutSubviews() { guard !hasPerformedLayout else { hasPerformedLayout = true; return } let path = UIBezierPath() path.move(to: CGPoint(x: 0.0, y: bounds.midY)) path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.midY)) lineLayer.path = path.cgPath lineLayer.strokeColor = colour.cgColor lineLayer.lineWidth = 1.0 lineLayer.strokeEnd = 1.0 layer.addSublayer(lineLayer) animate() } private func animate() { lineLayer.strokeEnd = 1.0 lineLayer.add(strokeEndAnimation(), forKey: "strokeEnd") lineLayer.add(strokeStartAnimation(), forKey: "strokeStart") } private func strokeEndAnimation() -> CAAnimation { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0 animation.toValue = 1 animation.duration = animationDuration animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let group = CAAnimationGroup() group.duration = animationDuration + animationDurationOffset group.repeatCount = MAXFLOAT group.animations = [animation] return group } private func strokeStartAnimation() -> CAAnimation { let animation = CABasicAnimation(keyPath: "strokeStart") animation.beginTime = animationDurationOffset animation.fromValue = 0 animation.toValue = 1 animation.duration = animationDuration animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let group = CAAnimationGroup() group.duration = animationDuration + animationDurationOffset group.repeatCount = MAXFLOAT group.animations = [animation] return group } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
cc3deff9bef4f9887c4d27077f37cab3
29.725275
103
0.646996
5.245779
false
false
false
false
goblinr/omim
iphone/Maps/UI/Ads/AdBanner.swift
1
10663
import AlamofireImage import FBAudienceNetwork @objc(MWMAdBannerState) enum AdBannerState: Int { case unset case compact case detailed case search func config() -> (priority: UILayoutPriority, numberOfTitleLines: Int, numberOfBodyLines: Int) { switch self { case .unset: assert(false) return (priority: UILayoutPriority(rawValue: 0), numberOfTitleLines: 0, numberOfBodyLines: 0) case .compact: return alternative(iPhone: (priority: UILayoutPriority.defaultLow, numberOfTitleLines: 1, numberOfBodyLines: 2), iPad: (priority: UILayoutPriority.defaultHigh, numberOfTitleLines: 0, numberOfBodyLines: 0)) case .search: return (priority: UILayoutPriority.defaultLow, numberOfTitleLines: 2, numberOfBodyLines: 0) case .detailed: return (priority: UILayoutPriority.defaultHigh, numberOfTitleLines: 0, numberOfBodyLines: 0) } } } @objc(MWMAdBannerContainerType) enum AdBannerContainerType: Int { case placePage case search } @objc(MWMAdBanner) final class AdBanner: UITableViewCell { @IBOutlet private var detailedModeConstraints: [NSLayoutConstraint]! @IBOutlet private weak var adCallToActionButtonCompactLeading: NSLayoutConstraint! @IBOutlet private weak var adIconImageView: UIImageView! @IBOutlet private weak var adTitleLabel: UILabel! @IBOutlet private weak var adBodyLabel: UILabel! @IBOutlet private weak var adCallToActionButtonCompact: UIButton! @IBOutlet private weak var adCallToActionButtonDetailed: UIButton! @IBOutlet private weak var adCallToActionButtonCustom: UIButton! @IBOutlet private weak var adPrivacyButton: UIButton! @IBOutlet private weak var nativeAdView: UIView! @IBOutlet private weak var fallbackAdView: UIView! @IBOutlet private var nativeAdViewBottom: NSLayoutConstraint! @IBOutlet private var fallbackAdViewBottom: NSLayoutConstraint! @IBOutlet private var fallbackAdViewHeight: NSLayoutConstraint! @objc static let detailedBannerExcessHeight: Float = 36 enum AdType { case native case fallback } var adType = AdType.native { didSet { let isNative = adType == .native nativeAdView.isHidden = !isNative fallbackAdView.isHidden = isNative nativeAdViewBottom.isActive = isNative fallbackAdViewBottom.isActive = !isNative fallbackAdViewHeight.isActive = !isNative } } @objc var state = AdBannerState.unset { didSet { guard state != .unset else { adPrivacyButton.isHidden = true adCallToActionButtonCustom.isHidden = true mpNativeAd = nil nativeAd = nil return } guard state != oldValue else { return } let config = state.config() animateConstraints(animations: { self.adTitleLabel.numberOfLines = config.numberOfTitleLines self.adBodyLabel.numberOfLines = config.numberOfBodyLines self.detailedModeConstraints.forEach { $0.priority = config.priority } self.refreshBannerIfNeeded() }) } } @objc weak var mpNativeAd: MPNativeAd? override func prepareForReuse() { adIconImageView.af_cancelImageRequest() } private var nativeAd: Banner? { willSet { nativeAd?.unregister() } } @IBAction private func privacyAction() { if let ad = nativeAd as? MopubBanner, let urlStr = ad.privacyInfoURL, let url = URL(string: urlStr) { UIViewController.topViewController().open(url) } } override func layoutSubviews() { super.layoutSubviews() switch nativeAd { case let ad as GoogleFallbackBanner: updateFallbackBannerLayout(ad: ad) default: break } } func reset() { state = .unset } @objc func config(ad: MWMBanner, containerType: AdBannerContainerType) { reset() switch containerType { case .placePage: state = alternative(iPhone: .compact, iPad: .detailed) case .search: state = .search } nativeAd = ad as? Banner switch ad { case let ad as FacebookBanner: configFBBanner(ad: ad.nativeAd) case let ad as RBBanner: configRBBanner(ad: ad) case let ad as MopubBanner: configMopubBanner(ad: ad) case let ad as GoogleFallbackBanner: configGoogleFallbackBanner(ad: ad) case let ad as GoogleNativeBanner: configGoogleNativeBanner(ad: ad) default: assert(false) } backgroundColor = UIColor.bannerBackground() } @objc func highlightButton() { adCallToActionButtonDetailed.setBackgroundImage(nil, for: .normal) adCallToActionButtonCompact.setBackgroundImage(nil, for: .normal) adCallToActionButtonDetailed.backgroundColor = UIColor.bannerButtonBackground() adCallToActionButtonCompact.backgroundColor = UIColor.bannerBackground() let duration = 0.5 * kDefaultAnimationDuration let darkerPercent: CGFloat = 0.2 UIView.animate(withDuration: duration, animations: { self.adCallToActionButtonDetailed.backgroundColor = UIColor.bannerButtonBackground().darker(percent: darkerPercent) self.adCallToActionButtonCompact.backgroundColor = UIColor.bannerBackground().darker(percent: darkerPercent) }, completion: { _ in UIView.animate(withDuration: duration, animations: { self.adCallToActionButtonDetailed.backgroundColor = UIColor.bannerButtonBackground() self.adCallToActionButtonCompact.backgroundColor = UIColor.bannerBackground() }, completion: { _ in self.adCallToActionButtonDetailed.setBackgroundColor(UIColor.bannerButtonBackground(), for: .normal) self.adCallToActionButtonCompact.setBackgroundColor(UIColor.bannerBackground(), for: .normal) }) }) } private func configFBBanner(ad: FBNativeAd) { adType = .native let adCallToActionButtons: [UIView] if state == .search { adCallToActionButtons = [self, adCallToActionButtonCompact] } else { adCallToActionButtons = [adCallToActionButtonCompact, adCallToActionButtonDetailed] } ad.registerView(forInteraction: self, with: nil, withClickableViews: adCallToActionButtons) ad.icon?.loadAsync { [weak self] image in self?.adIconImageView.image = image } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.firstLineHeadIndent = 24 paragraphStyle.lineBreakMode = .byTruncatingTail let adTitle = NSAttributedString(string: ad.title ?? "", attributes: [ NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.font: UIFont.bold12(), NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText(), ]) adTitleLabel.attributedText = adTitle adBodyLabel.text = ad.body ?? "" let config = state.config() adTitleLabel.numberOfLines = config.numberOfTitleLines adBodyLabel.numberOfLines = config.numberOfBodyLines [adCallToActionButtonCompact, adCallToActionButtonDetailed].forEach { $0.setTitle(ad.callToAction, for: .normal) } } private func configRBBanner(ad: MTRGNativeAd) { guard let banner = ad.banner else { return } adType = .native MTRGNativeAd.loadImage(banner.icon, to: adIconImageView) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.firstLineHeadIndent = 24 paragraphStyle.lineBreakMode = .byTruncatingTail let adTitle = NSAttributedString(string: banner.title ?? "", attributes: [ NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.font: UIFont.bold12(), NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText(), ]) adTitleLabel.attributedText = adTitle adBodyLabel.text = banner.descriptionText ?? "" let config = state.config() adTitleLabel.numberOfLines = config.numberOfTitleLines adBodyLabel.numberOfLines = config.numberOfBodyLines [adCallToActionButtonCompact, adCallToActionButtonDetailed].forEach { $0.setTitle(banner.ctaText, for: .normal) } refreshBannerIfNeeded() } private func configMopubBanner(ad: MopubBanner) { mpNativeAd = ad.nativeAd adType = .native let adCallToActionButtons: [UIButton] if state == .search { adCallToActionButtonCustom.isHidden = false adCallToActionButtons = [adCallToActionButtonCustom, adCallToActionButtonCompact] } else { adCallToActionButtons = [adCallToActionButtonCompact, adCallToActionButtonDetailed] adCallToActionButtons.forEach { $0.setTitle(ad.ctaText, for: .normal) } } mpNativeAd?.setAdView(self, actionButtons: adCallToActionButtons) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.firstLineHeadIndent = 24 paragraphStyle.lineBreakMode = .byTruncatingTail let adTitle = NSAttributedString(string: ad.title, attributes: [ NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.font: UIFont.bold12(), NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText(), ]) adTitleLabel.attributedText = adTitle adBodyLabel.text = ad.text if let url = URL(string: ad.iconURL) { adIconImageView.af_setImage(withURL: url) } adPrivacyButton.isHidden = ad.privacyInfoURL == nil } private func configGoogleFallbackBanner(ad: GoogleFallbackBanner) { adType = .fallback fallbackAdView.subviews.forEach { $0.removeFromSuperview() } fallbackAdView.addSubview(ad) updateFallbackBannerLayout(ad: ad) } private func updateFallbackBannerLayout(ad: GoogleFallbackBanner) { ad.width = fallbackAdView.width fallbackAdViewHeight.constant = ad.dynamicSize.height } private func configGoogleNativeBanner(ad _: GoogleNativeBanner) { } private func refreshBannerIfNeeded() { if let ad = nativeAd as? MTRGNativeAd { let clickableView: UIView switch state { case .unset: assert(false) clickableView = adCallToActionButtonCompact case .compact: clickableView = adCallToActionButtonCompact case .detailed: clickableView = adCallToActionButtonDetailed case .search: clickableView = self } ad.register(clickableView, with: UIViewController.topViewController()) } } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) mpNativeAd?.nativeViewWillMove(toSuperview: newSuperview) } }
apache-2.0
9f6545d2858d30c5e983785600284dc5
36.678445
121
0.707212
4.889042
false
true
false
false
mbalex99/FirebaseRxSwiftExtensions
Pod/Classes/Methods_REMOTE_77266.swift
1
11409
import Firebase import RxSwift //Authentication Extension Methods public extension FQuery { /** - Returns: An `Observable<FAuthData?>`, `FAuthData?` will be nil if the user is logged out. */ var rx_authObservable :Observable<FAuthData?> { get { return Observable.create({ (observer: AnyObserver<FAuthData?>) -> Disposable in let ref = self.ref; let listener = ref.observeAuthEventWithBlock({ (authData: FAuthData?) -> Void in observer.on(.Next(authData)) }) return AnonymousDisposable { self.ref.removeAuthEventObserverWithHandle(listener) } }) } } func rx_authUser(email: String, password: String) -> Observable<FAuthData> { let query = self; return Observable.create({ (observer: AnyObserver<FAuthData>) -> Disposable in query.ref.authUser(email, password: password, withCompletionBlock: { (error, authData) -> Void in if let error = error { observer.on(.Error(error)) }else{ observer.on(.Next(authData)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_authAnonymously() -> Observable<FAuthData> { let query = self; return Observable.create({ (observer: AnyObserver<FAuthData>) -> Disposable in query.ref.authAnonymouslyWithCompletionBlock({ (error, authData) -> Void in if let error = error { observer.on(.Error(error)) }else{ observer.on(.Next(authData)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_authWithOAuthProvider(provider: String, parameters: [NSObject: AnyObject]) -> Observable<FAuthData> { let query = self; return Observable.create({ (observer: AnyObserver<FAuthData>) -> Disposable in query.ref.authWithOAuthProvider(provider, parameters: parameters, withCompletionBlock: { (error, authData) -> Void in if let error = error { observer.on(.Error(error)) }else{ observer.on(.Next(authData)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_authWithOAuthProvider(provider: String, token: String) -> Observable<FAuthData> { let query = self; return Observable.create({ (observer: AnyObserver<FAuthData>) -> Disposable in query.ref.authWithOAuthProvider(provider, token: token, withCompletionBlock: { (error, authData) -> Void in if let error = error { observer.on(.Error(error)) }else{ observer.on(.Next(authData)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_authWithCustomToken(customToken: String) -> Observable<FAuthData> { let query = self; return Observable.create({ (observer: AnyObserver<FAuthData>) -> Disposable in query.ref.authWithCustomToken(customToken, withCompletionBlock: { (error, authData) -> Void in if let error = error { observer.on(.Error(error)) }else{ observer.on(.Next(authData)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_createUser(email: String, password: String) -> Observable<[NSObject : AnyObject]> { let query = self return Observable.create({ (observer: AnyObserver<[NSObject : AnyObject]>) -> Disposable in query.ref.createUser(email, password: password) { (error, userData) in if let error = error { observer.on(.Error(error)) } else { observer.on(.Next(userData)) observer.on(.Completed) } } return NopDisposable.instance }) } func rx_removeUser(email: String, password: String) -> Observable<Void> { let query = self return Observable.create({ (observer: AnyObserver<Void>) -> Disposable in query.ref.removeUser(email, password: password) { error in if let error = error { observer.on(.Error(error)) } else { observer.on(.Completed) } } return NopDisposable.instance }) } func rx_resetPasswordForUser(email: String) -> Observable<Void> { let query = self return Observable.create({ (observer: AnyObserver<Void>) -> Disposable in query.ref.resetPasswordForUser(email) { error in if let error = error { observer.on(.Error(error)) } else { observer.onCompleted() } } return NopDisposable.instance }) } func rx_changeEmailForUser(email: String, password: String, toNewEmail: String) -> Observable<Void> { let query = self return Observable.create({ (observer: AnyObserver<Void>) -> Disposable in query.ref.changeEmailForUser(email, password: password, toNewEmail: toNewEmail) { error in if let error = error { observer.on(.Error(error)) } else { observer.on(.Completed) } } return NopDisposable.instance }) } func rx_changePasswordForUser(email: String, fromOld: String, toNew: String) -> Observable<Void> { let query = self return Observable.create({ (observer: AnyObserver<Void>) -> Disposable in query.ref.changePasswordForUser(email, fromOld: fromOld, toNew: toNew) { error in if let error = error { observer.on(.Error(error)) } else { observer.on(.Completed) } } return NopDisposable.instance }) } func rx_observe(eventType: FEventType) -> Observable<FDataSnapshot> { let ref = self; return Observable.create({ (observer : AnyObserver<FDataSnapshot>) -> Disposable in let listener = ref.observeEventType(eventType, withBlock: { (snapshot) -> Void in observer.on(.Next(snapshot)) }, withCancelBlock: { (error) -> Void in observer.on(.Error(error)) }) return AnonymousDisposable{ ref.removeObserverWithHandle(listener) } }) } /** - Returns: A tuple `Observable<(FDataSnapshot, String)>` with the first value as the snapshot and the second value as the sibling key */ func rx_observeWithSiblingKey(eventType: FEventType) -> Observable<(FDataSnapshot, String?)> { let ref = self; return Observable.create({ (observer : AnyObserver<(FDataSnapshot, String?)>) -> Disposable in let listener = ref.observeEventType(eventType, andPreviousSiblingKeyWithBlock: { (snapshot, siblingKey) -> Void in let tuple : (FDataSnapshot, String?) = (snapshot, siblingKey) observer.on(.Next(tuple)) }, withCancelBlock: { (error) -> Void in observer.on(.Error(error)) }) return AnonymousDisposable{ ref.removeObserverWithHandle(listener) } }) } /** - Returns: The firebase reference where the update occured */ func rx_updateChildValues(values: [NSObject: AnyObject!]) -> Observable<Firebase> { let query = self return Observable.create({ (observer: AnyObserver<Firebase>) -> Disposable in query.ref.updateChildValues(values, withCompletionBlock: { (error, firebase) -> Void in if let error = error { observer.on(.Error(error)) } else{ observer.on(.Next(firebase)) observer.on(.Completed) } }) return AnonymousDisposable{} }) } func rx_setValue(value: AnyObject!, priority: AnyObject? = nil) -> Observable<Firebase> { let query = self return Observable.create({ (observer: AnyObserver<Firebase>) -> Disposable in if let priority = priority { query.ref.setValue(value, andPriority: priority, withCompletionBlock: { (error, firebase) -> Void in if let error = error { observer.on(.Error(error)) } else{ observer.on(.Next(firebase)) observer.on(.Completed) } }) }else { query.ref.setValue(value, withCompletionBlock: { (error, firebase) -> Void in if let error = error { observer.on(.Error(error)) } else{ observer.on(.Next(firebase)) observer.on(.Completed) } }) } return AnonymousDisposable{} }) } func rx_removeValue() -> Observable<Firebase> { let query = self return Observable.create({ (observer: AnyObserver<Firebase>) -> Disposable in query.ref.removeValueWithCompletionBlock({ (err, ref) -> Void in if let err = err { observer.onError(err) }else if let ref = ref { observer.onNext(ref) observer.onCompleted() } }) return AnonymousDisposable{} }) } func rx_runTransactionBlock(block: ((FMutableData!) -> FTransactionResult!)!) -> Observable<(isCommitted: Bool, snapshot : FDataSnapshot)> { let query = self return Observable.create({ (observer) -> Disposable in query.ref.runTransactionBlock(block) { (err, isCommitted, snapshot) -> Void in if let err = err { observer.onError(err) } else if let snapshot = snapshot { observer.onNext((isCommitted: isCommitted, snapshot: snapshot)) observer.onCompleted() } } return AnonymousDisposable {} }) } } public extension ObservableType where E : FDataSnapshot { func rx_filterWhenNSNull() -> Observable<E> { return self.filter { (snapshot) -> Bool in return snapshot.value is NSNull } } func rx_filterWhenNotNSNull() -> Observable<E> { return self.filter { (snapshot) -> Bool in return !(snapshot.value is NSNull) } } }
mit
b1b6f0bdc8a3c2e06070455753d6c94a
36.778146
144
0.524849
5.252762
false
false
false
false
kaojohnny/CoreStore
Sources/Internal/FetchedResultsControllerDelegate.swift
1
8011
// // FetchedResultsControllerDelegate.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData #if os(iOS) || os(watchOS) || os(tvOS) // MARK: - FetchedResultsControllerHandler internal protocol FetchedResultsControllerHandler: class { func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) func controllerWillChangeContent(controller: NSFetchedResultsController) func controllerDidChangeContent(controller: NSFetchedResultsController) func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? } // MARK: - FetchedResultsControllerDelegate internal final class FetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate { // MARK: Internal @nonobjc internal var enabled = true @nonobjc internal weak var handler: FetchedResultsControllerHandler? @nonobjc internal weak var fetchedResultsController: NSFetchedResultsController? { didSet { oldValue?.delegate = nil self.fetchedResultsController?.delegate = self } } deinit { self.fetchedResultsController?.delegate = nil } // MARK: NSFetchedResultsControllerDelegate @objc dynamic func controllerWillChangeContent(controller: NSFetchedResultsController) { guard self.enabled else { return } self.deletedSections = [] self.insertedSections = [] self.handler?.controllerWillChangeContent(controller) } @objc dynamic func controllerDidChangeContent(controller: NSFetchedResultsController) { guard self.enabled else { return } self.handler?.controllerDidChangeContent(controller) } @objc dynamic func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { guard self.enabled else { return } guard let actualType = NSFetchedResultsChangeType(rawValue: type.rawValue) else { // This fix is for a bug where iOS passes 0 for NSFetchedResultsChangeType, but this is not a valid enum case. // Swift will then always execute the first case of the switch causing strange behaviour. // https://forums.developer.apple.com/thread/12184#31850 return } // This whole dance is a workaround for a nasty bug introduced in XCode 7 targeted at iOS 8 devices // http://stackoverflow.com/questions/31383760/ios-9-attempt-to-delete-and-reload-the-same-index-path/31384014#31384014 // https://forums.developer.apple.com/message/9998#9998 // https://forums.developer.apple.com/message/31849#31849 switch actualType { case .Update: guard let section = indexPath?.indexAtPosition(0) else { return } if self.deletedSections.contains(section) || self.insertedSections.contains(section) { return } case .Move: guard let indexPath = indexPath, let newIndexPath = newIndexPath else { return } guard indexPath == newIndexPath else { break } if self.insertedSections.contains(indexPath.indexAtPosition(0)) { // Observers that handle the .Move change are advised to delete then reinsert the object instead of just moving. This is especially true when indexPath and newIndexPath are equal. For example, calling tableView.moveRowAtIndexPath(_:toIndexPath) when both indexPaths are the same will crash the tableView. self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: .Move, newIndexPath: newIndexPath ) return } if self.deletedSections.contains(indexPath.indexAtPosition(0)) { self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: nil, forChangeType: .Insert, newIndexPath: indexPath ) return } self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: .Update, newIndexPath: nil ) return default: break } self.handler?.controller( controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: actualType, newIndexPath: newIndexPath ) } @objc dynamic func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { guard self.enabled else { return } switch type { case .Delete: self.deletedSections.insert(sectionIndex) case .Insert: self.insertedSections.insert(sectionIndex) default: break } self.handler?.controller( controller, didChangeSection: sectionInfo, atIndex: sectionIndex, forChangeType: type ) } @objc dynamic func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String) -> String? { return self.handler?.controller( controller, sectionIndexTitleForSectionName: sectionName ) } // MARK: Private @nonobjc private var deletedSections = Set<Int>() @nonobjc private var insertedSections = Set<Int>() } #endif
mit
e4a4e02621c67b89378c0392b567bf81
33.377682
320
0.621223
6.114504
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/Pivotal/Domain/PivotalComment.swift
1
4177
// // PivotalComment.swift // bugTrap // // Created by Colby L Williams on 11/10/14. // Copyright (c) 2014 bugTrap. All rights reserved. // import Foundation class PivotalComment : JsonSerializable { var id: Int? var storyId: Int? var epicId: Int? var text = "" var personId = 0 var createdAt: NSDate? var updatedAt: NSDate? var fileAttachmentIds = [Int]() var fileAttachments: [PivotalAttachment] = [PivotalAttachment]() { willSet { fileAttachmentIds = newValue.filter({$0.id != nil}).map({$0.id!}) } } var googleAttachmentIds = [Int]() var commitIdentifier = "" var commitType = "" var kind = "" init() { } init(storyId: Int?) { self.storyId = storyId } init(id: Int?, storyId: Int?, epicId: Int?, text: String, personId: Int, fileAttachmentIds: [Int], googleAttachmentIds: [Int], commitIdentifier: String, commitType: String, kind: String) { self.id = id self.storyId = storyId self.epicId = epicId self.text = text self.personId = personId // self.createdAt = createdAt // self.updatedAt = updatedAt self.fileAttachmentIds = fileAttachmentIds self.googleAttachmentIds = googleAttachmentIds self.commitIdentifier = commitIdentifier self.commitType = commitType self.kind = kind } class func deserialize (json: JSON) -> PivotalComment? { var storyId: Int? var epicId: Int? // var createdAt: NSDate? // var updatedAt: NSDate? if let id = json["id"].int { if let storyIdW = json["story_id"].int { storyId = storyIdW } if let epicIdW = json["epic_id"].int { epicId = epicIdW } let text = json["text"].stringValue let personId = json["person_id"].intValue // if let createdAtW = json["created_at"].nSDate? { // createdAt = createdAtW // } // if let updatedAtW = json["updated_at"].nSDate? { // updatedAt = updatedAtW // } var fileAttachmentIds = [Int]() for item in json["file_attachment_ids"].arrayValue { if let idW = item.int { fileAttachmentIds.append(idW) } } var googleAttachmentIds = [Int]() for item in json["google_attachment_ids"].arrayValue { if let idW = item.int { googleAttachmentIds.append(idW) } } let commitIdentifier = json["commit_identifier"].stringValue let commitType = json["commit_type"].stringValue let kind = json["kind"].stringValue return PivotalComment(id: id, storyId: storyId, epicId: epicId, text: text, personId: personId, fileAttachmentIds: fileAttachmentIds, googleAttachmentIds: googleAttachmentIds, commitIdentifier: commitIdentifier, commitType: commitType, kind: kind) } return nil } class func deserializeAll(json: JSON) -> [PivotalComment] { var items = [PivotalComment]() if let jsonArray = json.array { for item: JSON in jsonArray { if let pivotalComment = deserialize(item) { items.append(pivotalComment) } } } return items } func serialize () -> NSMutableDictionary { let dict = NSMutableDictionary() // dict.setValue(id == nil ? nil : id!, forKey: PivotalFields.NewCommentFields.Id.rawValue) // dict.setValue(storyId == nil ? nil : storyId!, forKey: PivotalFields.NewCommentFields.StoryId.rawValue) // dict.setValue(epicId == nil ? nil : epicId!, forKey: PivotalFields.NewCommentFields.EpicId.rawValue) dict.setObject(text, forKey: PivotalFields.NewCommentFields.Text.rawValue) // dict.setObject(personId, forKey: PivotalFields.NewCommentFields.PersonId.rawValue) // dict.setObject(fileAttachmentIds, forKey: PivotalFields.NewCommentFields.FileAttachmentIds.rawValue) if fileAttachments.count > 0 { let attachmentsJson = fileAttachments.map({$0.serialize()}) dict.setObject(attachmentsJson, forKey: PivotalFields.NewCommentFields.FileAttachments.rawValue) } // dict.setObject(googleAttachmentIds, forKey: PivotalFields.NewCommentFields.GoogleAttachmentIds.rawValue) // dict.setObject(commitIdentifier, forKey: PivotalFields.NewCommentFields.CommitIdentifier.rawValue) // dict.setObject(commitType, forKey: PivotalFields.NewCommentFields.CommitType.rawValue) // dict.setObject(kind, forKey: PivotalFields.NewCommentFields.Kind.rawValue) return dict } }
mit
978e5467320192da0651c38dcc6a576b
24.011976
250
0.707206
3.21555
false
false
false
false
dasdom/UIStackViewPlayground
UIStackView.playground/Pages/Springboard.xcplaygroundpage/Contents.swift
1
5792
//: [Previous](@previous) import UIKit import PlaygroundSupport //: First we need a `hostView` to put the different elements on. let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) hostView.backgroundColor = UIColor.black PlaygroundPage.current.liveView = hostView let timeLabel = UILabel() timeLabel.text = "9:41 AM" timeLabel.textColor = UIColor.white timeLabel.font = UIFont.boldSystemFont(ofSize: 13) timeLabel.textAlignment = .center let calendarImageView = UIImageView(image: UIImage(named: "calendar")) let photosImageView = UIImageView(image: UIImage(named: "photos")) let mapsImageView = UIImageView(image: UIImage(named: "maps")) let remindersImageView = UIImageView(image: UIImage(named: "notes")) let healthImageView = UIImageView(image: UIImage(named: "health")) let settingsImageView = UIImageView(image: UIImage(named: "settings")) let safariImageView = UIImageView(image: UIImage(named: "safari")) let labelWithText = { (text: String) -> UILabel in let label = UILabel() label.text = text label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 12) label.textAlignment = .center return label } let calendarLabel = labelWithText("Calendar") let photosLabel = labelWithText("Photos") let mapsLabel = labelWithText("Maps") let remindersLabel = labelWithText("Reminders") let healthLabel = labelWithText("Health") let settingsLabel = labelWithText("Settings") let safariLabel = labelWithText("Safari") let appStackViewWithArrangedViews = { (views: [UIView]) -> UIStackView in let stackView = UIStackView(arrangedSubviews: views) stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.spacing = 3 return stackView } let calendarStackView = appStackViewWithArrangedViews([calendarImageView, calendarLabel]) let photosStackView = appStackViewWithArrangedViews([photosImageView, photosLabel]) let mapsStackView = appStackViewWithArrangedViews([mapsImageView, mapsLabel]) let remindersStackView = appStackViewWithArrangedViews([remindersImageView, remindersLabel]) let healthStackView = appStackViewWithArrangedViews([healthImageView, healthLabel]) let settingsStackView = appStackViewWithArrangedViews([settingsImageView, settingsLabel]) let safariStackView = appStackViewWithArrangedViews([safariImageView, safariLabel]) let firstColumnStackView = appStackViewWithArrangedViews([calendarStackView, healthStackView]) firstColumnStackView.spacing = 10 let secondColumnStackView = appStackViewWithArrangedViews([photosStackView, settingsStackView]) secondColumnStackView.spacing = 10 let pageControl = UIPageControl() pageControl.numberOfPages = 3 let safariColumnStackView = appStackViewWithArrangedViews([pageControl, safariStackView]) let firstRowStackView = UIStackView(arrangedSubviews: [firstColumnStackView, secondColumnStackView, mapsStackView, remindersStackView]) firstRowStackView.distribution = .equalSpacing firstRowStackView.alignment = .top firstRowStackView.spacing = 15 let topStackView = UIStackView(arrangedSubviews: [timeLabel, firstRowStackView]) topStackView.axis = .vertical topStackView.spacing = 5 //let bottomStackView = UIStackView(arrangedSubviews: [safariStackView]) //bottomStackView.alignment = .Top //bottomStackView.distribution = .EqualSpacing let dockBackgroundView = UIView() dockBackgroundView.translatesAutoresizingMaskIntoConstraints = false dockBackgroundView.backgroundColor = UIColor(white: 0.35, alpha: 1.0) let infoLabel = UILabel() infoLabel.translatesAutoresizingMaskIntoConstraints = false infoLabel.textColor = UIColor.gray infoLabel.text = "Build with UIStackViews" let mainStackView = UIStackView(arrangedSubviews: [topStackView, safariColumnStackView]) mainStackView.translatesAutoresizingMaskIntoConstraints = false mainStackView.axis = .vertical mainStackView.distribution = .equalSpacing mainStackView.alignment = .center hostView.addSubview(dockBackgroundView) hostView.addSubview(mainStackView) hostView.addSubview(infoLabel) NSLayoutConstraint.activate( [ mainStackView.leadingAnchor.constraint(equalTo: hostView.leadingAnchor), mainStackView.trailingAnchor.constraint(equalTo: hostView.trailingAnchor), mainStackView.topAnchor.constraint(equalTo: hostView.topAnchor, constant: 3), mainStackView.bottomAnchor.constraint(equalTo: hostView.bottomAnchor, constant: -3), dockBackgroundView.leadingAnchor.constraint(equalTo: hostView.leadingAnchor), dockBackgroundView.trailingAnchor.constraint(equalTo: hostView.trailingAnchor), dockBackgroundView.bottomAnchor.constraint(equalTo: hostView.bottomAnchor), dockBackgroundView.heightAnchor.constraint(equalToConstant: 95), infoLabel.centerXAnchor.constraint(equalTo: hostView.centerXAnchor), infoLabel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor), calendarImageView.widthAnchor.constraint(equalToConstant: 60), calendarImageView.heightAnchor.constraint(equalToConstant: 60), photosImageView.widthAnchor.constraint(equalToConstant: 60), photosImageView.heightAnchor.constraint(equalToConstant: 60), mapsImageView.widthAnchor.constraint(equalToConstant: 60), mapsImageView.heightAnchor.constraint(equalToConstant: 60), remindersImageView.widthAnchor.constraint(equalToConstant: 60), remindersImageView.heightAnchor.constraint(equalToConstant: 60), healthImageView.widthAnchor.constraint(equalToConstant: 60), healthImageView.heightAnchor.constraint(equalToConstant: 60), settingsImageView.widthAnchor.constraint(equalToConstant: 60), settingsImageView.heightAnchor.constraint(equalToConstant: 60), safariImageView.widthAnchor.constraint(equalToConstant: 60), safariImageView.heightAnchor.constraint(equalToConstant: 60), ]) //: [Next](@next)
mit
8948dc275ee45205981d702d72e50553
43.21374
135
0.80991
4.826667
false
false
false
false
pawrsccouk/Stereogram
Stereogram-iPad/UIImage+Alpha.swift
1
4609
// UIImage+Alpha.h // Created by Trevor Harmon on 9/20/09. // Free for personal or commercial use, with or without modification. // No warranty is expressed or implied. import UIKit // Helper methods for adding an alpha layer to an image extension UIImage { // true if this image has an alpha layer. var hasAlpha: Bool { let alpha = CGImageGetAlphaInfo(self.CGImage) return alpha == .First || alpha == .Last || alpha == .PremultipliedFirst || alpha == .PremultipliedLast } // Returns the given image if it already has an alpha channel // or a copy of the image adding an alpha channel if it doesn't already have one func imageWithAlpha() -> UIImage { if self.hasAlpha { return self } let imageRef = self.CGImage let width = CGImageGetWidth(imageRef), height = CGImageGetHeight(imageRef) // The bitsPerComponent and bitmapInfo values are hard-coded // to prevent an "unsupported parameter combination" error let bitmapInfo = CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue let offscreenContext = CGBitmapContextCreate(nil, width, height, 8, 0 , CGImageGetColorSpace(imageRef), CGBitmapInfo(rawValue: bitmapInfo)) // Draw the image into the context and retrieve the new image, which now has an alpha layer CGContextDrawImage(offscreenContext , CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef) let imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext) return UIImage(CGImage: imageRefWithAlpha)! } /// Returns a copy of the image with a transparent border added around its edges. /// If the image has no alpha layer, one will be added to it. /// /// :param: borderSize Size of the border. func transparentBorderImage(borderSize borderSizeUInt: UInt) -> UIImage { let borderSize = CGFloat(borderSizeUInt) // If the image does not have an alpha layer, add one let image = self.imageWithAlpha() let newRect = CGRectMake(0, 0, image.size.width + borderSize * 2 , image.size.height + borderSize * 2) // Build a context that's the same dimensions as the new size let width = Int(newRect.size.width), height = Int(newRect.size.height) let bitmap = CGBitmapContextCreate(nil , width , height , CGImageGetBitsPerComponent(self.CGImage) , 0 , CGImageGetColorSpace(self.CGImage) , CGImageGetBitmapInfo(self.CGImage)) // Draw the image in the center of the context, leaving a gap around the edges let imageLocation = CGRectMake(borderSize, borderSize, image.size.width, image.size.height) CGContextDrawImage(bitmap, imageLocation, self.CGImage) let borderImageRef = CGBitmapContextCreateImage(bitmap) // Create a mask to make the border transparent, and combine it with the image let maskImageRef = newBorderMask(borderSizeUInt, size:newRect.size) let transparentBorderImageRef = CGImageCreateWithMask(borderImageRef, maskImageRef) return UIImage(CGImage: transparentBorderImageRef)! } /// Creates a mask that makes the outer edges transparent and everything else opaque /// The size must include the entire mask (opaque part + transparent border) /// The caller is responsible for releasing the returned reference by calling CGImageRelease private func newBorderMask(borderSize: UInt, size: CGSize) -> CGImageRef { let border = CGFloat(borderSize) // Build a context that's the same dimensions as the new size let colorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.None.rawValue) let width = Int(size.width), height = Int(size.height) let maskContext = CGBitmapContextCreate(nil, width, height, 8 /* 8-bit grayscale*/, 0 , colorSpace, bitmapInfo) // Start with a mask that's entirely transparent CGContextSetFillColorWithColor(maskContext, UIColor.blackColor().CGColor) CGContextFillRect(maskContext, CGRectMake(0, 0, size.width, size.height)) // Make the inner part (within the border) opaque CGContextSetFillColorWithColor(maskContext, UIColor.whiteColor().CGColor) CGContextFillRect(maskContext , CGRectMake(border, border, size.width - border * 2, size.height - border * 2)) // Return an image of the context return CGBitmapContextCreateImage(maskContext) } }
mit
1969aa6aa87c2371df9661efb88a58a1
42.074766
99
0.701671
4.771222
false
false
false
false
Takanu/Pelican
Sources/Pelican/Utilities/Utilities.swift
1
2297
// // Utilities.swift // kabuki // // Created by Takanu Kyriako on 24/03/2017. // // import Foundation import Dispatch // Must be specified for Linux support // This needs re-factoring ASAP. internal func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) } if next.hashValue != i { return nil } i += 1 return next } } internal class DispatchTimer { private let queue = DispatchQueue(label: "timer") private let interval: TimeInterval private let execute: () -> Void private var operation: DispatchWorkItem? init(interval: TimeInterval, execute: @escaping () -> Void) { self.interval = interval self.execute = execute } func start() { let operation = DispatchWorkItem { [weak self] in defer { self?.start() } self?.execute() } self.operation = operation queue.asyncAfter(deadline: .now() + interval, execute: operation) } func stop() { operation?.cancel() } } /// With Vapor 2 these are currently no longer necessary. /* // Extensions to manipulate node entries more seamlessly extension Node { mutating func addNodeEntry(name: String, value: NodeConvertible) throws { var object = self.nodeObject if object != nil { object![name] = try value.makeNode() self = try object!.makeNode() } } mutating func removeNodeEntry(name: String) throws -> Bool { var object = self.nodeObject if object != nil { _ = object!.removeValue(forKey: name) self = try object!.makeNode() return true } else { return false } } mutating func renameNodeEntry(from: String, to: String) throws -> Bool { var object = self.nodeObject if object != nil { let value = object!.removeValue(forKey: from) object![to] = value self = try object!.makeNode() return true } else { return false } } mutating func removeNilValues() throws { var object = self.nodeObject if object != nil { for value in object! { if value.value.isNull == true { object!.removeValue(forKey: value.key) } } self = try object!.makeNode() } } } */
mit
ae04c64d6382211fbfacb0d41863c77b
21.97
75
0.617327
4.079929
false
false
false
false
lanjing99/RxSwiftDemo
16-testing-with-rxtests/starter/Testing/Testing/ViewModel.swift
2
6220
/* * Copyright (c) 2014-2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import RxSwift import RxCocoa import Hue class ViewModel { let hexString = Variable<String>("") let color: Driver<UIColor> let rgb: Driver<(Int, Int, Int)> let colorName: Driver<String> init() { color = hexString.asObservable() .map { hex in guard hex.characters.count == 7 else { return .clear } let color = UIColor(hex: hex) return color } .asDriver(onErrorJustReturn: .clear) rgb = color.asObservable() .map { color in var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 color.getRed(&red, green: &green, blue: &blue, alpha: nil) let rgb = (Int(red * 255.0), Int(green * 255.0), Int(blue * 255.0)) return rgb } .asDriver(onErrorJustReturn: (0, 0, 0)) colorName = hexString.asObservable() .map { hexString in let hex = String(hexString.characters.dropFirst()) if let color = ColorName(rawValue: hex) { return "\(color)" } else { return "--" } } .asDriver(onErrorJustReturn: "") } } enum ColorName: String { case aliceBlue = "F0F8FF" case antiqueWhite = "FAEBD7" case aqua = "0080FF" case aquamarine = "7FFFD4" case azure = "F0FFFF" case beige = "F5F5DC" case bisque = "FFE4C4" case black = "000000" case blanchedAlmond = "FFEBCD" case blue = "0000FF" case blueViolet = "8A2BE2" case brown = "A52A2A" case burlyWood = "DEB887" case cadetBlue = "5F9EA0" case cyan = "00FFFF" case chartreuse = "7FFF00" case chocolate = "D2691E" case coral = "FF7F50" case cornflowerBlue = "6495ED" case cornSilk = "FFF8DC" case crimson = "DC143C" case darkBlue = "00008B" case darkCyan = "008B8B" case darkGoldenRod = "B8860B" case darkGray = "A9A9A9" case darkGreen = "006400" case darkKhaki = "BDB76B" case darkMagenta = "8B008B" case darkOliveGreen = "556B2F" case darkOrange = "FF8C00" case darkOrchid = "9932CC" case darkRed = "8B0000" case darkSalmon = "E9967A" case darkSeaGreen = "8FBC8F" case darkSlateBlue = "483D8B" case darkSlateGray = "2F4F4F" case darkTurquoise = "00CED1" case darkViolet = "9400D3" case deepPink = "FF1493" case deepSkyBlue = "00BFFF" case dimGray = "696969" case dodgerBlue = "1E90FF" case fireBrick = "B22222" case floralWhite = "FFFAF0" case forestGreen = "228B22" case fuchsia_magenta = "FF00FF" case gainsboro = "DCDCDC" case ghostWhite = "F8F8FF" case gold = "FFD700" case goldenRod = "DAA520" case gray = "808080" case green = "008000" case greenYellow = "ADFF2F" case honeyDew = "F0FFF0" case hotPink = "FF69B4" case indianRed = "CD5C5C" case indigo = "4B0082" case ivory = "FFFFF0" case khaki = "F0E68C" case lavender = "E6E6FA" case lavenderBlush = "FFF0F5" case lawnGreen = "7CFC00" case lemonChiffon = "FFFACD" case lightBlue = "ADD8E6" case lightCoral = "F08080" case lightCyan = "E0FFFF" case lightGoldenRodYellow = "FAFAD2" case lightGray = "D3D3D3" case lightGreen = "90EE90" case lightPink = "FFB6C1" case lightSalmon = "FFA07A" case lightSeaGreen = "20B2AA" case lightSkyBlue = "87CEFA" case lightSlateGray = "778899" case lightSteelBlue = "B0C4DE" case lightYellow = "FFFFE0" case lime = "00FF00" case limeGreen = "32CD32" case linen = "FAF0E6" case maroon = "800000" case mediumAquamarine = "66CDAA" case mediumBlue = "0000CD" case mediumOrchid = "BA55D3" case mediumPurple = "9370D8" case mediumSeaGreen = "3CB371" case mediumSlateBlue = "7B68EE" case mediumSpringGreen = "00FA9A" case mediumTurquoise = "48D1CC" case mediumVioletRed = "C71585" case midnightBlue = "191970" case mintCream = "F5FFFA" case mistyRose = "FFE4E1" case moccasin = "FFE4B5" case navajoWhite = "FFDEAD" case navy = "000080" case oldLace = "FDF5E6" case olive = "808000" case oliveDrab = "6B8E23" case orange = "FFA500" case orangeRed = "FF4500" case orchid = "DA70D6" case paleGoldenRod = "EEE8AA" case paleGreen = "98FB98" case paleTurquoise = "AFEEEE" case paleVioletRed = "D87093" case papayaWhip = "FFEFD5" case peachPuff = "FFDAB9" case peru = "CD853F" case pink = "FFC0CB" case plum = "DDA0DD" case powderBlue = "B0E0E6" case purple = "800080" case rayWenderlichGreen = "006636" case rebeccaPurple = "663399" case red = "FF0000" case rosyBrown = "BC8F8F" case royalBlue = "4169E1" case saddleBrown = "8B4513" case salmon = "FA8072" case sandyBrown = "F4A460" case seaGreen = "2E8B57" case seaShell = "FFF5EE" case sienna = "A0522D" case silver = "C0C0C0" case skyBlue = "87CEEB" case slateBlue = "6A5ACD" case slateGray = "708090" case snow = "FFFAFA" case springGreen = "00FF7F" case steelBlue = "4682B4" case tan = "D2B48C" case teal = "008080" case thistle = "D8BFD8" case tomato = "FF6347" case turquoise = "40E0D0" case violet = "EE82EE" case wheat = "F5DEB3" case white = "FFFFFF" case whiteSmoke = "F5F5F5" case yellow = "FFFF00" case yellowGreen = "9ACD32" }
mit
018e366a2ad7fe823d01f5282d371609
28.478673
80
0.674277
3.041565
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/ConversationPicker/ConversationPicker.swift
1
29145
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit protocol ConversationPickerDelegate: AnyObject { var selectedConversationsForConversationPicker: [ConversationItem] { get } func conversationPicker(_ conversationPickerViewController: ConversationPickerViewController, didSelectConversation conversation: ConversationItem) func conversationPicker(_ conversationPickerViewController: ConversationPickerViewController, didDeselectConversation conversation: ConversationItem) func conversationPickerDidCompleteSelection(_ conversationPickerViewController: ConversationPickerViewController) } @objc class ConversationPickerViewController: OWSViewController { // MARK: - Dependencies var databaseStorage: SDSDatabaseStorage { return SSKEnvironment.shared.databaseStorage } var contactsManager: OWSContactsManager { return Environment.shared.contactsManager } var profileManager: OWSProfileManager { return OWSProfileManager.shared() } // MARK: - weak var delegate: ConversationPickerDelegate? enum Section: Int, CaseIterable { case recents, signalContacts, groups } let kMaxPickerSelection = 32 private let tableView = UITableView() private let footerView = ConversationPickerFooterView() private var footerOffsetConstraint: NSLayoutConstraint! private lazy var searchBar: OWSSearchBar = { let searchBar = OWSSearchBar() searchBar.placeholder = CommonStrings.searchPlaceholder searchBar.delegate = self return searchBar }() // MARK: - UIViewController override var canBecomeFirstResponder: Bool { return true } var currentInputAcccessoryView: UIView? { didSet { if oldValue != currentInputAcccessoryView { searchBar.inputAccessoryView = currentInputAcccessoryView searchBar.reloadInputViews() reloadInputViews() } } } override var inputAccessoryView: UIView? { return currentInputAcccessoryView } override func loadView() { self.view = UIView() view.backgroundColor = Theme.backgroundColor view.addSubview(tableView) tableView.separatorColor = Theme.cellSeparatorColor tableView.backgroundColor = Theme.backgroundColor tableView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom) self.autoPinView(toBottomOfViewControllerOrKeyboard: tableView, avoidNotch: true) searchBar.sizeToFit() tableView.tableHeaderView = searchBar } override func viewDidLoad() { super.viewDidLoad() title = Strings.title blockListCache.startObservingAndSyncState(delegate: self) tableView.dataSource = self tableView.delegate = self tableView.allowsMultipleSelection = true tableView.register(ConversationPickerCell.self, forCellReuseIdentifier: ConversationPickerCell.reuseIdentifier) tableView.register(DarkThemeTableSectionHeader.self, forHeaderFooterViewReuseIdentifier: DarkThemeTableSectionHeader.reuseIdentifier) footerView.delegate = self conversationCollection = buildConversationCollection() restoreSelection(tableView: tableView) } // MARK: - ConversationCollection func restoreSelection(tableView: UITableView) { guard let delegate = delegate else { return } tableView.indexPathsForSelectedRows?.forEach { tableView.deselectRow(at: $0, animated: false) } for selectedConversation in delegate.selectedConversationsForConversationPicker { guard let index = conversationCollection.indexPath(conversation: selectedConversation) else { // This can happen when restoring selection while the currently displayed results // are filtered. continue } tableView.selectRow(at: index, animated: false, scrollPosition: .none) } updateFooterForCurrentSelection(animated: false) } let blockListCache = BlockListCache() var fullTextSearcher: FullTextSearcher { return FullTextSearcher.shared } func buildSearchResults(searchText: String) -> Promise<ComposeScreenSearchResultSet?> { guard searchText.count > 1 else { return Promise.value(nil) } return DispatchQueue.global().async(.promise) { return self.databaseStorage.readReturningResult { transaction in return self.fullTextSearcher.searchForComposeScreen(searchText: searchText, transaction: transaction) } } } func buildGroupItem(_ groupThread: TSGroupThread, transaction: SDSAnyReadTransaction) -> GroupConversationItem { let isBlocked = self.blockListCache.isBlocked(thread: groupThread) let dmConfig = groupThread.disappearingMessagesConfiguration(with: transaction) return GroupConversationItem(groupThread: groupThread, isBlocked: isBlocked, disappearingMessagesConfig: dmConfig) } func buildContactItem(_ address: SignalServiceAddress, transaction: SDSAnyReadTransaction) -> ContactConversationItem { let isBlocked = self.blockListCache.isBlocked(address: address) let dmConfig = TSContactThread.getWithContactAddress(address, transaction: transaction)?.disappearingMessagesConfiguration(with: transaction) let contactName = contactsManager.displayName(for: address, transaction: transaction) let comparableName = contactsManager.comparableName(for: address, transaction: transaction) return ContactConversationItem(address: address, isBlocked: isBlocked, disappearingMessagesConfig: dmConfig, contactName: contactName, comparableName: comparableName) } func buildConversationCollection() -> ConversationCollection { return self.databaseStorage.uiReadReturningResult { transaction in var recentItems: [RecentConversationItem] = [] var contactItems: [ContactConversationItem] = [] var groupItems: [GroupConversationItem] = [] var seenAddresses: Set<SignalServiceAddress> = Set() let maxRecentCount = 25 let addThread = { (thread: TSThread) -> Void in switch thread { case let contactThread as TSContactThread: let item = self.buildContactItem(contactThread.contactAddress, transaction: transaction) seenAddresses.insert(contactThread.contactAddress) if recentItems.count < maxRecentCount { let recentItem = RecentConversationItem(backingItem: .contact(item)) recentItems.append(recentItem) } else { contactItems.append(item) } case let groupThread as TSGroupThread: let item = self.buildGroupItem(groupThread, transaction: transaction) if recentItems.count < maxRecentCount { let recentItem = RecentConversationItem(backingItem: .group(item)) recentItems.append(recentItem) } else { groupItems.append(item) } default: owsFailDebug("unexpected thread: \(thread)") } } try! AnyThreadFinder().enumerateVisibleThreads(isArchived: false, transaction: transaction) { thread in addThread(thread) } try! AnyThreadFinder().enumerateVisibleThreads(isArchived: true, transaction: transaction) { thread in addThread(thread) } SignalAccount.anyEnumerate(transaction: transaction) { signalAccount, _ in let address = signalAccount.recipientAddress guard !seenAddresses.contains(address) else { return } seenAddresses.insert(address) let contactItem = self.buildContactItem(address, transaction: transaction) contactItems.append(contactItem) } contactItems.sort() return ConversationCollection(contactConversations: contactItems, recentConversations: recentItems, groupConversations: groupItems) } } func buildConversationCollection(searchResults: ComposeScreenSearchResultSet?) -> Promise<ConversationCollection> { guard let searchResults = searchResults else { return Promise.value(buildConversationCollection()) } return DispatchQueue.global().async(.promise) { return self.databaseStorage.readReturningResult { transaction in let groupItems = searchResults.groupThreads.map { self.buildGroupItem($0, transaction: transaction) } let contactItems = searchResults.signalAccounts.map { self.buildContactItem($0.recipientAddress, transaction: transaction) } return ConversationCollection(contactConversations: contactItems, recentConversations: [], groupConversations: groupItems) } } } func conversation(for indexPath: IndexPath) -> ConversationItem? { guard let section = Section(rawValue: indexPath.section) else { owsFailDebug("section was unexpectedly nil") return nil } return conversationCollection.conversations(section: section)[indexPath.row] } var conversationCollection: ConversationCollection = .empty struct ConversationCollection { static let empty: ConversationCollection = ConversationCollection(contactConversations: [], recentConversations: [], groupConversations: []) let contactConversations: [ConversationItem] let recentConversations: [ConversationItem] let groupConversations: [ConversationItem] func conversations(section: Section) -> [ConversationItem] { switch section { case .recents: return recentConversations case .signalContacts: return contactConversations case .groups: return groupConversations } } func indexPath(conversation: ConversationItem) -> IndexPath? { switch conversation.messageRecipient { case .contact: if let row = (recentConversations.map { $0.messageRecipient }).firstIndex(of: conversation.messageRecipient) { return IndexPath(row: row, section: Section.recents.rawValue) } else if let row = (contactConversations.map { $0.messageRecipient }).firstIndex(of: conversation.messageRecipient) { return IndexPath(row: row, section: Section.signalContacts.rawValue) } else { return nil } case .group: if let row = (recentConversations.map { $0.messageRecipient }).firstIndex(of: conversation.messageRecipient) { return IndexPath(row: row, section: Section.recents.rawValue) } else if let row = (groupConversations.map { $0.messageRecipient }).firstIndex(of: conversation.messageRecipient) { return IndexPath(row: row, section: Section.groups.rawValue) } else { return nil } } } } } extension ConversationPickerViewController: BlockListCacheDelegate { func blockListCacheDidUpdate(_ blocklistCache: BlockListCache) { Logger.debug("") self.conversationCollection = buildConversationCollection() } } extension ConversationPickerViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Section.allCases.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard !Theme.isDarkThemeEnabled else { // we build a custom header for dark theme return nil } return titleForHeader(inSection: section) } func titleForHeader(inSection section: Int) -> String? { guard let section = Section(rawValue: section) else { owsFailDebug("section was unexpectedly nil") return nil } guard conversationCollection.conversations(section: section).count > 0 else { return nil } switch section { case .recents: return Strings.recentsSection case .signalContacts: return Strings.signalContactsSection case .groups: return Strings.groupsSection } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let section = Section(rawValue: section) else { owsFailDebug("section was unexpectedly nil") return 0 } return conversationCollection.conversations(section: section).count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let conversationItem = conversation(for: indexPath) else { owsFail("conversation was unexpectedly nil") } guard let cell = tableView.dequeueReusableCell(withIdentifier: ConversationPickerCell.reuseIdentifier, for: indexPath) as? ConversationPickerCell else { owsFail("cell was unexpectedly nil for indexPath: \(indexPath)") } databaseStorage.uiRead { transaction in cell.configure(conversationItem: conversationItem, transaction: transaction) } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard Theme.isDarkThemeEnabled else { return nil } guard let title = titleForHeader(inSection: section) else { // empty sections will have no title - don't show a header. let dummyView = UIView() dummyView.backgroundColor = .yellow return dummyView } guard let sectionHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: DarkThemeTableSectionHeader.reuseIdentifier) as? DarkThemeTableSectionHeader else { owsFailDebug("unable to build section header for section: \(section)") return nil } sectionHeader.configure(title: title) return sectionHeader } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard titleForHeader(inSection: section) != nil else { // empty sections will have no title - don't show a header. return 0 } return DarkThemeHeaderView.desiredHeight } } extension ConversationPickerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard let delegate = delegate else { return nil } guard let item = conversation(for: indexPath) else { owsFailDebug("item was unexpectedly nil") return nil } guard delegate.selectedConversationsForConversationPicker.count < kMaxPickerSelection else { showTooManySelectedToast() return nil } guard !item.isBlocked else { // TODO remove these passed in dependencies. let contactsManager = Environment.shared.contactsManager! let blockingManager = OWSBlockingManager.shared() switch item.messageRecipient { case .contact(let address): BlockListUIUtils.showUnblockAddressActionSheet(address, from: self, blockingManager: blockingManager, contactsManager: contactsManager) { isStillBlocked in AssertIsOnMainThread() guard !isStillBlocked else { return } self.conversationCollection = self.buildConversationCollection() tableView.reloadData() self.restoreSelection(tableView: tableView) } case .group(let groupThread): BlockListUIUtils.showUnblockThreadActionSheet(groupThread, from: self, blockingManager: blockingManager, contactsManager: contactsManager) { isStillBlocked in AssertIsOnMainThread() guard !isStillBlocked else { return } self.conversationCollection = self.buildConversationCollection() tableView.reloadData() self.restoreSelection(tableView: tableView) } } return nil } return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let conversation = conversation(for: indexPath) else { owsFailDebug("conversation was unexpectedly nil") return } delegate?.conversationPicker(self, didSelectConversation: conversation) updateFooterForCurrentSelection(animated: true) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { guard let conversation = conversation(for: indexPath) else { owsFailDebug("conversation was unexpectedly nil") return } delegate?.conversationPicker(self, didDeselectConversation: conversation) updateFooterForCurrentSelection(animated: true) } private func updateFooterForCurrentSelection(animated: Bool) { guard let delegate = delegate else { return } let conversations = delegate.selectedConversationsForConversationPicker if conversations.count == 0 { currentInputAcccessoryView = nil } else { currentInputAcccessoryView = footerView } let labelText = conversations.map { $0.title }.joined(separator: ", ") footerView.setNamesText(labelText, animated: animated) } private func showTooManySelectedToast() { Logger.info("") let toastFormat = NSLocalizedString("CONVERSATION_PICKER_CAN_SELECT_NO_MORE_CONVERSATIONS", comment: "Momentarily shown to the user when attempting to select more conversations than is allowed. Embeds {{max number of conversations}} that can be selected.") let toastText = String(format: toastFormat, NSNumber(value: kMaxPickerSelection)) let toastController = ToastController(text: toastText) let bottomInset = (view.bounds.height - tableView.frame.height) let kToastInset: CGFloat = bottomInset + 10 toastController.presentToastView(fromBottomOfView: view, inset: kToastInset) } } extension ConversationPickerViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { buildSearchResults(searchText: searchText).then { [weak self] searchResults -> Promise<ConversationCollection> in guard let self = self else { throw PMKError.cancelled } return self.buildConversationCollection(searchResults: searchResults) }.done { [weak self] conversationCollection in guard let self = self else { return } self.conversationCollection = conversationCollection self.tableView.reloadData() self.restoreSelection(tableView: self.tableView) }.retainUntilComplete() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = nil searchBar.resignFirstResponder() } } extension ConversationPickerViewController: ConversationPickerFooterDelegate { fileprivate func conversationPickerFooterDelegateDidRequestProceed(_ conversationPickerFooterView: ConversationPickerFooterView) { delegate?.conversationPickerDidCompleteSelection(self) } } extension ConversationPickerViewController { private struct Strings { static let title = NSLocalizedString("CONVERSATION_PICKER_TITLE", comment: "navbar header") static let recentsSection = NSLocalizedString("CONVERSATION_PICKER_SECTION_RECENTS", comment: "table section header for section containing recent conversations") static let signalContactsSection = NSLocalizedString("CONVERSATION_PICKER_SECTION_SIGNAL_CONTACTS", comment: "table section header for section containing contacts") static let groupsSection = NSLocalizedString("CONVERSATION_PICKER_SECTION_GROUPS", comment: "table section header for section containing groups") } } // MARK: - ConversationPickerCell private class ConversationPickerCell: ContactTableViewCell { static let reuseIdentifier = "ConversationPickerCell" // MARK: - UITableViewCell override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) selectedBadgeView.isHidden = !selected unselectedBadgeView.isHidden = selected } // MARK: - ContactTableViewCell public func configure(conversationItem: ConversationItem, transaction: SDSAnyReadTransaction) { if conversationItem.isBlocked { setAccessoryMessage(MessageStrings.conversationIsBlocked) } else { ows_setAccessoryView( buildAccessoryView(disappearingMessagesConfig: conversationItem.disappearingMessagesConfig) ) } switch conversationItem.messageRecipient { case .contact(let address): super.configure(withRecipientAddress: address) case .group(let groupThread): super.configure(with: groupThread, transaction: transaction) } selectionStyle = .none } // MARK: - Subviews static let selectedBadgeImage = #imageLiteral(resourceName: "image_editor_checkmark_full").withRenderingMode(.alwaysTemplate) let selectionBadgeSize = CGSize(width: 20, height: 20) lazy var selectionView: UIView = { let container = UIView() container.layoutMargins = .zero container.autoSetDimensions(to: selectionBadgeSize) container.addSubview(unselectedBadgeView) unselectedBadgeView.autoPinEdgesToSuperviewMargins() container.addSubview(selectedBadgeView) selectedBadgeView.autoPinEdgesToSuperviewMargins() return container }() func buildAccessoryView(disappearingMessagesConfig: OWSDisappearingMessagesConfiguration?) -> UIView { guard let disappearingMessagesConfig = disappearingMessagesConfig, disappearingMessagesConfig.isEnabled else { return selectionView } let timerView = DisappearingTimerConfigurationView(durationSeconds: disappearingMessagesConfig.durationSeconds) timerView.tintColor = Theme.middleGrayColor timerView.autoSetDimensions(to: CGSize(width: 44, height: 44)) timerView.setCompressionResistanceHigh() let stackView = UIStackView(arrangedSubviews: [timerView, selectionView]) stackView.alignment = .center stackView.setCompressionResistanceHigh() return stackView } lazy var unselectedBadgeView: UIView = { let circleView = CircleView() circleView.autoSetDimensions(to: selectionBadgeSize) circleView.layer.borderWidth = 1.0 circleView.layer.borderColor = Theme.outlineColor.cgColor return circleView }() lazy var selectedBadgeView: UIView = { let imageView = UIImageView() imageView.autoSetDimensions(to: selectionBadgeSize) imageView.image = ConversationPickerCell.selectedBadgeImage imageView.tintColor = .ows_signalBlue return imageView }() } // MARK: - ConversationPickerFooterView private protocol ConversationPickerFooterDelegate: AnyObject { func conversationPickerFooterDelegateDidRequestProceed(_ conversationPickerFooterView: ConversationPickerFooterView) } private class ConversationPickerFooterView: UIView { weak var delegate: ConversationPickerFooterDelegate? override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = .flexibleHeight translatesAutoresizingMaskIntoConstraints = false backgroundColor = Theme.keyboardBackgroundColor layoutMargins = UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 16) let topStrokeView = UIView() topStrokeView.backgroundColor = Theme.hairlineColor addSubview(topStrokeView) topStrokeView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom) topStrokeView.autoSetDimension(.height, toSize: CGHairlineWidth()) let stackView = UIStackView(arrangedSubviews: [labelScrollView, proceedButton]) stackView.spacing = 12 stackView.alignment = .center addSubview(stackView) stackView.autoPinEdgesToSuperviewMargins() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return CGSize.zero } // MARK: public var namesText: String? { get { return namesLabel.text } } func setNamesText(_ newValue: String?, animated: Bool) { let changes = { self.namesLabel.text = newValue self.layoutIfNeeded() let offset = max(0, self.labelScrollView.contentSize.width - self.labelScrollView.bounds.width) let trailingEdge = CGPoint(x: offset, y: 0) self.labelScrollView.setContentOffset(trailingEdge, animated: false) } if animated { UIView.animate(withDuration: 0.1, animations: changes) } else { changes() } } // MARK: private subviews lazy var labelScrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.addSubview(namesLabel) namesLabel.autoPinEdgesToSuperviewEdges() namesLabel.autoMatch(.height, to: .height, of: scrollView) return scrollView }() lazy var namesLabel: UILabel = { let label = UILabel() label.font = UIFont.ows_dynamicTypeBody label.textColor = Theme.secondaryColor label.setContentHuggingLow() return label }() lazy var proceedButton: UIButton = { let button = OWSButton.sendButton(imageName: "send-solid-24") { [weak self] in guard let self = self else { return } self.delegate?.conversationPickerFooterDelegateDidRequestProceed(self) } return button }() }
gpl-3.0
d5b419523b42af44f10c45b09c6e5618
38.924658
208
0.629165
6.037912
false
false
false
false
PureSwift/LittleCMS
Sources/LittleCMS/ToneCurve.swift
1
1027
// // ToneCurve.swift // LittleCMS // // Created by Alsey Coleman Miller on 6/3/17. // // import CLCMS public final class ToneCurve { // MARK: - Properties internal let internalPointer: OpaquePointer // MARK: - Initialization deinit { // deallocate profile cmsFreeToneCurve(internalPointer) } internal init(_ internalPointer: OpaquePointer) { self.internalPointer = internalPointer } public init?(gamma: Double, context: Context? = nil) { guard let internalPointer = cmsBuildGamma(context?.internalPointer, gamma) else { return nil } self.internalPointer = internalPointer } // MARK: - Accessors public var isLinear: Bool { return cmsIsToneCurveLinear(internalPointer) != 0 } } // MARK: - Internal Protocols extension ToneCurve: DuplicableHandle { static var cmsDuplicate: cmsDuplicateFunction { return cmsDupToneCurve } }
mit
fcf66b2cc8abb685ff6c5681ee810280
19.54
82
0.615385
4.732719
false
false
false
false
iOSDevLog/iOSDevLog
Checklists/Checklists/ListDetailViewController.swift
1
3357
// // ListDetailViewController.swift // Checklists // // Created by iosdevlog on 16/1/3. // Copyright © 2016年 iosdevlog. All rights reserved. // import UIKit protocol ListDetailViewControllerDelegate: class { func listDetailViewControllerDidCancel(controller: ListDetailViewController) func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist) func listDetailViewController(controller: ListDetailViewController, didFinishEditingChecklist checklist: Checklist) } class ListDetailViewController: UITableViewController, UITextFieldDelegate, IconPickerViewControllerDelegate { @IBOutlet weak var doneBarButton: UIBarButtonItem! @IBOutlet weak var textField: UITextField! weak var delegate: ListDetailViewControllerDelegate? var checklistToEdit: Checklist? var iconName = "Folder" @IBOutlet weak var iconImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let checklist = checklistToEdit { title = "Edit Checklist" textField.text = checklist.name doneBarButton.enabled = true iconName = checklist.iconName } iconImageView.image = UIImage(named: iconName) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textField.becomeFirstResponder() } // MARK: - Action @IBAction func cancel() { delegate?.listDetailViewControllerDidCancel(self) } @IBAction func done() { if let checklist = checklistToEdit { checklist.name = textField.text! checklist.iconName = iconName delegate?.listDetailViewController(self, didFinishEditingChecklist: checklist) } else { let checklist = Checklist(name: textField.text!, iconName: iconName) delegate?.listDetailViewController(self, didFinishAddingChecklist: checklist) } } // MARK: - Table view delegate override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 1 { return indexPath } else { return nil } } // MARK: - UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let oldText: NSString = textField.text! let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string) doneBarButton.enabled = (newText.length > 0) return true } // MARK: - IconPickerViewControllerDelegate func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) { self.iconName = iconName iconImageView.image = UIImage(named: iconName) navigationController?.popViewControllerAnimated(true) } // MARK: - segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PickIcon" { let controller = segue.destinationViewController as! IconPickerViewController controller.delegate = self } } }
mit
6751e92c5b427f103de182ef64b7d16f
31.25
132
0.672928
5.884211
false
false
false
false
badparking/badparking-ios
BadParking/Classes/Pages/SendViewController.swift
1
3553
// // SendViewController.swift // BadParking // // Created by Roman Simenok on 10/18/16. // Copyright © 2016 BadParking. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class SendViewController: BasePageViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var facebookVIew: UIView! var claim:Claim? override func viewDidLoad() { super.viewDidLoad() self.claim = (self.parent?.parent as! MainViewController).claim self.index = 3 self.tableView.estimatedRowHeight = 50 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.tableFooterView = UIView.init(frame: CGRect.zero) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // check if user logged in with FB and has phone number associated guard FBSDKAccessToken.current() == nil else { facebookVIew.isHidden = true return } facebookVIew.isHidden = false let storyboard = UIStoryboard(name: "Main", bundle: nil) let accountVC = storyboard.instantiateViewController(withIdentifier: "AccountTableViewController") as! AccountTableViewController // self.present(accountVC, animated: true, completion: nil) let loginButton = FBSDKLoginButton() loginButton.readPermissions = ["public_profile", "email"] loginButton.delegate = accountVC facebookVIew.addSubview(loginButton) loginButton.center = CGPoint(x: facebookVIew.bounds.width/2, y: facebookVIew.bounds.height/2) tableView.reloadData() } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning can be 4 if we have additional info return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: indexPath.row == 0 ? "photosCell" : "cell", for: indexPath) if indexPath.row == 0 { // photos let icon = cell.viewWithTag(1) as! UIImageView icon.image = #imageLiteral(resourceName: "photosIcon") let stackView = cell.viewWithTag(2) as! UIStackView let firstImage = stackView.viewWithTag(3) as! UIImageView let secondImage = stackView.viewWithTag(4) as! UIImageView firstImage.image = claim?.photos[0].image secondImage.image = claim?.photos[1].image } else if indexPath.row == 1 { // location (cell.viewWithTag(1) as! UIImageView).image = #imageLiteral(resourceName: "locationIcon") (cell.viewWithTag(2) as! UILabel).text = "Адреса:" (cell.viewWithTag(3) as! UILabel).text = claim?.address ?? "" } else if indexPath.row == 2 { // crime types (cell.viewWithTag(1) as! UIImageView).image = #imageLiteral(resourceName: "violation") (cell.viewWithTag(2) as! UILabel).text = "Порушення:" (cell.viewWithTag(3) as! UILabel).text = claim?.crimetypes.map({$0.name ?? ""}).joined(separator: "\n") } return cell } // MARK: IBActions @IBAction func sendViolationPressed(_ sender: NextButton) { // #warnind send data to server } }
apache-2.0
5dde8015a0c52e3fd8aa6b8a53402716
38.741573
137
0.653096
4.635649
false
false
false
false
zenopolis/Minimal-Shoebox
Shoebox/DetailViewController.swift
1
2288
// // DetailViewController.swift // Shoebox // // Created by David Kennedy on 10/04/2016. // Copyright © 2016 David Kennedy of Zenopolis. All rights reserved. // import Cocoa class DetailViewController: NSViewController { // MARK: - Outlets @IBOutlet var textView: NSTextView! // MARK: Lifecycle override func viewDidDisappear() { super.viewWillDisappear() storeTextChanges() } deinit { if let library = dataController.library { library.removeObserver(self, forKeyPath: Library.ObservableProperty.selectedItem) } } // MARK: - Data Controller Access override var representedObject: AnyObject? { didSet { registerAsObserver() updateView() } } var dataController: DataController! { return representedObject as! DataController } // MARK: Helper Methods func registerAsObserver() { dataController.library.addObserver(self, forKeyPath: Library.ObservableProperty.selectedItem, options: .New, context: nil) } func updateView() { if let text = dataController.library.selectedItem.content { textView.string = text } } // MARK: - NSText Delegate - Editing Text var textHasChanged = false func textDidBeginEditing(notification: NSNotification) { textHasChanged = true } func textDidEndEditing(notification: NSNotification) { storeTextChanges() } // MARK: Helper Methods private func storeTextChanges() { if textHasChanged { if let item = dataController.library.selectedItem { item.content = textView.string } textHasChanged = false } } // MARK: - Key Value Observing override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (keyPath == Library.ObservableProperty.selectedItem) { updateView() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } }
mit
151e7f9d1796f80730ac000ef26d203f
24.131868
157
0.607783
5.343458
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/model/UserBalance.swift
1
2314
// // userBalance.swift // Chance_wallet // // Created by Chance on 16/1/20. // Copyright © 2016年 Chance. All rights reserved. // import UIKit import RealmSwift class UserBalance: Object { //MARK: - 数据库的字段 @objc dynamic var address = "" @objc dynamic var balance: Double = 0 @objc dynamic var balanceSat: Int = 0 @objc dynamic var totalReceived: Double = 0 @objc dynamic var totalReceivedSat: Int = 0 @objc dynamic var totalSent: Double = 0 @objc dynamic var totalSentSat: Int = 0 @objc dynamic var unconfirmedBalance: Double = 0 @objc dynamic var unconfirmedBalanceSat: Int = 0 @objc dynamic var unconfirmedTxApperances: Int = 0 @objc dynamic var txApperances: Int = 0 @objc dynamic var currency: String = "" //MARK: - 忽略持久化的字段 var currencyType: CurrencyType = .BTC override static func primaryKey() -> String? { return "address" } /// 忽略建立的字段 /// /// - Returns: override static func ignoredProperties() -> [String] { return [ "currencyType" ] } /// 保存 func save() { //保存到数据库 let realm = RealmDBHelper.shared.txDB try? realm.write { realm.add(self, update: true) } } /// 获取用户余额 /// /// - Parameter address: 地址 /// - Returns: 用户余额对象 class func getUserBalance(byAddress address: String) -> UserBalance? { let realm = RealmDBHelper.shared.txDB //Realm数据库 let datas: Results<UserBalance> = realm.objects(UserBalance.self).filter(" address = '\(address)'") return datas.first } /// 计算法币的价值 /// /// - Parameter price: 单价 /// - Returns: (余额 + 未确认) * 单价 func getBTCBalance() -> String { let total = BTCAmount(self.balanceSat + self.unconfirmedBalanceSat) return total.toBTC() } /// 计算法币的价值 /// /// - Parameter price: 单价 /// - Returns: (余额 + 未确认) * 单价 func getLegalMoney(price: Double) -> Double { let total = (self.balance + self.unconfirmedBalance) * price return total } }
mit
24856ccb927033a7f4ee2ec7c0897e43
24.559524
107
0.583605
3.875451
false
false
false
false
ustwo/formvalidator-swift
Example/macOS/FormViewController.swift
1
1664
// // FormViewController.swift // FormValidatorSwift // // Created by Aaron McTavish on 06/01/2017. // Copyright © 2017 ustwo Fampany Ltd. All rights reserved. // import AppKit import FormValidatorSwift final class FormViewController: NSViewController { // MARK: - Properties var form = ControlForm() fileprivate var underlyingView: FormView { if let myView = view as? FormView { return myView } let newView = FormView() view = newView return newView } // MARK: - View Lifecycle override func loadView() { view = FormView() } override func viewDidLoad() { super.viewDidLoad() form.addEntry(underlyingView.titleEntry.textField) form.addEntry(underlyingView.nameEntry.textField) form.addEntry(underlyingView.emailEntry.textField) underlyingView.submitButton.action = #selector(FormViewController.submitButtonPressed(_:)) } // MARK: - Control Actions @objc func submitButtonPressed(_ sender: NSButton) { let alertMessage: String if form.isValid { alertMessage = NSLocalizedString("Success: Your data has been submitted!", comment: "") } else { alertMessage = NSLocalizedString("Error: Please correct your entries in the form.", comment: "") } let alert = NSAlert() alert.alertStyle = .critical alert.messageText = alertMessage alert.beginSheetModal(for: NSApplication.shared.mainWindow!, completionHandler: nil) } }
mit
7ab8d28af63a41cc0abaaed5d515cbe7
23.820896
108
0.613349
5.364516
false
false
false
false
overtake/TelegramSwift
packages/FetchManager/Sources/FetchManager/PreloadVideoResource.swift
1
1823
// // File.swift // // // Created by Mike Renoir on 21.02.2022. // import Foundation import SwiftSignalKit import Postbox import TelegramCore public func preloadVideoResource(postbox: Postbox, resourceReference: MediaResourceReference, duration: Double) -> Signal<Never, NoError> { return Signal { subscriber in let queue = Queue() let disposable = MetaDisposable() queue.async { // let maximumFetchSize = 2 * 1024 * 1024 + 128 * 1024 // //let maximumFetchSize = 128 // let sourceImpl = FFMpegMediaFrameSource(queue: queue, postbox: postbox, resourceReference: resourceReference, tempFilePath: nil, streamable: true, video: true, preferSoftwareDecoding: false, fetchAutomatically: true, maximumFetchSize: maximumFetchSize) // let source = QueueLocalObject(queue: queue, generate: { // return sourceImpl // }) // let signal = sourceImpl.seek(timestamp: 0.0) // |> deliverOn(queue) // |> mapToSignal { result -> Signal<Never, MediaFrameSourceSeekError> in // let result = result.syncWith({ $0 }) // if let videoBuffer = result.buffers.videoBuffer { // let impl = source.syncWith({ $0 }) // // return impl.ensureHasFrames(until: min(duration, videoBuffer.duration.seconds)) // |> ignoreValues // |> castError(MediaFrameSourceSeekError.self) // } else { // return .complete() // } // } // disposable.set(signal.start(error: { _ in // subscriber.putCompletion() // }, completed: { // subscriber.putCompletion() // })) } return disposable } }
gpl-2.0
9c513190624ecfde4496f71bd224f007
38.630435
266
0.574877
4.403382
false
false
false
false
uber/RIBs
ios/RIBs/Classes/ViewableRouter.swift
1
4243
// // Copyright (c) 2017. Uber Technologies // // 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 RxSwift /// The base protocol for all routers that own their own view controllers. public protocol ViewableRouting: Routing { // The following methods must be declared in the base protocol, since `Router` internally invokes these methods. // In order to unit test router with a mock child router, the mocked child router first needs to conform to the // custom subclass routing protocol, and also this base protocol to allow the `Router` implementation to execute // base class logic without error. /// The base view controllable associated with this `Router`. var viewControllable: ViewControllable { get } } /// The base class of all routers that owns view controllers, representing application states. /// /// A `Router` acts on inputs from its corresponding interactor, to manipulate application state and view state, /// forming a tree of routers that drives the tree of view controllers. Router drives the lifecycle of its owned /// interactor. `Router`s should always use helper builders to instantiate children `Router`s. open class ViewableRouter<InteractorType, ViewControllerType>: Router<InteractorType>, ViewableRouting { /// The corresponding `ViewController` owned by this `Router`. public let viewController: ViewControllerType /// The base `ViewControllable` associated with this `Router`. public let viewControllable: ViewControllable /// Initializer. /// /// - parameter interactor: The corresponding `Interactor` of this `Router`. /// - parameter viewController: The corresponding `ViewController` of this `Router`. public init(interactor: InteractorType, viewController: ViewControllerType) { self.viewController = viewController guard let viewControllable = viewController as? ViewControllable else { fatalError("\(viewController) should conform to \(ViewControllable.self)") } self.viewControllable = viewControllable super.init(interactor: interactor) } // MARK: - Internal override func internalDidLoad() { setupViewControllerLeakDetection() super.internalDidLoad() } // MARK: - Private private var viewControllerDisappearExpectation: LeakDetectionHandle? private func setupViewControllerLeakDetection() { let disposable = interactable.isActiveStream // Do not retain self here to guarantee execution. Retaining self will cause the dispose bag to never be // disposed, thus self is never deallocated. Also cannot just store the disposable and call dispose(), // since we want to keep the subscription alive until deallocation, in case the router is re-attached. // Using weak does require the router to be retained until its interactor is deactivated. .subscribe(onNext: { [weak self] (isActive: Bool) in guard let strongSelf = self else { return } strongSelf.viewControllerDisappearExpectation?.cancel() strongSelf.viewControllerDisappearExpectation = nil if !isActive { let viewController = strongSelf.viewControllable.uiviewController strongSelf.viewControllerDisappearExpectation = LeakDetector.instance.expectViewControllerDisappear(viewController: viewController) } }) _ = deinitDisposable.insert(disposable) } deinit { LeakDetector.instance.expectDeallocate(object: viewControllable.uiviewController, inTime: LeakDefaultExpectationTime.viewDisappear) } }
apache-2.0
fb0c680500c0f876c574dae3e9276a56
43.663158
151
0.711053
5.290524
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/SectionEditorNavigationItemController.swift
1
6881
protocol SectionEditorNavigationItemControllerDelegate: AnyObject { func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapProgressButton progressButton: UIBarButtonItem) func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapCloseButton closeButton: UIBarButtonItem) func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapUndoButton undoButton: UIBarButtonItem) func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapRedoButton redoButton: UIBarButtonItem) func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapReadingThemesControlsButton readingThemesControlsButton: UIBarButtonItem) } class SectionEditorNavigationItemController: NSObject, Themeable { weak var navigationItem: UINavigationItem? var readingThemesControlsToolbarItem: UIBarButtonItem { return readingThemesControlsButton } init(navigationItem: UINavigationItem) { self.navigationItem = navigationItem super.init() configureNavigationButtonItems() } func apply(theme: Theme) { for case let barButonItem as BarButtonItem in navigationItem?.rightBarButtonItems ?? [] { barButonItem.apply(theme: theme) } for case let barButonItem as BarButtonItem in navigationItem?.leftBarButtonItems ?? [] { barButonItem.apply(theme: theme) } } weak var delegate: SectionEditorNavigationItemControllerDelegate? private class BarButtonItem: UIBarButtonItem, Themeable { var tintColorKeyPath: KeyPath<Theme, UIColor>? convenience init(title: String?, style: UIBarButtonItem.Style, target: Any?, action: Selector?, tintColorKeyPath: KeyPath<Theme, UIColor>) { self.init(title: title, style: style, target: target, action: action) self.tintColorKeyPath = tintColorKeyPath } convenience init(image: UIImage?, style: UIBarButtonItem.Style, target: Any?, action: Selector?, tintColorKeyPath: KeyPath<Theme, UIColor>, accessibilityLabel: String? = nil) { let button = UIButton(type: .system) button.setImage(image, for: .normal) if let target = target, let action = action { button.addTarget(target, action: action, for: .touchUpInside) } self.init(customView: button) self.tintColorKeyPath = tintColorKeyPath self.accessibilityLabel = accessibilityLabel } func apply(theme: Theme) { guard let tintColorKeyPath = tintColorKeyPath else { return } let newTintColor = theme[keyPath: tintColorKeyPath] if customView == nil { tintColor = newTintColor } else if let button = customView as? UIButton { button.tintColor = newTintColor } } } private lazy var progressButton: BarButtonItem = { return BarButtonItem(title: CommonStrings.nextTitle, style: .done, target: self, action: #selector(progress(_:)), tintColorKeyPath: \Theme.colors.link) }() private lazy var redoButton: BarButtonItem = { return BarButtonItem(image: #imageLiteral(resourceName: "redo"), style: .plain, target: self, action: #selector(redo(_ :)), tintColorKeyPath: \Theme.colors.inputAccessoryButtonTint, accessibilityLabel: CommonStrings.redo) }() private lazy var undoButton: BarButtonItem = { return BarButtonItem(image: #imageLiteral(resourceName: "undo"), style: .plain, target: self, action: #selector(undo(_ :)), tintColorKeyPath: \Theme.colors.inputAccessoryButtonTint, accessibilityLabel: CommonStrings.undo) }() private lazy var readingThemesControlsButton: BarButtonItem = { return BarButtonItem(image: #imageLiteral(resourceName: "settings-appearance"), style: .plain, target: self, action: #selector(showReadingThemesControls(_ :)), tintColorKeyPath: \Theme.colors.inputAccessoryButtonTint, accessibilityLabel: CommonStrings.readingThemesControls) }() private lazy var separatorButton: BarButtonItem = { let button = BarButtonItem(image: #imageLiteral(resourceName: "separator"), style: .plain, target: nil, action: nil, tintColorKeyPath: \Theme.colors.chromeText) button.isEnabled = false button.isAccessibilityElement = false return button }() @objc private func progress(_ sender: UIBarButtonItem) { delegate?.sectionEditorNavigationItemController(self, didTapProgressButton: sender) } @objc private func close(_ sender: UIBarButtonItem) { delegate?.sectionEditorNavigationItemController(self, didTapCloseButton: sender) } @objc private func undo(_ sender: UIBarButtonItem) { delegate?.sectionEditorNavigationItemController(self, didTapUndoButton: undoButton) } @objc private func redo(_ sender: UIBarButtonItem) { delegate?.sectionEditorNavigationItemController(self, didTapRedoButton: sender) } @objc private func showReadingThemesControls(_ sender: UIBarButtonItem) { delegate?.sectionEditorNavigationItemController(self, didTapReadingThemesControlsButton: sender) } private func configureNavigationButtonItems() { let closeButton = BarButtonItem(image: #imageLiteral(resourceName: "close"), style: .plain, target: self, action: #selector(close(_ :)), tintColorKeyPath: \Theme.colors.chromeText) closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel navigationItem?.leftBarButtonItem = closeButton navigationItem?.rightBarButtonItems = [ progressButton, UIBarButtonItem.wmf_barButtonItem(ofFixedWidth: 20), separatorButton, UIBarButtonItem.wmf_barButtonItem(ofFixedWidth: 20), readingThemesControlsButton, UIBarButtonItem.wmf_barButtonItem(ofFixedWidth: 20), redoButton, UIBarButtonItem.wmf_barButtonItem(ofFixedWidth: 20), undoButton ] } func textSelectionDidChange(isRangeSelected: Bool) { undoButton.isEnabled = true redoButton.isEnabled = true progressButton.isEnabled = true } func disableButton(button: SectionEditorButton) { switch button.kind { case .undo: undoButton.isEnabled = false case .redo: redoButton.isEnabled = false case .progress: progressButton.isEnabled = false default: break } } }
mit
bf501906b41ae62da46fc3b03af75cbc
46.455172
282
0.710798
5.787216
false
false
false
false
FotiosTragopoulos/Core-Geometry
Core Geometry/Par3ViewFilling.swift
1
1936
// // Par3ViewFilling.swift // Core Geometry // // Created by Fotios Tragopoulos on 13/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Par3ViewFilling: UIView { override func draw(_ rect: CGRect) { let filling = UIGraphicsGetCurrentContext() let xView = viewWithTag(7)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(7)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(7)?.frame.size.width let height = self.viewWithTag(7)?.frame.size.height let size = CGSize(width: width! * 0.6, height: height! * 0.4) let linePlacementX = CGFloat(size.width/2) let linePlacementY = CGFloat(size.height/2) let myShadowOffset = CGSize (width: 10, height: 10) filling?.setShadow (offset: myShadowOffset, blur: 8) filling?.saveGState() filling?.move(to: CGPoint(x: (xView! - (linePlacementX * 1.3)), y: (yView! + (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 0.7)), y: (yView! + (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 1.3)), y: (yView! - (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 0.7)), y: (yView! - (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 1.3)), y: (yView! + (linePlacementY * 1.2)))) filling?.setFillColor(UIColor.white.cgColor) filling?.fillPath() filling?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
apache-2.0
8957b1e6e99507375a676252d90a2f44
42.977273
219
0.625323
3.616822
false
false
false
false
coodly/TalkToCloud
Sources/TalkToCloud/URL+Extensions.swift
1
994
/* * Copyright 2020 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation extension URL { internal func appending(param: String, value: String) -> URL { let append = "\(param)=\(value.ckEncoded)" var string = absoluteString if string.range(of: "?") == nil { string.append("?") } else { string.append("&") } string.append(append) return URL(string: string)! } }
apache-2.0
e3d225244b383ee3b691f97d26c60d5b
30.0625
75
0.651911
4.340611
false
false
false
false
google/android-auto-companion-ios
Sources/AndroidAutoConnectedDeviceManager/KeychainSecureSessionManager.swift
1
3894
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import AndroidAutoLogger import Foundation /// A class that stores secure session information in the keychain. class KeychainSecureSessionManager: NSObject { private static let log = Logger(for: KeychainSecureSessionManager.self) private func secureSessionKey(for identifier: String) -> Data { return Data("com.google.ios.aae.trustagentclient.secureSessionKey.\(identifier)".utf8) } /// The query to retrieve a saved secure connection for a car. /// /// This query does not consider the access mode because it is not considered for /// uniqueness. However, storing the secure session will have access mode set. /// /// - Parameter identifier: The identifier of the car. /// - Returns: The query dictionary. private func secureSessionGetQuery(for identifier: String) -> [String: Any] { return [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: secureSessionKey(for: identifier), kSecReturnData as String: true, ] } /// The query to store a secure session for a car. /// /// - Parameters: /// - secureSession: The session to save. /// - identifier: The identifier of the car. /// - Returns: The query dictionary. private func secureSessionAddQuery(secureSession: Data, identifier: String) -> [String: Any] { return [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: secureSessionKey(for: identifier), kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, kSecValueData as String: secureSession, ] } } // MARK: - SecureSessionManager extension KeychainSecureSessionManager: SecureSessionManager { /// The stored secure session for a given car or `nil` if none has been saved. /// /// - Parameter identifier: The identifier of the car. /// - Returns: A `Data` object containing the secure session of `nil` if there was an error. func secureSession(for identifier: String) -> Data? { var item: CFTypeRef? let status = SecItemCopyMatching( secureSessionGetQuery(for: identifier) as CFDictionary, &item ) guard status == errSecSuccess else { Self.log.error("Unable to secure session; err: \(status)") return nil } return item as? Data } /// Stores the given `Data` objects as a secure session for a car. /// /// - Parameters: /// - secureSession: The session to save. /// - identifier: The identifier for the car. /// - Returns: `true` if the operation was successful. func storeSecureSession(_ secureSession: Data, for identifier: String) -> Bool { // Avoid storing duplicate keys by checking if there is already an entry and deleting it. clearSecureSession(for: identifier) let addQuery = secureSessionAddQuery(secureSession: secureSession, identifier: identifier) let status = SecItemAdd(addQuery as CFDictionary, nil) guard status == errSecSuccess else { Self.log.error("Unable to store secure session; err: \(status)") return false } return true } /// Clears any stored secure sessions for the given car. /// /// - Parameter identifier: the identifier of the car. func clearSecureSession(for identifier: String) { SecItemDelete(secureSessionGetQuery(for: identifier) as CFDictionary) } }
apache-2.0
ea6be26d4f34726da12994d4ae762fc7
35.735849
96
0.712635
4.533178
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Support/UIColor.swift
1
3180
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit extension UIColor { /** Returns a new color which is the average of 2 of the colors. scale can be a number between 0 to 1 otherwise the start or end color is returned respectively */ static func averageColor(start: UIColor, end: UIColor, scale: CGFloat = 0.5) -> UIColor { guard scale > 0 else { return start } guard scale < 1 else { return end } guard let sComp = start.componentsRGBA, let eComp = end.componentsRGBA else { return start } let red = CGFloat.scaledAverage(x: sComp.red, y: eComp.red, scale: scale) let green = CGFloat.scaledAverage(x: sComp.green, y: eComp.green, scale: scale) let blue = CGFloat.scaledAverage(x: sComp.blue, y: eComp.blue, scale: scale) let alpha = CGFloat.scaledAverage(x: sComp.alpha, y: eComp.alpha, scale: scale) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } func average(with other: UIColor, scale: CGFloat = 0.5) -> UIColor { return .averageColor(start: self, end: other, scale: scale) } // swiftlint:disable large_tuple var componentsRGBA: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)? { var (red, green, blue, alpha) = (CGFloat(0.0), CGFloat(0.0), CGFloat(0.0), CGFloat(0.0)) guard getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return nil } return (red, green, blue, alpha) } /** Init a color with a hex value Format: 0xXXXXXX */ convenience init(hex: Int) { self.init(red: CGFloat( (hex & 0xFF0000) >> 16 ) / 255.0, green: CGFloat( (hex & 0x00FF00) >> 8 ) / 255.0, blue: CGFloat( (hex & 0x0000FF) >> 0 ) / 255.0, alpha: 1) } }
bsd-3-clause
3a7c6e91961bb11d77034dec1413ea67
40.285714
97
0.696131
3.919852
false
false
false
false
aucl/YandexDiskKit
YandexDiskKit/YandexDiskKit/YDisk+Version.swift
1
3153
// // YDisk+Version.swift // // Copyright (c) 2014-2015, Clemens Auer // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation extension YandexDisk { public enum APIVersionResult { case Done(build: String, version: String) case Failed(NSError!) } /// Yandex Disk API version and build implemented. /// /// This returns the highest version of yandex disk API which is fully implemented in this SDK. /// /// :returns: The tuple `(build: String, version: String)` public func apiVersionImplemented() -> (build: String, version: String) { return (build: "2.6.37", version: "v1") } /// Yandex Disk backend API version and build. /// /// :param: handler Optional. /// :returns: `APIVersionResult` future. /// /// API reference: *undocumented* public func apiVersion(handler:((result:APIVersionResult) -> Void)? = nil) -> Result<APIVersionResult> { let result = Result<APIVersionResult>(handler: handler) var url = "\(baseURL)/" let error = { result.set(.Failed($0)) } session.jsonTaskWithURL(url, errorHandler: error) { (jsonRoot, response)->Void in switch response.statusCode { case 200: if let build = jsonRoot["build"] as? String, version = jsonRoot["api_version"] as? String { return result.set(.Done(build: build, version: version)) } else { return error(NSError(domain: "YDisk", code: response.statusCode, userInfo: ["response":response, "json":jsonRoot])) } default: return error(NSError(domain: "YDisk", code: response.statusCode, userInfo: ["response":response])) } }.resume() return result } }
bsd-2-clause
3b162bc6ebd0110fd26eb8a1fa63923f
38.911392
135
0.658738
4.491453
false
false
false
false
cafielo/iOS_BigNerdRanch_5th
Chap6_WorldTrotter_bronze_silver_gold/ConversionViewController.swift
4
1861
// // ConversionViewController.swift // WorldTrotter // // Created by Joonwon Lee on 7/17/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class ConversionViewController: UIViewController { @IBOutlet weak var celsiusLabel: UILabel! @IBOutlet weak var textField: UITextField! var fahrenheitValue: Double? var celsiusValue: Double? { didSet { updateCelsiusLabel() } } let numberFormatter: NSNumberFormatter = { let nf = NSNumberFormatter() nf.numberStyle = .DecimalStyle nf.minimumFractionDigits = 0 nf.maximumFractionDigits = 1 return nf }() override func viewDidLoad() { super.viewDidLoad() } func updateCelsiusLabel() { if let value = celsiusValue { celsiusLabel.text = numberFormatter.stringFromNumber(value) } else { celsiusLabel.text = "???" } } @IBAction func fahrenheitFieldEditingChanged(textField: UITextField) { if let text = textField.text, value = Double(text) { fahrenheitValue = value } else { fahrenheitValue = nil } } @IBAction func disissKeyboard(sender: AnyObject) { textField.resignFirstResponder() } } extension ConversionViewController: UITextFieldDelegate { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let existingTextHasDecimalSeparator = textField.text?.rangeOfString(".") let replacementTextHasDecimalSeparator = string.rangeOfString(".") if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil { return false } else { return true } } }
mit
cf1c3bb7f5e9da761d504de681ab2c81
27.181818
132
0.632796
5.329513
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Live/Controller/LiveViewController.swift
1
3166
// // LiveViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/2/25. // Copyright © 2016年 ming. All rights reserved. // 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles // github: https://github.com/LYM-mg import UIKit private let kTitlesViewH : CGFloat = 44 class LiveViewController: UIViewController { var isFirst: Bool = false // MARK:- life cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white automaticallyAdjustsScrollViewInsets = false // 1.创建UI setUpMainView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) liveTitlesView.isHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) liveTitlesView.isHidden = true } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - lazy fileprivate lazy var liveTitlesView: HomeTitlesView = { [weak self] in let titleFrame = CGRect(x: 0, y: 0, width: kScreenW, height: kTitlesViewH) let titles = ["全部","颜值", "体育","游戏","科技"] let tsView = HomeTitlesView(frame: titleFrame, titles: titles) tsView.deledate = self return tsView }() fileprivate lazy var liveContentView: HomeContentView = { [weak self] in // 1.确定内容的frame let contentH = kScreenH - MGNavHeight let contentFrame = CGRect(x: 0, y: MGNavHeight, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(AllListViewController()) childVcs.append(FaceScoreViewController()) childVcs.append(SportViewController()) childVcs.append(HotGameViewController()) childVcs.append(ScienceViewController()) let contentView = HomeContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self return contentView }() } // MARK: - 初始化UI extension LiveViewController { fileprivate func setUpMainView() { setUpNavgationBar() view.addSubview(liveContentView) } fileprivate func setUpNavgationBar() { navigationItem.title = "" navigationController?.navigationBar.addSubview(liveTitlesView) liveTitlesView.backgroundColor = UIColor(r: 250, g: 250, b: 250, a: 0.01) } } // MARK:- 遵守 HomeTitlesViewDelegate 协议 extension LiveViewController : HomeTitlesViewDelegate { func HomeTitlesViewDidSetlected(_ homeTitlesView: HomeTitlesView, selectedIndex: Int) { liveContentView.setCurrentIndex(selectedIndex) } } // MARK:- 遵守 HomeContentViewDelegate 协议 extension LiveViewController : HomeContentViewDelegate { func HomeContentViewDidScroll(_ contentView: HomeContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { liveTitlesView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
05890c2886d8c0067d6192a0c4e22b0e
31.776596
122
0.679
4.675266
false
false
false
false
gregomni/swift
test/SILGen/objc_imported_generic.swift
2
7806
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic %s | %FileCheck %s // For integration testing, ensure we get through IRGen too. // RUN: %target-swift-emit-ir(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -verify -DIRGEN_INTEGRATION_TEST %s // REQUIRES: objc_interop import objc_generics func callInitializer() { _ = GenericClass(thing: NSObject()) } // CHECK-LABEL: sil shared [serialized] [ossa] @$sSo12GenericClassC5thingAByxGSgxSg_tcfC // CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject { return o.thing!()! } // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C17MethodOnAnyObject{{[_0-9a-zA-Z]*}}F // CHECK: objc_method {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject> public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? { return o.thing?() } // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF // CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool): // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign, bb1 // CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>): // CHECK: } // end sil function '$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF' public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? { return o[0 as UInt16] } // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF // CHECK: bb0([[ANY:%.*]] // CHCEK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.foreign, bb1 // CHECK: bb1({{%.*}} : $@convention(objc_method) (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject): // CHECK: } // end sil function '$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF' public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? { return o.propertyThing } // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF // CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool): // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.foreign, bb1 // CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>): // CHECK: } // end sil function '$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF' public protocol ThingHolder { associatedtype Thing init!(thing: Thing!) func thing() -> Thing? func arrayOfThings() -> [Thing] func setArrayOfThings(_: [Thing]) static func classThing() -> Thing? var propertyThing: Thing? { get set } var propertyArrayOfThings: [Thing]? { get set } } public protocol Ansible: class { associatedtype Anser: ThingHolder } public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) { let block = x.blockForPerformingOnThings() x.performBlock(onThings: block) } // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C13BlockBridging{{[_0-9a-zA-Z]*}}F // CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @$sxxIeyBya_xxIeggo_21objc_imported_generic7AnsibleRzlTR // CHECK: partial_apply [callee_guaranteed] [[BLOCK_TO_FUNC]]<T> // CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @$sxxIeggo_xxIeyBya_21objc_imported_generic7AnsibleRzlTR // CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T> // CHECK-LABEL: sil [ossa] @$s21objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) { // CHECK: function_ref @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>> let x = GenericClass<T>(arrayOfThings: y)! // CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> () x.setArrayOfThings(y) // CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray> _ = x.propertyArrayOfThings // CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> () x.propertyArrayOfThings = y } // CHECK-LABEL: sil private [ossa] @$s21objc_imported_generic0C4FuncyyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () { // CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type // CHECK: [[INIT:%.*]] = function_ref @$sSo12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0> // CHECK: apply [[INIT]]<V>([[META]]) // CHECK: return func genericFunc<V: AnyObject>(_ v: V.Type) { let _ = { var _ = GenericClass<V>() } } // CHECK-LABEL: sil hidden [ossa] @$s21objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> () // CHECK: enum $Optional<Dictionary<GenericOption, Any>>, #Optional.none!enumelt // CHECK: return func configureWithoutOptions() { _ = GenericClass<NSObject>(options: nil) } // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfcTO // CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>> // foreign to native thunk for init(options:), uses GenericOption : Hashable // conformance // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC7optionsAByxGSgSDySo0A6OptionaypGSg_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>> // CHECK: [[FN:%.*]] = function_ref @$sSD10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: return // Make sure we emitted the witness table for the above conformance // CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics { // CHECK: method #Hashable.hashValue!getter: {{.*}}: @$sSo13GenericOptionaSHSCSH9hashValueSivgTW // CHECK: }
apache-2.0
2095591a77de8df1b53056db641fe58c
57.451128
274
0.690764
3.492363
false
false
false
false
sidepelican/swift-toml
Sources/Date.swift
1
2117
/* * Copyright 2016 JD Fergason * * 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 private func buildDateFormatter(format: String) -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = format formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter } private var rfc3339fractionalformatter = buildDateFormatter(format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSZZZZZ") private var rfc3339formatter: DateFormatter = buildDateFormatter(format: "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ") private func localTimeOffset() -> String { let totalSeconds: Int = TimeZone.current.secondsFromGMT() let minutes: Int = (totalSeconds / 60) % 60 let hours: Int = totalSeconds / 3600 return String(format: "%02d%02d", hours, minutes) } extension Date { // rfc3339 w fractional seconds w/ time offset init?(rfc3339String: String, fractionalSeconds: Bool = true, localTime: Bool = false) { var dateStr = rfc3339String var dateFormatter: DateFormatter if localTime { dateStr += localTimeOffset() } dateFormatter = fractionalSeconds ? rfc3339fractionalformatter : rfc3339formatter if let d = dateFormatter.date(from: dateStr) { self.init(timeInterval: 0, since: d) } else { return nil } } func rfc3339String() -> String { return rfc3339fractionalformatter.string(from: self) } }
apache-2.0
b8faa0ced7c22c8a957480d7b34f37b1
31.569231
91
0.685404
4.311609
false
false
false
false
icanzilb/RealmNotificationExample
Pods/RealmSwift/RealmSwift/RealmCollection.swift
2
61437
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm #if swift(>=3.0) /** An iterator for a `RealmCollection` instance. */ public final class RLMIterator<T: Object>: IteratorProtocol { private var i: UInt = 0 private let generatorBase: NSFastEnumerationIterator init(collection: RLMCollection) { generatorBase = NSFastEnumerationIterator(collection) } /// Advance to the next element and return it, or `nil` if no next element exists. public func next() -> T? { // swiftlint:disable:this valid_docs let accessor = unsafeBitCast(generatorBase.next() as! Object?, to: Optional<T>.self) if let accessor = accessor { RLMInitializeSwiftAccessorGenerics(accessor) } return accessor } } /** A `RealmCollectionChange` value encapsulates information about changes to collections that are reported by Realm notifications. The change information is available in two formats: a simple array of row indices in the collection for each type of change, and an array of index paths in a requested section suitable for passing directly to `UITableView`'s batch update methods. The arrays of indices in the `.Update` case follow `UITableView`'s batching conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths. For example, for a simple one-section table view, you can do the following: ```swift self.notificationToken = results.addNotificationBlock { changes in switch changes { case .initial: // Results are now populated and can be accessed without blocking the UI self.tableView.reloadData() break case .update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the TableView self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.endUpdates() break case .error(let err): // An error occurred while opening the Realm file on the background worker thread fatalError("\(err)") break } } ``` */ public enum RealmCollectionChange<T> { /** `.initial` indicates that the initial run of the query has completed (if applicable), and the collection can now be used without performing any blocking work. */ case initial(T) /** `.update` indicates that a write transaction has been committed which either changed which objects are in the collection, and/or modified one or more of the objects in the collection. All three of the change arrays are always sorted in ascending order. - parameter deletions: The indices in the previous version of the collection which were removed from this one. - parameter insertions: The indices in the new collection which were added in this version. - parameter modifications: The indices of the objects in the new collection which were modified in this version. */ case update(T, deletions: [Int], insertions: [Int], modifications: [Int]) /** If an error occurs, notification blocks are called one time with a `.error` result and an `NSError` containing details about the error. This can only currently happen if the Realm is opened on a background worker thread to calculate the change set. */ case error(Error) static func fromObjc(value: T, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange { if let error = error { return .error(error) } if let change = change { return .update(value, deletions: change.deletions as [Int], insertions: change.insertions as [Int], modifications: change.modifications as [Int]) } return .initial(value) } } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollection: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible { /// The type of the objects contained in the collection. associatedtype Element: Object // MARK: Properties /// The Realm which manages the collection, or `nil` for unmanaged collections. var realm: Realm? { get } /** Indicates if the collection can no longer be accessed. The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection. */ var isInvalidated: Bool { get } /// The number of objects in the collection. var count: Int { get } /// A human-readable description of the objects contained in the collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of an object in the collection, or `nil` if the object is not present. - parameter object: An object. */ func index(of object: Element) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate to use to filter the objects. */ func index(matching predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func index(matching predicateFormat: String, _ args: Any...) -> Int? // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate to use to filter the objects. */ func filter(_ predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ func sorted(byProperty property: String, ascending: Bool) -> Results<Element> /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byProperty:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ func min<U: MinMaxType>(ofProperty property: String) -> U? /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ func max<U: MinMaxType>(ofProperty property: String) -> U? /** Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. */ func sum<U: AddableType>(ofProperty property: String) -> U /** Returns the sum of the values of a given property over all the objects in the collection. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ func average<U: AddableType>(ofProperty property: String) -> U? // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ func value(forKey key: String) -> Any? /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ func value(forKeyPath keyPath: String) -> Any? /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ func setValue(_ value: Any?, forKey key: String) // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken /// :nodoc: func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken } private class _AnyRealmCollectionBase<T: Object> { typealias Wrapper = AnyRealmCollection<Element> typealias Element = T var realm: Realm? { fatalError() } var isInvalidated: Bool { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func index(of object: Element) -> Int? { fatalError() } func index(matching predicate: NSPredicate) -> Int? { fatalError() } func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() } func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() } func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(byProperty property: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { fatalError() } func min<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() } func max<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() } func sum<U: AddableType>(ofProperty property: String) -> U { fatalError() } func average<U: AddableType>(ofProperty property: String) -> U? { fatalError() } subscript(position: Int) -> Element { fatalError() } func makeIterator() -> RLMIterator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func value(forKey key: String) -> Any? { fatalError() } func value(forKeyPath keyPath: String) -> Any? { fatalError() } func setValue(_ value: Any?, forKey key: String) { fatalError() } func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { fatalError() } } private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } // MARK: Properties override var realm: Realm? { return base.realm } override var isInvalidated: Bool { return base.isInvalidated } override var count: Int { return base.count } override var description: String { return base.description } // MARK: Index Retrieval override func index(of object: C.Element) -> Int? { return base.index(of: object) } override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) } override func index(matching predicateFormat: String, _ args: Any...) -> Int? { return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting override func sorted(byProperty property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(byProperty: property, ascending: ascending) } override func sorted<S: Sequence> (by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor { return base.sorted(by: sortDescriptors) } // MARK: Aggregate Operations override func min<U: MinMaxType>(ofProperty property: String) -> U? { return base.min(ofProperty: property) } override func max<U: MinMaxType>(ofProperty property: String) -> U? { return base.max(ofProperty: property) } override func sum<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) } override func average<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) } // MARK: Sequence Support override subscript(position: Int) -> C.Element { // FIXME: it should be possible to avoid this force-casting return unsafeBitCast(base[position as! C.Index], to: C.Element.self) } override func makeIterator() -> RLMIterator<Element> { // FIXME: it should be possible to avoid this force-casting return base.makeIterator() as! RLMIterator<Element> } // MARK: Collection Support override var startIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.startIndex as! Int } override var endIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.endIndex as! Int } // MARK: Key-Value Coding override func value(forKey key: String) -> Any? { return base.value(forKey: key) } override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) } override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /// :nodoc: override func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } /** A type-erased `RealmCollection`. Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type. */ public final class AnyRealmCollection<T: Object>: RealmCollection { public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// The type of the objects contained in the collection. public typealias Element = T private let base: _AnyRealmCollectionBase<T> /// Creates an `AnyRealmCollection` wrapping `base`. public init<C: RealmCollection>(_ base: C) where C.Element == T { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm which manages the collection, or `nil` if the collection is unmanaged. public var realm: Realm? { return base.realm } /** Indicates if the collection can no longer be accessed. The collection can no longer be accessed if `invalidate()` is called on the containing `realm`. */ public var isInvalidated: Bool { return base.isInvalidated } /// The number of objects in the collection. public var count: Int { return base.count } /// A human-readable description of the objects contained in the collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: An object. */ public func index(of object: Element) -> Int? { return base.index(of: object) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. - returns: A `Results` containing objects that match the given predicate. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byProperty property: String, ascending: Bool) -> Results<Element> { return base.sorted(byProperty: property, ascending: ascending) } /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byProperty:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return base.sorted(by: sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return base.min(ofProperty: property) } /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return base.max(ofProperty: property) } /** Returns the sum of the values of a given property over all the objects in the collection. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) } /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> T { return base[position] } /// Returns a `RLMIterator` that yields successive elements in the collection. public func makeIterator() -> RLMIterator<T> { return base.makeIterator() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return base.startIndex } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return base.endIndex } // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ public func value(forKey key: String) -> Any? { return base.value(forKey: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } // MARK: Unavailable extension AnyRealmCollection { @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byProperty:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } } #else /** An iterator for a `RealmCollectionType` instance. */ public final class RLMGenerator<T: Object>: GeneratorType { private let generatorBase: NSFastGenerator internal init(collection: RLMCollection) { generatorBase = NSFastGenerator(collection) } /// Advance to the next element and return it, or `nil` if no next element exists. public func next() -> T? { // swiftlint:disable:this valid_docs let accessor = unsafeBitCast(generatorBase.next() as! Object?, Optional<T>.self) if let accessor = accessor { RLMInitializeSwiftAccessorGenerics(accessor) } return accessor } } /** A `RealmCollectionChange` value encapsulates information about changes to collections that are reported by Realm notifications. The change information is available in two formats: a simple array of row indices in the collection for each type of change, and an array of index paths in a requested section suitable for passing directly to `UITableView`'s batch update methods. The arrays of indices in the `.Update` case follow `UITableView`'s batching conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths. For example, for a simple one-section table view, you can do the following: ```swift self.notificationToken = results.addNotificationBlock { changes in switch changes { case .Initial: // Results are now populated and can be accessed without blocking the UI self.tableView.reloadData() break case .Update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the TableView self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.endUpdates() break case .Error(let err): // An error occurred while opening the Realm file on the background worker thread fatalError("\(err)") break } } ``` */ public enum RealmCollectionChange<T> { /// `.Initial` indicates that the initial run of the query has completed (if applicable), and the /// collection can now be used without performing any blocking work. case Initial(T) /// `.Update` indicates that a write transaction has been committed which either changed which objects /// are in the collection, and/or modified one or more of the objects in the collection. /// /// All three of the change arrays are always sorted in ascending order. /// /// - parameter deletions: The indices in the previous version of the collection /// which were removed from this one. /// - parameter insertions: The indices in the new collection which were added in /// this version. /// - parameter modifications: The indices of the objects in the new collection which /// were modified in this version. case Update(T, deletions: [Int], insertions: [Int], modifications: [Int]) /// If an error occurs, notification blocks are called one time with a /// `.Error` result and an `NSError` containing details about the error. This can only currently happen if the /// Realm is opened on a background worker thread to calculate the change set. case Error(NSError) static func fromObjc(value: T, change: RLMCollectionChange?, error: NSError?) -> RealmCollectionChange { if let error = error { return .Error(error) } if let change = change { return .Update(value, deletions: change.deletions as! [Int], insertions: change.insertions as! [Int], modifications: change.modifications as! [Int]) } return .Initial(value) } } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollectionType: CollectionType, CustomStringConvertible { /// The type of the objects contained in the collection. associatedtype Element: Object // MARK: Properties /// The Realm which manages the collection, or `nil` for unmanaged collections. var realm: Realm? { get } /// Indicates if the collection can no longer be accessed. /// /// The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection. var invalidated: Bool { get } /// The number of objects in the collection. var count: Int { get } /// A human-readable description of the objects contained in the collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of an object in the collection, or `nil` if the object is not present. - parameter object: An object. */ func indexOf(object: Element) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate to use to filter the objects. */ func indexOf(predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? // MARK: Filtering /** Returns all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> /** Returns all objects matching the given predicate in the collection. - parameter predicate: The predicate to use to filter the objects. */ func filter(predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ func sorted(byProperty: String, ascending: Bool) -> Results<Element> /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byProperty:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ func min<U: MinMaxType>(property: String) -> U? /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ func max<U: MinMaxType>(property: String) -> U? /** Returns the sum of the values of a given property over all the objects represented by the collection. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ func sum<U: AddableType>(property: String) -> U /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ func average<U: AddableType>(property: String) -> U? // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ func valueForKey(key: String) -> AnyObject? /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ func valueForKeyPath(keyPath: String) -> AnyObject? /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ func setValue(value: AnyObject?, forKey key: String) // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .Initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ func addNotificationBlock(block: (RealmCollectionChange<Self>) -> Void) -> NotificationToken /// :nodoc: func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken } private class _AnyRealmCollectionBase<T: Object> { typealias Wrapper = AnyRealmCollection<Element> typealias Element = T var realm: Realm? { fatalError() } var invalidated: Bool { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func indexOf(object: Element) -> Int? { fatalError() } func indexOf(predicate: NSPredicate) -> Int? { fatalError() } func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() } func filter(predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { fatalError() } func min<U: MinMaxType>(property: String) -> U? { fatalError() } func max<U: MinMaxType>(property: String) -> U? { fatalError() } func sum<U: AddableType>(property: String) -> U { fatalError() } func average<U: AddableType>(property: String) -> U? { fatalError() } subscript(index: Int) -> Element { fatalError() } func generate() -> RLMGenerator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func valueForKey(key: String) -> AnyObject? { fatalError() } func valueForKeyPath(keyPath: String) -> AnyObject? { fatalError() } func setValue(value: AnyObject?, forKey key: String) { fatalError() } func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { fatalError() } } private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } override var realm: Realm? { return base.realm } override var invalidated: Bool { return base.invalidated } override var count: Int { return base.count } override var description: String { return base.description } // MARK: Index Retrieval override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) } override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting override func sorted(property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(property, ascending: ascending) } override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<C.Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } override func sum<U: AddableType>(property: String) -> U { return base.sum(property) } override func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support override subscript(index: Int) -> C.Element { // FIXME: it should be possible to avoid this force-casting return unsafeBitCast(base[index as! C.Index], C.Element.self) } override func generate() -> RLMGenerator<Element> { // FIXME: it should be possible to avoid this force-casting return base.generate() as! RLMGenerator<Element> } // MARK: Collection Support override var startIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.startIndex as! Int } override var endIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.endIndex as! Int } // MARK: Key-Value Coding override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } override func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) } override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /// :nodoc: override func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } /** A type-erased `RealmCollectionType`. Instances of `RealmCollectionType` forward operations to an opaque underlying collection having the same `Element` type. */ public final class AnyRealmCollection<T: Object>: RealmCollectionType { /// The type of the objects contained in the collection. public typealias Element = T private let base: _AnyRealmCollectionBase<T> /// Creates an `AnyRealmCollection` wrapping `base`. public init<C: RealmCollectionType where C.Element == T>(_ base: C) { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm which manages this collection, or `nil` if the collection is unmanaged. public var realm: Realm? { return base.realm } /// Indicates if the collection can no longer be accessed. /// /// The collection can no longer be accessed if `invalidate()` is called on the containing `realm`. public var invalidated: Bool { return base.invalidated } /// The number of objects in the collection. public var count: Int { return base.count } /// A human-readable description of the objects contained in the collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: An object. */ public func indexOf(object: Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted("age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(property: String, ascending: Bool) -> Results<Element> { return base.sorted(property, ascending: ascending) } /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(_:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the values of a given property over all the objects in the collection. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: An index to retrieve or set an object from. */ public subscript(index: Int) -> T { return base[index] } /// Returns an `RLMGenerator` that yields successive elements in the collection. public func generate() -> RLMGenerator<T> { return base.generate() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to `endIndex` in an empty collection. public var startIndex: Int { return base.startIndex } /// The collection's "past the end" position. /// `endIndex` is not a valid argument to `subscript`, and is always reachable from `startIndex` by /// zero or more applications of `successor()`. public var endIndex: Int { return base.endIndex } // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .Initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } /// :nodoc: public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } #endif
mit
a9dc603d1d2d34f3fa850f8a5404ddbc
38.816591
132
0.680795
4.789662
false
false
false
false
CryptoKitten/CryptoEssentials
Sources/Utils.swift
1
3468
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. public func rotateLeft(_ v:UInt8, _ n:UInt8) -> UInt8 { return ((v << n) & 0xFF) | (v >> (8 - n)) } public func rotateLeft(_ v:UInt16, _ n:UInt16) -> UInt16 { return ((v << n) & 0xFFFF) | (v >> (16 - n)) } public func rotateLeft(_ v:UInt32, _ n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } public func rotateLeft(_ x:UInt64, _ n:UInt64) -> UInt64 { return (x << n) | (x >> (64 - n)) } public func rotateRight(_ x:UInt16, n:UInt16) -> UInt16 { return (x >> n) | (x << (16 - n)) } public func rotateRight(_ x:UInt32, n:UInt32) -> UInt32 { return (x >> n) | (x << (32 - n)) } public func rotateRight(_ x:UInt64, n:UInt64) -> UInt64 { return ((x >> n) | (x << (64 - n))) } public func reverseBytes(_ value: UInt32) -> UInt32 { return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24); } public func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) { let val1:UInt32 = (UInt32(slice[idx.advanced(by: 3)]) << 24) let val2:UInt32 = (UInt32(slice[idx.advanced(by: 2)]) << 16) let val3:UInt32 = (UInt32(slice[idx.advanced(by: 1)]) << 8) let val4:UInt32 = UInt32(slice[idx]) let val:UInt32 = val1 | val2 | val3 | val4 result.append(val) } return result } public func toUInt64Array(_ slice: ArraySlice<UInt8>) -> Array<UInt64> { var result = Array<UInt64>() result.reserveCapacity(32) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt64>.size) { var val:UInt64 = 0 val |= UInt64(slice[idx.advanced(by: 7)]) << 56 val |= UInt64(slice[idx.advanced(by: 6)]) << 48 val |= UInt64(slice[idx.advanced(by: 5)]) << 40 val |= UInt64(slice[idx.advanced(by: 4)]) << 32 val |= UInt64(slice[idx.advanced(by: 3)]) << 24 val |= UInt64(slice[idx.advanced(by: 2)]) << 16 val |= UInt64(slice[idx.advanced(by: 1)]) << 8 val |= UInt64(slice[idx.advanced(by: 0)]) << 0 result.append(val) } return result } public func xor(_ a: [UInt8], _ b:[UInt8]) -> [UInt8] { var xored = [UInt8](repeating: 0, count: min(a.count, b.count)) for i in 0..<xored.count { xored[i] = a[i] ^ b[i] } return xored }
mit
3bf73841f2bbc59a7e1a4c3034bbde32
39.302326
216
0.630987
3.279092
false
false
false
false
taiphamtiki/TikiTool
TikiTool/Manager/FirebaseManager.swift
1
986
// // FirebaseManager.swift // TikiTool // // Created by ZickOne on 2/9/17. // Copyright © 2017 ZickOne. All rights reserved. // import Foundation import Firebase class FirebaseManager: NSObject { static let shareInsstance = FirebaseManager() let deeplinkReef = FIRDatabase.database().reference().child("deeplinks") func getDeepLink(_ onCompletion:@escaping ([BoxItem]) -> Void) { deeplinkReef.observe(FIRDataEventType.value, with: { snapshot in if snapshot.value == nil { onCompletion([]) } var deepLink = [BoxItem]() for value in snapshot.children { let child = value as! FIRDataSnapshot let dict = child.value as! NSDictionary let deeplink = BoxItem(name: dict["title"] as! String, link: dict["link"] as! String,false) deepLink += [deeplink] } onCompletion(deepLink) }) } }
mit
13fc12e49abb06505c594f62c78faa12
29.78125
107
0.583756
4.602804
false
false
false
false
cardstream/iOS-SDK
cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/Generics.swift
7
2403
// // Generics.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** build bit pattern from array of bits */ @_specialize(exported: true, where T == UInt8) func integerFrom<T: FixedWidthInteger>(_ bits: Array<Bit>) -> T { var bitPattern: T = 0 for idx in bits.indices { if bits[idx] == Bit.one { let bit = T(UInt64(1) << UInt64(idx)) bitPattern = bitPattern | bit } } return bitPattern } /// Array of bytes. Caution: don't use directly because generic is slow. /// /// - parameter value: integer value /// - parameter length: length of output array. By default size of value type /// /// - returns: Array of bytes @_specialize(exported: true, where T == Int) @_specialize(exported: true, where T == UInt) @_specialize(exported: true, where T == UInt8) @_specialize(exported: true, where T == UInt16) @_specialize(exported: true, where T == UInt32) @_specialize(exported: true, where T == UInt64) func arrayOfBytes<T: FixedWidthInteger>(value: T, length totalBytes: Int = MemoryLayout<T>.size) -> Array<UInt8> { let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer)) var bytes = Array<UInt8>(repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes }
gpl-3.0
4be7132c7f00172e7e46e48f7cd66b60
41.892857
217
0.70816
4.141379
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/Moya/Sources/Moya/MultipartFormData.swift
43
834
import Foundation /// Represents "multipart/form-data" for an upload. public struct MultipartFormData { /// Method to provide the form data. public enum FormDataProvider { case data(Foundation.Data) case file(URL) case stream(InputStream, UInt64) } /// Initialize a new `MultipartFormData`. public init(provider: FormDataProvider, name: String, fileName: String? = nil, mimeType: String? = nil) { self.provider = provider self.name = name self.fileName = fileName self.mimeType = mimeType } /// The method being used for providing form data. public let provider: FormDataProvider /// The name. public let name: String /// The file name. public let fileName: String? /// The MIME type public let mimeType: String? }
apache-2.0
d0b744c2f39b51b6e5927689e8ec9bec
25.0625
109
0.648681
4.607735
false
false
false
false
sigmonky/hearthechanges
Experiments.playground/Contents.swift
1
2746
//: Playground - noun: a place where people can play import UIKit let MIDIC = 60 extension Bool: IntValue { func intValue() -> Int { if self { return 1 } return 0 } } protocol IntValue { func intValue() -> Int } func getChord(input:Array<Int>, offset:Int = 0,flat:Bool = false)->[String] { return input.map({ (value:Int) -> String in let chordIdentity = [["I"],["#I","b2"],["II"],["#2","bIII"],["III"],["IV"],["#IV","bV"],["V"],["#V","bVI"],["VI"],["#VI","bVII"],["VII"]] var adjustedOffset = (value + offset) % 12 if adjustedOffset < 0 { adjustedOffset = 12 + adjustedOffset } var currentSolfege:String = "" if adjustedOffset >= 0 && adjustedOffset < chordIdentity.count { if chordIdentity[adjustedOffset].count > 1 { currentSolfege = chordIdentity[adjustedOffset][0 + flat.intValue()] } else { currentSolfege = chordIdentity[adjustedOffset][0] } } return currentSolfege }) } getChord(input: [0,4,7],offset:0) enum ColorName: String { case black, silver, gray, white, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua } let x:String = ColorName.teal.rawValue enum ChordQuality { case Major case Minor case Diminished case Augmented case Dominant case Suspended func members() -> [Int] { var returnArray:[Int] = [0] switch theChord { case .Major: returnArray += [4,7] case .Minor: returnArray += [3,7] case .Diminished: returnArray += [3,6] case .Augmented: returnArray += [4,8] case .Dominant: returnArray += [4,7,10] case.Suspended: returnArray += [5,7] } return returnArray } } var theChord = ChordQuality.Dominant let offset = 63 let transpose = {$0 + offset} let renderedChord = theChord.members().map(transpose) print(renderedChord) let array = [1,2,3,4,5,6] print(array.startIndex) print(array.endIndex) let slice = Array(array[3...5]) print(slice.startIndex) //execute search let isFound: Bool = numberList.binarySearch(forElement: 8) /* do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) print("AVAudioSession Category Playback OK") do { try AVAudioSession.sharedInstance().setActive(true) print("AVAudioSession is Active") } catch let error as NSError { print(error.localizedDescription) } } catch let error as NSError { print(error.localizedDescription) }*/
mit
21e1dab6a457ee1280a0fdbb79954acf
21.694215
145
0.583394
3.962482
false
false
false
false
rudkx/swift
test/Generics/rdar75656022.swift
1
3096
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s protocol P1 { associatedtype T } protocol P2 { associatedtype T : P1 } struct S1<A, B, C> : P2 where A : P1, C : P2, B == A.T.T, C.T == A.T { typealias T = C.T } struct S2<D : P1> : P2 { typealias T = D } // Make sure that we can resolve the nested type A.T // in the same-type requirement 'A.T == B.T'. // // A is concrete, and S1<C, E, S2<D>>.T resolves to // S2<D>.T, which is D. The typealias S1.T has a // structural type 'C.T'; since C is concrete, we // have to handle the case of an unresolved member // type with a concrete base. struct UnresolvedWithConcreteBase<A, B> { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where A == S1<C, E, S2<D>>, B : P2, A.T == B.T, C : P1, D == C.T, E == D.T { } } // Make sure that we drop the conformance requirement // 'A : P2' and rebuild the generic signature with the // correct same-type requirements. // // The original test case in the bug report (correctly) // produces two warnings about redundant requirements. struct OriginalExampleWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, D : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} C.T : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} // expected-note@-1 {{conformance constraint 'D' : 'P1' implied here}} A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without the warnings. struct OriginalExampleWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without unnecessary generic parameters. struct WithoutBogusGenericParametersWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, C.T : P1, // expected-warning {{redundant conformance constraint 'C.T' : 'P1'}} A == S1<C, C.T.T, S2<C.T>> {} } // Same as above but without unnecessary generic parameters // or the warning. struct WithoutBogusGenericParametersWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>> {} }
apache-2.0
a39787aee4d62a8b879ce2347adf4cad
35.857143
143
0.559432
2.584307
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/UserProfile.swift
1
3220
// // UserProfile.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // MARK: UserProfile /** * Information regarding an Uber user. */ @objc(UBSDKUserProfile) public class UserProfile: NSObject, Codable { /// First name of the Uber user. @objc public private(set) var firstName: String? /// Last name of the Uber user. @objc public private(set) var lastName: String? /// Email address of the Uber user. @objc public private(set) var email: String? /// Image URL of the Uber user. @objc public private(set) var picturePath: String? /// Promo code of the Uber user. @objc public private(set) var promoCode: String? /// Unique identifier of the Uber user. Deprecated, use riderID instead. @available(*, deprecated, message:"use riderID instead") @objc public var UUID: String { // This implementation gets rid of the deprecated warning while compiling this SDK. return _UUID } private let _UUID: String /// Unique identifier of the Uber user. @objc public private(set) var riderID: String enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastName = "last_name" case email = "email" case picturePath = "picture" case promoCode = "promo_code" case _UUID = "uuid" case riderID = "rider_id" } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) firstName = try container.decodeIfPresent(String.self, forKey: .firstName) lastName = try container.decodeIfPresent(String.self, forKey: .lastName) email = try container.decodeIfPresent(String.self, forKey: .email) picturePath = try container.decodeIfPresent(String.self, forKey: .picturePath) promoCode = try container.decodeIfPresent(String.self, forKey: .promoCode) _UUID = try container.decode(String.self, forKey: ._UUID) riderID = try container.decode(String.self, forKey: .riderID) } }
mit
5f519a09df4f97c76cddaa6772712de7
40.805195
91
0.69183
4.332436
false
false
false
false
lkzhao/ElasticTransition
ElasticTransitionExample/MenuViewController.swift
1
1086
// // MenuViewController.swift // ElasticTransitionExample // // Created by Luke Zhao on 2015-12-09. // Copyright © 2015 lkzhao. All rights reserved. // import UIKit class MenuViewController: UIViewController, ElasticMenuTransitionDelegate { var contentLength:CGFloat = 320 var dismissByBackgroundTouch = true var dismissByBackgroundDrag = true var dismissByForegroundDrag = true @IBOutlet weak var textView: UITextView! @IBOutlet weak var codeView2: UITextView! override func viewDidLoad() { super.viewDidLoad() let tm = transitioningDelegate as! ElasticTransition textView.text = "transition.edge = .\(tm.edge)\n" + "transition.transformType = .\(tm.transformType)\n" + "transition.sticky = \(tm.sticky)\n" + "transition.showShadow = \(tm.showShadow)" codeView2.text = "let vc = segue.destinationViewController\n" + "vc.transitioningDelegate = transition\n" + "vc.modalPresentationStyle = .Custom\n" } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } }
mit
b0dcd268a80fffecf5bbbfa32767a1d8
30
97
0.722581
4.483471
false
false
false
false
bangslosan/ImagePickerSheetController
ImagePickerSheetController/Example/ViewController.swift
1
3761
// // ViewController.swift // Example // // Created by Laurin Brandner on 26/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit import Photos import ImagePickerSheetController class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() let tapRecognizer = UITapGestureRecognizer(target: self, action: "presentImagePickerSheet:") view.addGestureRecognizer(tapRecognizer) } // MARK: Other Methods func presentImagePickerSheet(gestureRecognizer: UITapGestureRecognizer) { let authorization = PHPhotoLibrary.authorizationStatus() if authorization == .NotDetermined { PHPhotoLibrary.requestAuthorization() { status in dispatch_async(dispatch_get_main_queue()) { self.presentImagePickerSheet(gestureRecognizer) } } return } if authorization == .Authorized { let presentImagePickerController: UIImagePickerControllerSourceType -> () = { source in let controller = UIImagePickerController() controller.delegate = self var sourceType = source if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) { sourceType = .PhotoLibrary println("Fallback to camera roll as a source since the simulator doesn't support taking pictures") } controller.sourceType = sourceType self.presentViewController(controller, animated: true, completion: nil) } let controller = ImagePickerSheetController() controller.addAction(ImageAction(title: NSLocalizedString("Take Photo Or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Add comment", comment: "Action Title"), handler: { _ in presentImagePickerController(.Camera) }, secondaryHandler: { _, numberOfPhotos in println("Comment \(numberOfPhotos) photos") })) controller.addAction(ImageAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title"), $0) as String}, handler: { _ in presentImagePickerController(.PhotoLibrary) }, secondaryHandler: { _, numberOfPhotos in controller.getSelectedImagesWithCompletion() { images in println("Send \(images) photos") } })) controller.addAction(ImageAction(title: NSLocalizedString("Cancel", comment: "Action Title"), style: .Cancel, handler: { _ in println("Cancelled") })) presentViewController(controller, animated: true, completion: nil) } else { let alertView = UIAlertView(title: NSLocalizedString("An error occurred", comment: "An error occurred"), message: NSLocalizedString("ImagePickerSheet needs access to the camera roll", comment: "ImagePickerSheet needs access to the camera roll"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "OK")) alertView.show() } } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
mit
6c64b7a603c5f84e200c922d75afb907
43.77381
331
0.628556
6.257903
false
false
false
false
luanhssa/bookr
Bookr/ProfileViewController.swift
1
2502
// // ProfileViewController.swift // Bookr // // Created by Student on 3/8/17. // Copyright © 2017 Luan Almeida. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var tableView: UITableView! var user = User() func maskRoundedImage(image: UIImage, radius: Float) -> UIImage { let imageView: UIImageView = UIImageView(image: image) var layer: CALayer = CALayer() layer = imageView.layer layer.masksToBounds = true layer.cornerRadius = CGFloat(radius) UIGraphicsBeginImageContext(imageView.bounds.size) let roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage! } override func viewDidLoad() { super.viewDidLoad() user = UserProfile.user userName.text = user.name + " " + user.lastName if let image = user.image { let uiimage = maskRoundedImage(image: UIImage(named: image)!, radius: 45.0) userImage.image = uiimage } tableView.delegate = self tableView.dataSource = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ProfileViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (user.hasManyBooks?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier : String = "userBooksIdentifier" let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) let books = user.hasManyBooks?.allObjects let book = books?[indexPath.row] as! Book cell.textLabel?.text = book.name cell.detailTextLabel?.text = book.author if let image = book.image { cell.imageView?.image = UIImage(named: image) } return cell } }
apache-2.0
51d7608208dbb31fa8eaca85f62cab0d
25.892473
100
0.620152
5.378495
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/Cells/MessageActionsCell.swift
1
1578
// // MessageActionsCell.swift // Rocket.Chat // // Created by Filipe Alvarenga on 22/10/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import RocketChatViewController class MessageActionsCell: BaseMessageCell, SizingCell { static let identifier = String(describing: MessageActionsCell.self) static let sizingCell: UICollectionViewCell & ChatCell = { guard let cell = MessageActionsCell.instantiateFromNib() else { return MessageActionsCell() } return cell }() @IBOutlet weak var replyButton: UIButton! { didSet { let image = UIImage(named: "back")?.imageWithTint(.white, alpha: 0.0) replyButton.setImage(image, for: .normal) replyButton.layer.cornerRadius = 4 replyButton.setTitle(localized("chat.message.actions.reply"), for: .normal) } } override func awakeFromNib() { super.awakeFromNib() insertGesturesIfNeeded(with: nil) } override func configure(completeRendering: Bool) {} @IBAction func buttonReplyDidPressed(sender: Any) { guard let viewModel = viewModel?.base as? MessageActionsChatItem, let message = viewModel.message else { return } delegate?.openReplyMessage(message: message) } } extension MessageActionsCell { override func applyTheme() { super.applyTheme() replyButton.setTitleColor(.white, for: .normal) replyButton.backgroundColor = theme?.actionTintColor } }
mit
806f15e0cfe1c7bc612187e97d110719
26.666667
87
0.649968
4.75
false
false
false
false
velvetroom/columbus
Source/View/CreateTravel/VCreateTravelListCell.swift
1
1461
import UIKit final class VCreateTravelListCell:UICollectionViewCell { private weak var imageView:UIImageView! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.center imageView.clipsToBounds = true self.imageView = imageView addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { imageView.tintColor = UIColor.white } else { imageView.tintColor = UIColor.colourBackgroundDark } } //MARK: internal func config(model:MCreateTravelProtocol) { imageView.image = model.icon.withRenderingMode(UIImageRenderingMode.alwaysTemplate) hover() } }
mit
c809b20b9a4aa335c86e0aa082c832f2
20.173913
91
0.569473
5.820717
false
false
false
false
alucarders/SHSPhoneComponentSwift
SHSPhoneComponent/Library/SHSFlagAccessoryView.swift
1
1936
// // SHSFlagAccessoryView.swift // SHSPhoneComponentSwift // // Created by Maksim Kupetskii on 12/09/2017. // Copyright © 2017 Maksim Kupetskii. All rights reserved. // import UIKit /** Accessory view that shows flag images. */ internal class SHSFlagAccessoryView: UIView { private enum Sizes { static let iconSize: CGFloat = 18 static let minShift: CGFloat = 5 static let fontCorrection: CGFloat = 1 } private var imageView: UIImageView? // MARK: - Life cycle init(with textField: UITextField) { super.init(frame: .zero) let fieldRect = textField.textRect(forBounds: textField.bounds) self.frame = CGRect(x: 0, y: 0, width: viewWidth(for: fieldRect), height: textField.frame.size.height) imageView = UIImageView(frame: CGRect(x: leftShift(for: fieldRect), y: fieldRect.origin.y + (fieldRect.size.height - Sizes.iconSize)/2, width: Sizes.iconSize, height: Sizes.iconSize)) self.addSubview(imageView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Set image for accessory view. */ internal func set(image: UIImage?) { imageView?.image = image } // MARK: - Internal private func leftShift(for textFieldRect: CGRect) -> CGFloat { let minX = textFieldRect.minX let result = minX < Sizes.minShift ? Sizes.minShift : minX return result + Sizes.fontCorrection } private func viewWidth(for textFieldRect: CGRect) -> CGFloat { let minX = textFieldRect.minX if minX < Sizes.minShift { return Sizes.minShift + Sizes.iconSize + Sizes.minShift - minX } else { return minX + Sizes.iconSize } } }
mit
d6f8ff27e7e53869b51398fca23487aa
28.769231
86
0.596899
4.338565
false
false
false
false
ffxfiend/SwiftPulseCast
SwiftPulseCast/SwiftPulseCast/PulseResults.swift
1
553
// // PulseResults.swift // SwiftPulseCast // // Created by Jeremiah Poisson on 5/7/17. // Copyright © 2017 Jeremiah Poisson. All rights reserved. // import Foundation public typealias PulseData = [String: Any] public typealias PulseCompletion<T> = ((PulseResults<T>) -> Void) public struct PulseResults<Value> { public var error : PulseNetworkError? public var result : Value? public var succeeded : Bool { get { return self.error == nil && result != nil } } public var failed : Bool { get { return !self.succeeded } } }
mit
eadbb8381161ca587a8c8db4a2a053cb
18.714286
65
0.681159
3.305389
false
false
false
false
WXGBridgeQ/SwiftPullToRefresh
SwiftPullToRefreshDemo/TestViewController.swift
1
2806
// // TestViewController.swift // SwiftPullToRefreshDemo // // Created by Leo Zhou on 2017/12/19. // Copyright © 2017年 Wiredcraft. All rights reserved. // import UIKit import SwiftPullToRefresh class TestViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! var refresh: Refresh = .indicatorHeader override func viewDidLoad() { super.viewDidLoad() title = refresh.rawValue switch refresh { case .indicatorHeader: scrollView.spr_setIndicatorHeader { [weak self] in self?.action() } case .textHeader: scrollView.spr_setTextHeader { [weak self] in self?.action() } case .smallGIFHeader: guard let url = Bundle.main.url(forResource: "demo-small", withExtension: "gif"), let data = try? Data(contentsOf: url) else { return } scrollView.spr_setGIFHeader(data: data) { [weak self] in self?.action() } case .bigGIFHeader: guard let url = Bundle.main.url(forResource: "demo-big", withExtension: "gif"), let data = try? Data(contentsOf: url) else { return } scrollView.spr_setGIFHeader(data: data, isBig: true, height: 120) { [weak self] in self?.action() } case .gifTextHeader: guard let url = Bundle.main.url(forResource: "demo-small", withExtension: "gif"), let data = try? Data(contentsOf: url) else { return } scrollView.spr_setGIFTextHeader(data: data) { [weak self] in self?.action() } case .superCatHeader: let header = SuperCatHeader(style: .header, height: 120) { [weak self] in self?.action() } scrollView.spr_setCustomHeader(header) case .indicatorFooter: scrollView.spr_setIndicatorFooter { [weak self] in self?.action() } case .textFooter: scrollView.spr_setTextFooter { [weak self] in self?.action() } case .indicatorAutoFooter: scrollView.spr_setIndicatorAutoFooter { [weak self] in self?.action() } case .textAutoFooter: scrollView.spr_setTextAutoFooter { [weak self] in self?.action() } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) scrollView.spr_beginRefreshing() } private func action() { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.scrollView.spr_endRefreshing() } } }
mit
1b1a28c2e9b0a7f81311303a36655f87
31.218391
94
0.551552
4.640728
false
false
false
false
breadwallet/breadwallet-core
Swift/BRCryptoDemo/TransferCreatePaymentController.swift
1
3456
// // TransferCreatePaymentController.swift // BRCryptoDemo // // Created by Ed Gamble on 8/6/19. // Copyright © 2019 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import UIKit import BRCrypto class TransferCreatePaymentController: TransferCreateController { var payment: PaymentProtocolRequest! = nil override func viewDidLoad() { super.viewDidLoad() bitpayURLTextField.text = "https://test.bitpay.com/i/NzMSnqcd6uUuaVDyn6niVa" // "https://test.bitpay.com/i/H2ExBjeUHhjm5zhTaNyazH" submitButton.isEnabled = false } @IBAction func submit(_ sender: Any) { print ("APP: TCP: Want to Pay") self.dismiss(animated: true) {} } @IBAction func cancel(_ sender: Any) { self.dismiss(animated: true) {} } func updateFailed () { DispatchQueue.main.async { self.submitButton.isEnabled = false self.updateButton.isEnabled = true self.parseLabel.text = "" } } @IBAction func updateButtonAction(_ sender: Any) { // Build a URL Request guard let url = bitpayURLTextField.text, var request = URLComponents (string: url) .flatMap ({ $0.url }) .map ({ URLRequest (url: $0) }) else { updateFailed(); return } request.httpMethod = "GET" request.addValue ("application/payment-request", forHTTPHeaderField: "Accept") request.addValue ("application/json", forHTTPHeaderField: "Content-Type") // Fetch the request URLSession (configuration: .default) .dataTask(with: request) { (data: Data?, res: URLResponse?, error: Error?) in guard nil == error else { self.updateFailed(); return } guard let res = res as? HTTPURLResponse else { self.updateFailed(); return } guard 200 == res.statusCode else { self.updateFailed(); return } guard let data = data else { self.updateFailed(); return } switch res.mimeType { case "application/bitcoin-paymentrequest": self.payment = PaymentProtocolRequest.create(wallet: self.wallet, forBip70: data) case "application/payment-request": self.payment = PaymentProtocolRequest.create(wallet: self.wallet, forBitPay: data) default: self.updateFailed(); return } guard nil != self.payment else { self.updateFailed(); return } self.payment.estimateFee (fee: self.wallet.manager.network.minimumFee) { (res: Result<TransferFeeBasis, Wallet.FeeEstimationError>) in guard case let .success(basis) = res else { return } print ("Basis: \(basis)") } DispatchQueue.main.async { self.parseLabel.text = "Yes" // Populate the display self.submitButton.isEnabled = true } }.resume() } @IBOutlet var submitButton: UIBarButtonItem! @IBOutlet var updateButton: UIButton! @IBOutlet var bitpayURLTextField: UITextField! @IBOutlet var parseLabel: UILabel! }
mit
c7233da8703abe71e19a367012e037cc
36.150538
139
0.588712
4.70068
false
false
false
false
royhsu/tiny-core
Sources/Core/Context/Context.swift
1
2380
// // Context.swift // TinyCore // // Created by Roy Hsu on 2019/2/17. // Copyright © 2019 TinyWorld. All rights reserved. // // MARK: - Context /// Use context to encapsulate all associated properties and dependencies together. /// The context provides a set of convenient methods to make instances. /// It also throws the well-defined error when things go wrong. /// For examples, making instances from unregistered identifiers, or specifying a wrong target type for context to make. public struct Context<Identifier> where Identifier: Hashable { private var storage: [Identifier: () throws -> Any] public init(storage: [Identifier: () throws -> Any] = [:]) { self.storage = storage } /// Register a factory for specific identifier. public mutating func register( _ factory: @escaping () throws -> Any, for identifier: Identifier ) { storage[identifier] = factory } /// Make a instance for specific identifier from the context. /// If the identifier hasn't been registered, the context would throw an error. /// Or specify the wrong target type, will also raise an error. public func make<T>( _ targetType: T.Type, for identifier: Identifier ) throws -> T { guard let factory = storage[identifier] else { throw Error.unregistered(identifier: identifier) } let instance = try factory() guard let typedInstance = instance as? T else { throw Error.typeMismatch( identifier: identifier, expectedType: targetType, autualType: type(of: instance) ) } return typedInstance } } extension Context { /// Register a factory for specific identifier. public mutating func register( _ factory: @autoclosure @escaping () throws -> Any, for identifier: Identifier ) { register({ try factory() }, for: identifier) } public mutating func register( _ type: Initializable.Type, for identifier: Identifier ) { register(type.init, for: identifier) } } extension Context { public func make<T>(for identifier: Identifier) throws -> T { return try make(T.self, for: identifier) } } // MARK: - Error extension Context { private typealias Error = ContextError<Identifier> }
mit
d8089a9945f53b44f1de1267220e4a03
24.042105
120
0.641026
4.637427
false
false
false
false
frootloops/swift
test/Constraints/generics.swift
1
22873
// RUN: %target-typecheck-verify-swift infix operator +++ protocol ConcatToAnything { static func +++ <T>(lhs: Self, other: T) } func min<T : Comparable>(_ x: T, y: T) -> T { if y < x { return y } return x } func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) { t +++ u t +++ 1 u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}} } // Make sure that the protocol operators don't get in the way. var b1, b2 : Bool _ = b1 != b2 extension UnicodeScalar { func isAlpha2() -> Bool { return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z") } } protocol P { static func foo(_ arg: Self) -> Self } struct S : P { static func foo(_ arg: S) -> S { return arg } } func foo<T : P>(_ arg: T) -> T { return T.foo(arg) } // Associated types and metatypes protocol SomeProtocol { associatedtype SomeAssociated } func generic_metatypes<T : SomeProtocol>(_ x: T) -> (T.Type, T.SomeAssociated.Type) { return (type(of: x), type(of: x).SomeAssociated.self) } // Inferring a variable's type from a call to a generic. struct Pair<T, U> { } // expected-note 4 {{'T' declared as parameter to type 'Pair'}} expected-note {{'U' declared as parameter to type 'Pair'}} func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { } var i : Int, f : Float var p = pair(i, f) // Conformance constraints on static variables. func f1<S1 : Sequence>(_ s1: S1) {} var x : Array<Int> = [1] f1(x) // Inheritance involving generics and non-generics. class X { func f() {} } class Foo<T> : X { func g() { } } class Y<U> : Foo<Int> { } func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) { x.f() y.f() y.g() } func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) { t.f() t.g() } protocol P1 {} protocol P2 {} func foo<T : P1>(_ t: T) -> P2 { return t // expected-error{{return expression of type 'T' does not conform to 'P2'}} } func foo2(_ p1: P1) -> P2 { return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}} } // <rdar://problem/14005696> protocol BinaryMethodWorkaround { associatedtype MySelf } protocol Squigglable : BinaryMethodWorkaround { } infix operator ~~~ func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T { return true } extension UInt8 : Squigglable { typealias MySelf = UInt8 } var rdar14005696 : UInt8 _ = rdar14005696 ~~~ 5 // <rdar://problem/15168483> public struct SomeIterator<C: Collection, Indices: Sequence> : IteratorProtocol, Sequence where C.Index == Indices.Iterator.Element { var seq : C var indices : Indices.Iterator public typealias Element = C.Iterator.Element public mutating func next() -> Element? { fatalError() } public init(elements: C, indices: Indices) { fatalError() } } func f1<T>(seq: Array<T>) { let x = (seq.indices).lazy.reversed() SomeIterator(elements: seq, indices: x) // expected-warning{{unused}} SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}} } // <rdar://problem/16078944> func count16078944<T>(_ x: Range<T>) -> Int { return 0 } func test16078944 <T: Comparable>(lhs: T, args: T) -> Int { return count16078944(lhs..<args) // don't crash } // <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy() class r22409190ManagedBuffer<Value, Element> { final var value: Value { get {} set {}} func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) -> R) -> R { } } class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> { deinit { self.withUnsafeMutablePointerToElements { elems -> Void in elems.deinitialize(count: self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } } } // <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))' func r22459135() { func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element where S.Iterator.Element : FixedWidthInteger { return 0 } func g(_ x: Any) {} func f(_ x: Int) { g(h([3])) } func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) { let _: (AnyObject) -> () = { internalTarget in handler(internalTarget as! TargetType) } } } // <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set" // <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context _ = [] as Set // expected-error {{generic parameter 'Element' could not be inferred in cast to 'Set<_>}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{14-14=<<#Element: Hashable#>>}} //<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}} r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}} } // <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int' struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}} static func foo() -> Int {} } var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}} // https://bugs.swift.org/browse/SR-599 func SR599<T: FixedWidthInteger>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599()'}} _ = SR599() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type protocol Q19215114 {} protocol P19215114 {} // expected-note @+1 {{in call to function 'body9215114'}} func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {} func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () { //Should complain about not being able to infer type of U. let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}} return f } // <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)' class Whatever<A: Numeric, B: Numeric> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}} static func foo(a: B) {} static func bar() {} } Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}} // <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}} // <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any protocol P27515965 { associatedtype R func f() -> R } struct S27515965 : P27515965 { func f() -> Any { return self } } struct V27515965 { init<T : P27515965>(_ tp: T) where T.R == Float {} // expected-note@-1 {{candidate requires that the types 'Any' and 'Float' be equivalent (requirement specified as 'T.R' == 'Float' [with T = S27515965])}} } func test(x: S27515965) -> V27515965 { return V27515965(x) // expected-error@-1 {{cannot invoke initializer for type 'init(_:)' with an argument list of type '(S27515965)'}} } protocol BaseProto {} protocol SubProto: BaseProto {} @objc protocol NSCopyish { func copy() -> Any } struct FullyGeneric<Foo> {} // expected-note 11 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}} struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}} struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}} struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}} struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}} struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}} struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}} struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}} struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}} struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}} struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}} struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}} struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}} struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}} struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtoBound'}} struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound'}} struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound2'}} extension Pair { init(first: T) {} init(second: U) {} var first: T { fatalError() } var second: U { fatalError() } } func testFixIts() { _ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}} _ = FullyGeneric<Any>() _ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}} _ = AnyClassBound<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}} _ = AnyClassBound<AnyObject>() _ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}} _ = AnyClassBound2<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}} _ = AnyClassBound2<AnyObject>() _ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}} _ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}} _ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}} _ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}} _ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}} _ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}} _ = ObjCProtoBound<NSCopyish>() _ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}} _ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}} _ = ObjCProtoBound2<NSCopyish>() _ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}} _ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}} _ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}} _ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: SubProto & AnyObject#>>}} _ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: SubProto & AnyObject#>>}} _ = ClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<<#Foo: X & SubProto#>>}} _ = ClassAndProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<<#Foo: X & NSCopyish & SubProto#>>}} _ = ClassAndProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{27-27=<<#Foo: X & NSCopyish & SubProto#>>}} _ = Pair() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}} _ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}} _ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}} } func testFixItClassBound() { // We infer a single class bound for simple cases in expressions... let x = ClassBound() let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}} let y = ClassBound2() let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}} // ...but not in types. let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}} let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}} } func testFixItCasting(x: Any) { _ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred in cast to 'FullyGeneric<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}} } func testFixItContextualKnowledge() { // FIXME: These could propagate backwards. let _: Int = Pair().first // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}} let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}} } func testFixItTypePosition() { let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}} let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}} let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}} let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}} let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}} } func testFixItNested() { _ = Array<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}} _ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}} _ = FullyGeneric<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}} _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric, // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}} FullyGeneric // FIXME: We could diagnose both of these, but we don't. >() _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric<Any>, FullyGeneric >() _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric, // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}} FullyGeneric<Any> >() _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}} FullyGeneric() ) _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric<Any>(), FullyGeneric() // expected-note {{explicitly specify the generic arguments to fix this issue}} ) _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}} FullyGeneric<Any>() ) } // rdar://problem/26845038 func occursCheck26845038(a: [Int]) { _ = Array(a)[0] } // rdar://problem/29633747 extension Array where Element: Hashable { public func trimmed(_ elements: [Element]) -> SubSequence { return [] } } func rdar29633747(characters: String) { let _ = Array(characters).trimmed(["("]) } // Null pointer dereference in noteArchetypeSource() class GenericClass<A> {} // expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}} func genericFunc<T>(t: T) { _ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} // expected-error@-2 3 {{type 'T' does not conform to protocol 'Hashable'}} } struct SR_3525<T> {} func sr3525_arg_int(_: inout SR_3525<Int>) {} func sr3525_arg_gen<T>(_: inout SR_3525<T>) {} func sr3525_1(t: SR_3525<Int>) { let _ = sr3525_arg_int(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } func sr3525_2(t: SR_3525<Int>) { let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } func sr3525_3<T>(t: SR_3525<T>) { let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } class testStdlibType { let _: Array // expected-error {{reference to generic type 'Array' requires arguments in <...>}} {{15-15=<Any>}} } // rdar://problem/32697033 protocol P3 { associatedtype InnerAssoc } protocol P4 { associatedtype OuterAssoc: P3 } struct S3 : P3 { typealias InnerAssoc = S4 } struct S4: P4 { typealias OuterAssoc = S3 } public struct S5 { func f<Model: P4, MO> (models: [Model]) where Model.OuterAssoc == MO, MO.InnerAssoc == Model { } func g<MO, Model: P4> (models: [Model]) where Model.OuterAssoc == MO, MO.InnerAssoc == Model { } func f(arr: [S4]) { f(models: arr) g(models: arr) } } // rdar://problem/24329052 - QoI: call argument archetypes not lining up leads to ambiguity errors struct S_24329052<T> { // expected-note {{generic parameter 'T' of generic struct 'S_24329052' declared here}} var foo: (T) -> Void // expected-note@+1 {{generic parameter 'T' of instance method 'bar(_:)' declared here}} func bar<T>(_ v: T) { foo(v) } // expected-error@-1 {{cannot convert value of type 'T' (generic parameter of instance method 'bar(_:)') to expected argument type 'T' (generic parameter of generic struct 'S_24329052')}} } extension Sequence { var rdar24329052: (Element) -> Void { fatalError() } // expected-note@+1 {{generic parameter 'Element' of instance method 'foo24329052(_:)' declared here}} func foo24329052<Element>(_ v: Element) { rdar24329052(v) } // expected-error@-1 {{cannot convert value of type 'Element' (generic parameter of instance method 'foo24329052(_:)') to expected argument type 'Self.Element' (associated type of protocol 'Sequence')}} } func rdar27700622<E: Comparable>(_ input: [E]) -> [E] { let pivot = input.first! let lhs = input.dropFirst().filter { $0 <= pivot } let rhs = input.dropFirst().filter { $0 > pivot } return rdar27700622(lhs) + [pivot] + rdar27700622(rhs) // Ok } // rdar://problem/22898292 - Type inference failure with constrained subclass protocol P_22898292 {} do { func construct_generic<T: P_22898292>(_ construct: () -> T) -> T { return construct() } class A {} class B : A, P_22898292 {} func foo() -> B { return B() } func bar(_ value: A) {} func baz<T: A>(_ value: T) {} func rdar_22898292_1() { let x = construct_generic { foo() } // returns A bar(x) // Ok bar(construct_generic { foo() }) // Ok } func rdar22898292_2<T: B>(_ d: T) { _ = { baz($0) }(construct_generic { d }) // Ok } } // rdar://problem/35541153 - Generic parameter inference bug func rdar35541153() { func foo<U: Equatable, V: Equatable, C: Collection>(_ c: C) where C.Element == (U, V) {} func bar<K: Equatable, V, C: Collection>(_ c: C, _ k: K, _ v: V) where C.Element == (K, V) {} let x: [(a: Int, b: Int)] = [] let y: [(k: String, v: Int)] = [] foo(x) // Ok bar(y, "ultimate question", 42) // Ok }
apache-2.0
dbeeec3e3115e872f3ded9785b4ea47f
41.123389
219
0.679141
3.770689
false
false
false
false
frootloops/swift
test/Sema/diag_deprecated_iuo.swift
1
14455
// RUN: %target-typecheck-verify-swift -swift-version 3 // RUN: %target-typecheck-verify-swift -swift-version 4 // These are all legal uses of '!'. struct Fine { var value: Int! func m(_ unnamed: Int!, named: Int!) -> Int! { return unnamed } static func s(_ unnamed: Int!, named: Int!) -> Int! { return named } init(_ value: Int) { self.value = value } init!() { return nil } subscript ( index: Int! ) -> Int! { return index } subscript<T> ( index: T! ) -> T! { return index } } let _: ImplicitlyUnwrappedOptional<Int> = 1 // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{8-36=}} {{39-39=!}} {{39-40=}} let _: ImplicitlyUnwrappedOptional = 1 // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use an explicit type followed by '!'}} extension ImplicitlyUnwrappedOptional { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{11-38=Optional}} } func functionSpelling( _: ImplicitlyUnwrappedOptional<Int> // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{6-34=}} {{37-37=!}} {{37-38=}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{6-34=}} {{37-37=!}} {{37-38=}} return 1 } // Okay, like in the method case. func functionSigil( _: Int! ) -> Int! { return 1 } // Not okay because '!' is not at the top level of the type. func functionSigilArray( _: [Int!] // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{10-11=?}} ) -> [Int!] { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{10-11=?}} return [1] } func genericFunction<T>( iuo: ImplicitlyUnwrappedOptional<T> // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{8-36=}} {{37-37=!}} {{37-38=}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{6-34=}} {{35-35=!}} {{35-36=}} return iuo } // Okay, like in the non-generic case. func genericFunctionSigil<T>( iuo: T! ) -> T! { return iuo } func genericFunctionSigilArray<T>( // FIXME: We validate these types multiple times resulting in multiple diagnostics iuo: [T!] // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{10-11=?}} // expected-warning@-1 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{10-11=?}} // expected-warning@-2 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{10-11=?}} ) -> [T!] { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} // expected-warning@-1 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} // expected-warning@-2 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} return iuo } protocol P { associatedtype T associatedtype U } struct S : P { typealias T = ImplicitlyUnwrappedOptional<Int> // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{17-45=}} {{48-48=?}} {{48-49=}} typealias U = Optional<ImplicitlyUnwrappedOptional<Int>> // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{26-54=}} {{57-57=?}} {{57-58=}} typealias V = Int! // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{20-21=?}} typealias W = Int!? // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{20-21=?}} var x: V var y: W var fn1: (Int!) -> Int // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{16-17=?}} var fn2: (Int) -> Int! // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{24-25=?}} subscript ( index: ImplicitlyUnwrappedOptional<Int> // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{12-40=}} {{43-43=!}} {{43-44=}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{12-40=}} {{43-43=!}} {{43-44=}} return index } subscript<T> ( index: ImplicitlyUnwrappedOptional<T> // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{12-40=}} {{41-41=!}} {{41-42=}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{12-40=}} {{41-41=!}} {{41-42=}} return index } } func generic<T : P>(_: T) where T.T == ImplicitlyUnwrappedOptional<Int> { } // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{40-68=}} {{71-71=?}} {{71-72=}} func genericOptIUO<T : P>(_: T) where T.U == Optional<ImplicitlyUnwrappedOptional<Int>> {} // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{55-83=}} {{86-86=?}} {{86-87=}} func testClosure() -> Int { return { (i: ImplicitlyUnwrappedOptional<Int>) // expected-warning {{the spelling 'ImplicitlyUnwrappedOptional' is deprecated; use '!' after the type name}}{{9-37=}} {{40-40=!}} {{40-41=}} -> ImplicitlyUnwrappedOptional<Int> in // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{9-37=}} {{40-40=?}} {{40-41=}} return i }(1)! } _ = Array<Int!>() // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{14-15=?}} let _: Array<Int!> = [1] // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{17-18=?}} _ = [Int!]() // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{9-10=?}} let _: [Int!] = [1] // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{12-13=?}} _ = Optional<Int!>(nil) // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{17-18=?}} let _: Optional<Int!> = nil // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{20-21=?}} _ = Int!?(0) // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} let _: Int!? = 0 // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{11-12=?}} _ = ( Int!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{6-7=?}} Float!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} String! // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{9-10=?}} )(1, 2.0, "3") let _: ( Int!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{6-7=?}} Float!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{8-9=?}} String! // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{9-10=?}} ) = (1, 2.0, "3") struct Generic<T, U, C> { init(_ t: T, _ u: U, _ c: C) {} } _ = Generic<Int!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{16-17=?}} Float!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{18-19=?}} String!>(1, 2.0, "3") // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{19-20=?}} let _: Generic<Int!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{19-20=?}} Float!, // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{21-22=?}} String!> = Generic(1, 2.0, "3") // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{22-23=?}} func vararg(_ first: Int, more: Int!...) { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{36-37=?}} } func varargIdentifier(_ first: Int, more: ImplicitlyUnwrappedOptional<Int>...) { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{43-71=}} {{74-74=?}} {{74-75=}} } func iuoInTuple() -> (Int!) { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{26-27=?}} return 1 } func iuoInTupleIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{33-61=}} {{64-64=?}} {{64-65=}} return 1 } func iuoInTuple2() -> (Float, Int!) { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{34-35=?}} return (1.0, 1) } func iuoInTuple2Identifier() -> (Float, ImplicitlyUnwrappedOptional<Int>) { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{41-69=}} {{72-72=?}} {{72-73=}} return (1.0, 1) } func takesFunc(_ fn: (Int!) -> Int) -> Int { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{26-27=?}} return fn(0) } func takesFuncIdentifier(_ fn: (ImplicitlyUnwrappedOptional<Int>) -> Int) -> Int { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{33-61=}} {{64-64=?}} {{64-65=}} return fn(0) } func takesFunc2(_ fn: (Int) -> Int!) -> Int { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{35-36=?}} return fn(0)! } func takesFunc2Identifier(_ fn: (Int) -> ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{42-70=}} {{73-73=?}} {{73-74=}} return fn(0)! } func returnsFunc() -> (Int!) -> Int { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{27-28=?}} return { $0! } } func returnsFuncIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{34-62=}} {{65-65=?}} {{65-66=}} return { $0! } } func returnsFunc2() -> (Int) -> Int! { // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}{{36-37=?}} return { $0 } } func returnsFunc2Identifier() -> (Int) -> ImplicitlyUnwrappedOptional<Int> { // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{43-71=}} {{74-74=?}} {{74-75=}} return { $0 } } let x = 1 as ImplicitlyUnwrappedOptional // expected-warning {{using 'ImplicitlyUnwrappedOptional' in this location is deprecated and will be removed in a future release; consider changing this to 'Optional' instead}}{{14-41=Optional}} let y = x! let z: Int = x // expected-error {{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}}{{15-15=!}}
apache-2.0
4b2ca7b641e9048e76ceb66332bea194
70.206897
300
0.688966
4.209377
false
false
false
false
texuf/outandabout
outandabout/outandabout/ViewController.swift
1
2292
// // ViewController.swift // outandabout // // Created by Austin Ellis on 1/2/15. // Copyright (c) 2015 Austin Ellis. All rights reserved. // import UIKit protocol writeBarcodeBackDelegate { func writeBarcodeBack(value: String) } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, writeBarcodeBackDelegate { var barcodevalue :String = "" @IBOutlet weak var tableView: UITableView! @IBAction func onCameraButton(sender: AnyObject) { println("CAMERA BUTTON") self.performSegueWithIdentifier("cameraPopover", sender: self) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. println("VIEW DID LOAD " + barcodevalue) //pull data from parse, based on install id //populate list } override func viewDidAppear(animated: Bool) { println("VIEW DID Appear " + barcodevalue) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let secondVC = segue.destinationViewController as BarcodeReaderController secondVC.delegate = self; } func writeBarcodeBack(value: String) { println("YEAH!!!!!!!!!! " + value) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return max(1, dataMgr.interactions.count) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier:"convo"); if(dataMgr.interactions.count > 0) { cell.textLabel?.text = dataMgr.interactions[indexPath.row].barcode_id; } else { cell.textLabel?.text = "No conversations" cell.detailTextLabel?.text = "Scan a barcode with the camera button" } return cell; } }
mit
0a19a6c12cc0b82ccad9e46e8c96331b
25.651163
114
0.629145
5.127517
false
false
false
false
foresterre/mal
swift3/Sources/step7_quote/main.swift
4
6149
import Foundation // read func READ(_ str: String) throws -> MalVal { return try read_str(str) } // eval func is_pair(_ ast: MalVal) -> Bool { switch ast { case MalVal.MalList(let lst, _): return lst.count > 0 case MalVal.MalVector(let lst, _): return lst.count > 0 default: return false } } func quasiquote(_ ast: MalVal) -> MalVal { if !is_pair(ast) { return list([MalVal.MalSymbol("quote"), ast]) } let a0 = try! _nth(ast, 0) switch a0 { case MalVal.MalSymbol("unquote"): return try! _nth(ast, 1) default: break } if is_pair(a0) { let a00 = try! _nth(a0, 0) switch a00 { case MalVal.MalSymbol("splice-unquote"): return list([MalVal.MalSymbol("concat"), try! _nth(a0, 1), quasiquote(try! rest(ast))]) default: break } } return list([MalVal.MalSymbol("cons"), quasiquote(a0), quasiquote(try! rest(ast))]) } func eval_ast(_ ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalSymbol: return try env.get(ast) case MalVal.MalList(let lst, _): return list(try lst.map { try EVAL($0, env) }) case MalVal.MalVector(let lst, _): return vector(try lst.map { try EVAL($0, env) }) case MalVal.MalHashMap(let dict, _): var new_dict = Dictionary<String,MalVal>() for (k,v) in dict { new_dict[k] = try EVAL(v, env) } return hash_map(new_dict) default: return ast } } func EVAL(_ orig_ast: MalVal, _ orig_env: Env) throws -> MalVal { var ast = orig_ast, env = orig_env while true { switch ast { case MalVal.MalList(let lst, _): if lst.count == 0 { return ast } default: return try eval_ast(ast, env) } switch ast { case MalVal.MalList(let lst, _): switch lst[0] { case MalVal.MalSymbol("def!"): return try env.set(lst[1], try EVAL(lst[2], env)) case MalVal.MalSymbol("let*"): let let_env = try Env(env) var binds = Array<MalVal>() switch lst[1] { case MalVal.MalList(let l, _): binds = l case MalVal.MalVector(let l, _): binds = l default: throw MalError.General(msg: "Invalid let* bindings") } var idx = binds.startIndex while idx < binds.endIndex { let v = try EVAL(binds[binds.index(after: idx)], let_env) try let_env.set(binds[idx], v) idx = binds.index(idx, offsetBy: 2) } env = let_env ast = lst[2] // TCO case MalVal.MalSymbol("quote"): return lst[1] case MalVal.MalSymbol("quasiquote"): ast = quasiquote(lst[1]) // TCO case MalVal.MalSymbol("do"): let slc = lst[1..<lst.index(before: lst.endIndex)] try _ = eval_ast(list(Array(slc)), env) ast = lst[lst.index(before: lst.endIndex)] // TCO case MalVal.MalSymbol("if"): switch try EVAL(lst[1], env) { case MalVal.MalFalse, MalVal.MalNil: if lst.count > 3 { ast = lst[3] // TCO } else { return MalVal.MalNil } default: ast = lst[2] // TCO } case MalVal.MalSymbol("fn*"): return malfunc( { return try EVAL(lst[2], Env(env, binds: lst[1], exprs: list($0))) }, ast:[lst[2]], env:env, params:[lst[1]]) default: switch try eval_ast(ast, env) { case MalVal.MalList(let elst, _): switch elst[0] { case MalVal.MalFunc(let fn, nil, _, _, _, _): let args = Array(elst[1..<elst.count]) return try fn(args) case MalVal.MalFunc(_, let a, let e, let p, _, _): let args = Array(elst[1..<elst.count]) env = try Env(e, binds: p![0], exprs: list(args)) // TCO ast = a![0] // TCO default: throw MalError.General(msg: "Cannot apply on '\(elst[0])'") } default: throw MalError.General(msg: "Invalid apply") } } default: throw MalError.General(msg: "Invalid apply") } } } // print func PRINT(_ exp: MalVal) -> String { return pr_str(exp, true) } // repl @discardableResult func rep(_ str:String) throws -> String { return PRINT(try EVAL(try READ(str), repl_env)) } var repl_env: Env = try Env() // core.swift: defined using Swift for (k, fn) in core_ns { try repl_env.set(MalVal.MalSymbol(k), malfunc(fn)) } try repl_env.set(MalVal.MalSymbol("eval"), malfunc({ try EVAL($0[0], repl_env) })) let pargs = CommandLine.arguments.map { MalVal.MalString($0) } // TODO: weird way to get empty list, fix this var args = pargs[pargs.startIndex..<pargs.startIndex] if pargs.index(pargs.startIndex, offsetBy:2) < pargs.endIndex { args = pargs[pargs.index(pargs.startIndex, offsetBy:2)..<pargs.endIndex] } try repl_env.set(MalVal.MalSymbol("*ARGV*"), list(Array(args))) // core.mal: defined using the language itself try rep("(def! not (fn* (a) (if a false true)))") try rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") if CommandLine.arguments.count > 1 { try rep("(load-file \"" + CommandLine.arguments[1] + "\")") exit(0) } while true { print("user> ", terminator: "") let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } catch (MalError.General(let msg)) { print("Error: \(msg)") } catch (MalError.MalException(let obj)) { print("Error: \(pr_str(obj, true))") } }
mpl-2.0
964332be5e8900b187dc85be164672a7
31.193717
89
0.519759
3.78633
false
false
false
false
iSapozhnik/LoadingViewController
LoadingViewController/Classes/Views/LoadingViews/StrokeLoadingView.swift
1
1084
// // StrokeLoadingView.swift // LoadingControllerDemo // // Created by Sapozhnik Ivan on 28.06.16. // Copyright © 2016 Sapozhnik Ivan. All rights reserved. // import UIKit class StrokeLoadingView: LoadingView, Animatable { var activity = StrokeActivityView() override init(frame: CGRect) { super.init(frame: frame) defaultInitializer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) defaultInitializer() } fileprivate func defaultInitializer() { let size = CGSize(width: 34, height: 34) activity.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) addSubview(activity) } override func layoutSubviews() { super.layoutSubviews() activity.center = CGPoint(x: bounds.midX, y: bounds.midY) } func startAnimating() { let delay = 0.0 * Double(NSEC_PER_SEC) let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { self.activity.animating = true }) } func stopAnimating() { activity.animating = false } }
mit
566a9a951357bd1095589d2c86f3adc0
20.66
77
0.700831
3.394984
false
false
false
false
kellanburket/franz
Tests/FranzTests/AssignmentTests.swift
1
1339
// // AssignmentTests.swift // FranzTests // // Created by Luke Lau on 23/07/2017. // import XCTest @testable import Franz class AssignmentTests: XCTestCase { func getMockPartition(id: Int) -> Partition { return Partition(partitionErrorCode: 0, partitionId: id, leader: 0, replicas: [Int](), isr: [Int]()) } func testRoundRobin() { let topics = ["foo", "bar", "baz", "daz", "waz", "woz"] let partitions = topics.reduce([TopicName: [Partition]]()) { acc, next in var newAcc = acc newAcc[next] = [0, 1, 2, 3, 4, 5].map(getMockPartition) return newAcc } let cluster = Cluster(brokers: [(String, Int32)](), clientId: "test") let members = ["gary", "bary", "dary"] let result = cluster.assignRoundRobin(members: members, partitions: partitions) XCTAssertEqual(result["gary"]!["foo"]!, [0, 3]) let combinations = result.flatMap { member, topics in topics.flatMap { topic, partitions in partitions.map { partition in (member, topic, partition) } } } var seen = [(MemberId, TopicName, PartitionId)]() for combination in combinations { if seen.contains(where: { memberId, topicName, partitionId in (memberId, topicName, partitionId) == combination }) { XCTFail("A partition was given out twice") } seen.append(combination) } } }
mit
9ee374b497b00a78e78f24db734e0870
24.264151
102
0.644511
3.3475
false
true
false
false
knox-carl/iOS-samples
DrawPad starter/DrawPad/ViewController.swift
1
8469
// // ViewController.swift // DrawPad // // Created by Jean-Pierre Distler on 13.11.14. // Copyright (c) 2014 Ray Wenderlich. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var tempImageView: UIImageView! // lastPoint stores the last drawn point on the canvas. This is used when a // continuous brush stroke is being drawn on the canvas. var lastPoint = CGPoint.zeroPoint // red, green, and blue store the current RGB values of the selected color. var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 // brushWidth and opacity store the brush stroke width and opacity. var brushWidth: CGFloat = 10.0 var opacity: CGFloat = 1.0 // swiped identifies if the brush stroke is continuous. var swiped = false 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. } let colors: [(CGFloat, CGFloat, CGFloat)] = [ (0, 0, 0), (105.0 / 255.0 , 105.0 / 255.0, 105.0 / 255.0), (1.0, 0, 0), (0, 0, 1.0), (51.0 / 255.0, 204.0 / 255.0, 1.0), (102.0 / 255.0, 204.0 / 255.0, 0), (102.0 / 255.0, 1.0, 0), (160.0 / 255.0, 82.0 / 255.0, 45.0 / 255.0), (1.0, 102.0 / 255.0, 0), (1.0, 1.0, 0), (1.0, 1.0, 1.0), ] // end colors override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { swiped = false if let touch = touches.anyObject() as? UITouch { lastPoint = touch.locationInView(self.view) } } func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) { // 1 // here we draw a line between two points. remember that this app has // two image views- mainImageView (which holds the "drawing so far") and // tempImageView (which holds the "line you're currently drawing"). Here // you want to draw into tempImageView, so you need to set up a drawing // context with the image currently in the tempImageView (which should // be empty the first time). UIGraphicsBeginImageContext(view.frame.size) let context = UIGraphicsGetCurrentContext() tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)) // 2 // Next, you get the current touch point and then draw a line with // CGContextAddLineToPoint from lastPoint to currentPoint. You might think // that this appraoch will produce a series of straight lines and the // result will look like a set of jagged lines. This WILL produce straight // lines, but the touch events fire so quickly that the lines are short // enough and the result will look like a nice smooth curve. CGContextMoveToPoint(context, fromPoint.x, toPoint.y) CGContextAddLineToPoint(context, toPoint.x, toPoint.y) // 3 // here are all the drawing parameters for brush size and opacity and // brush stroke color. CGContextSetLineCap(context, kCGLineCapSquare) CGContextSetLineWidth(context, brushWidth) CGContextSetRGBStrokeColor(context, red, green, blue, 1.0) CGContextSetBlendMode(context, kCGBlendModeNormal) // 4 // this is where the magic happens, and where you actually draw the // path! CGContextStrokePath(context) // 5 // next, you need to wrap up the drawing context to render the new // line into the temporary image view. tempImageView.image = UIGraphicsGetImageFromCurrentImageContext() tempImageView.alpha = opacity UIGraphicsEndImageContext() } // end drawLineFrom override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { // 6 // in touchesMoved, you set swiped to true so you can keep track of whether // there is a current swipe in progress. since this is touchesMoved, the // answer is yes, there is a swipe in progress! You then call the helper // method you just wrote to draw the line. swiped = true if let touch = touches.anyObject() as? UITouch { let currentPoint = touch.locationInView(view) drawLineFrom(lastPoint, toPoint: currentPoint) // 7 // finally, you update the lastPoint so the next touch event will // continue where you just left off. lastPoint = currentPoint } // end if } // end touchesMoved override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { if !swiped { // draw a single point drawLineFrom(lastPoint, toPoint: lastPoint) } // Merge tempImageView into mainImageView UIGraphicsBeginImageContext(mainImageView.frame.size) mainImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode:kCGBlendModeNormal, alpha: 1.0) tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: kCGBlendModeNormal, alpha: opacity) mainImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() tempImageView.image = nil } // end touchesEnded // MARK: - Actions @IBAction func reset(sender: AnyObject) { mainImageView.image = nil } @IBAction func share(sender: AnyObject) { UIGraphicsBeginImageContext(mainImageView.bounds.size) mainImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil) presentViewController(activity, animated: true, completion: nil) } @IBAction func pencilPressed(sender: AnyObject) { // 1 // first, you need to know which color index the user selected. there are // many places this could go wrong - incorrect tag, tag not set, not enough // colors in the array - so there are a few checks here. the default if the // value is out of range is just black, the first color. var index = sender.tag ?? 0 if index < 0 || index >= colors.count { index = 0 } // 2 // next, you set the red, green, and blue properties. you didn't know you could set // multiple variables with a tuple like that? there's your swift tip of the day! :] (red, green, blue) = colors[index] // 3 // the last color is the eraser, so it's a bit special. the eraser button sets the // color to white and opacity to 1.0. as your background color is also white, this will // give you a very handy eraser effect. if index == colors.count - 1 { opacity = 1.0 } } // end pencilPressed override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let settingsViewController = segue.destinationViewController as SettingsViewController settingsViewController.delegate = self settingsViewController.brush = brushWidth settingsViewController.opacity = opacity settingsViewController.red = red settingsViewController.green = green settingsViewController.blue = blue } } extension ViewController: SettingsViewControllerDelegate { func settingsViewControllerFinished(settingsViewController: SettingsViewController) { self.brushWidth = settingsViewController.brush self.opacity = settingsViewController.opacity self.red = settingsViewController.red self.green = settingsViewController.green self.blue = settingsViewController.blue } }
mit
788d3e7f84007901cd1612d907478f72
35.192308
95
0.636321
4.811932
false
false
false
false
knox-carl/iOS-samples
StrutsProblem/StrutsProblem/ViewController.swift
1
1950
// // ViewController.swift // StrutsProblem // // Created by Carl R Knox on 1/21/15. // Copyright (c) 2015 Carl R Knox. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var bottomView: UIView! @IBOutlet weak var topRightView: UIView! @IBOutlet weak var topLeftView: UIView! 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. } /* override func viewWillLayoutSubviews() { if UIInterfaceOrientationIsLandscape(self.interfaceOrientation) { var rect = self.topLeftView.frame rect.size.width = 254 rect.size.height = 130 self.topLeftView.frame = rect rect = self.topRightView.frame rect.origin.x = 294 rect.size.width = 254 rect.size.height = 130 self.topRightView.frame = rect rect = self.bottomView.frame rect.origin.y = 170 rect.size.width = 528 rect.size.height = 130 self.bottomView.frame = rect } else { var rect = self.topLeftView.frame rect.size.width = 130 rect.size.height = 254 self.topLeftView.frame = rect rect = self.topRightView.frame rect.origin.x = 170 rect.size.width = 130 rect.size.height = 254 self.topRightView.frame = rect rect = self.bottomView.frame rect.origin.y = 295 rect.size.width = 280 rect.size.height = 254 self.bottomView.frame = rect } } */ }
mit
953340a90b54b6ae33829075f4d1c9d3
26.857143
80
0.554359
4.814815
false
false
false
false
cuzv/ExtensionKit
Sources/Classes/DashlineView.swift
1
2512
// // DashlineView.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.com). // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit final public class DashlineView: UIView { public var spacing: CGFloat = 2 public var lineColor: UIColor = UIColor.separator public var horizontal: Bool = true public override func draw(_ rect: CGRect) { super.draw(rect) backgroundColor?.setFill() UIRectFill(rect) let lineWidth = horizontal ? rect.height.ceilling : rect.width.ceilling let startPoint = horizontal ? CGPoint(x: (lineWidth / 2).ceilling, y: (rect.height / 2).ceilling) : CGPoint(x: (rect.width / 2).ceilling , y: (lineWidth / 2).ceilling) let endPoint = horizontal ? CGPoint(x: rect.width - (lineWidth / 2).ceilling, y: (rect.height / 2).ceilling) : CGPoint(x: (rect.width / 2).ceilling , y: rect.height - (lineWidth / 2).ceilling) guard let context = UIGraphicsGetCurrentContext() else { return } context.beginPath() context.setLineWidth(lineWidth) context.setStrokeColor(lineColor.cgColor) context.setLineDash(phase: 0, lengths: [spacing, spacing]) context.move(to: CGPoint(x: startPoint.x, y: startPoint.y)) context.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) context.strokePath() } }
mit
cf8a30995fe5262e581b941d3009858d
45.518519
118
0.67078
4.286689
false
false
false
false
guidomb/Portal
Portal/Subscription.swift
1
3336
// // Subscription.swift // Portal // // Created by Guido Marucci Blas on 4/4/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Foundation public enum Subscription<MessageType, RouteType: Route, CustomSubscriptionType: Equatable>: Equatable { static public func ==<MessageType, RouteType, CustomSubscriptionType>( lhs: Subscription<MessageType, RouteType, CustomSubscriptionType>, rhs: Subscription<MessageType, RouteType, CustomSubscriptionType>) -> Bool { switch (lhs, rhs) { case (.timer(let a), .timer(let b)): return a == b case (.custom(let a), .custom(let b)): return a == b default: return false } } case timer(Timer<MessageType, RouteType>) case custom(CustomSubscriptionType) } public protocol SubscriptionManager { associatedtype SubscriptionType: Equatable associatedtype RouteType: Route associatedtype MessageType func add(subscription: SubscriptionType, dispatch: @escaping (Action<RouteType, MessageType>) -> Void) func remove(subscription: SubscriptionType) } internal final class SubscriptionsManager<RouteType, MessageType, CustomSubscriptionManager: SubscriptionManager> where CustomSubscriptionManager.RouteType == RouteType, CustomSubscriptionManager.MessageType == MessageType { typealias ActionType = Action<RouteType, MessageType> typealias SubscriptionType = Subscription<MessageType, RouteType, CustomSubscriptionManager.SubscriptionType> private let dispatch: (ActionType) -> Void private var currentSubscriptions: [SubscriptionType] = [] fileprivate let subscriptionManager: CustomSubscriptionManager fileprivate let timerSubscriptionManager = TimerSubscriptionManager<MessageType, RouteType>() init(subscriptionManager: CustomSubscriptionManager, dispatch: @escaping (ActionType) -> Void) { self.subscriptionManager = subscriptionManager self.dispatch = dispatch } internal func manage(subscriptions: [SubscriptionType]) { for subscription in currentSubscriptions where !subscriptions.contains(subscription) { remove(subscription: subscription) } for subscription in subscriptions where !currentSubscriptions.contains(subscription) { add(subscription: subscription, dispatch: dispatch) } currentSubscriptions = subscriptions } } extension SubscriptionsManager: SubscriptionManager { func add(subscription: SubscriptionType, dispatch: @escaping (ActionType) -> Void) { switch subscription { case .timer(let timer): timerSubscriptionManager.add(subscription: timer, dispatch: dispatch) case .custom(let customSubscription): subscriptionManager.add(subscription: customSubscription, dispatch: dispatch) } } func remove(subscription: SubscriptionType) { switch subscription { case .timer(let timer): timerSubscriptionManager.remove(subscription: timer) case .custom(let customSubscription): subscriptionManager.remove(subscription: customSubscription) } } }
mit
de0f5e0de200434ce8511333510d5436
34.105263
114
0.688156
5.586265
false
false
false
false
soundq/SoundQ-iOS
SoundQ/AppDelegate.swift
1
2645
// // AppDelegate.swift // SoundQ // // Created by Nishil Shah on 4/24/16. // Copyright © 2016 Nishil Shah. All rights reserved. // import UIKit import Soundcloud import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { //configure status bar application.statusBarHidden = false application.statusBarStyle = UIStatusBarStyle.LightContent let SCAuth = SoundCloudAuth() Soundcloud.clientIdentifier = SCAuth.clientIdentifier Soundcloud.clientSecret = SCAuth.clientSecret Soundcloud.redirectURI = SCAuth.redirectURI return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { 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:. } }
apache-2.0
0f11d080a069f53b1a26cdae71cef5d1
42.344262
285
0.738275
5.566316
false
false
false
false
davedelong/DDMathParser
MathParser/Sources/MathParser/HexNumberExtractor.swift
1
1659
// // HexNumberExtractor.swift // DDMathParser // // Created by Dave DeLong on 8/6/15. // // import Foundation internal struct HexNumberExtractor: TokenExtractor { func matchesPreconditions(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Bool { return buffer.peekNext() == "0" && buffer.peekNext(1, lowercase: true) == "x" } func extract(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Tokenizer.Result { let start = buffer.currentIndex guard buffer.peekNext() == "0" && buffer.peekNext(1, lowercase: true) == "x" else { let error = MathParserError(kind: .cannotParseHexNumber, range: start ..< start) return .error(error) } buffer.consume(2) // 0x let indexBeforeHexNumbers = buffer.currentIndex while buffer.peekNext()?.isHexDigit == true { buffer.consume() } if buffer.currentIndex == indexBeforeHexNumbers { // there wasn't anything after 0[xX] buffer.resetTo(start) } let result: Tokenizer.Result if buffer.currentIndex - start > 0 { let range: Range<Int> = indexBeforeHexNumbers ..< buffer.currentIndex let raw = buffer[range] result = .value(HexNumberToken(string: raw, range: range)) } else { let range: Range<Int> = start ..< buffer.currentIndex let error = MathParserError(kind: .cannotParseHexNumber, range: range) result = .error(error) } return result } }
mit
28ad175ff2c8807f7131cfd9971ffc83
30.301887
101
0.58469
4.62117
false
true
false
false
DaRkD0G/EasyHelper
EasyHelper/UIViewExtensions.swift
1
17885
// // UIViewExtensions.swift // EasyHelper // // Created by DaRk-_-D0G on 24/07/2015. // Copyright (c) 2015 DaRk-_-D0G. All rights reserved. // import UIKit // Todo So if you want to change the position of your cell within it’s superview (the tableview in this case), use the frame. But if you want to shrink or move an element within the view, use the bounds! /// ############################################################ /// /// Initilizers /// /// ############################################################ /// // MARK: - Initilizers public extension UIView { public convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.init (frame: CGRect (x: x, y: y, width: width, height: height)) } convenience init (superView: UIView) { self.init (frame: CGRect (origin: CGPointZero, size: superView.size)) } } /// ############################################################ /// /// Classical /// /// ############################################################ /// // MARK: - UIView Extension Classical public extension UIView { /// X position public var x:CGFloat { get { return self.frame.origin.x } set { self.frame = CGRect (x: newValue, y: self.y, width: self.width, height: self.height) } } /// Y position public var y:CGFloat { get { return self.frame.origin.y } set { self.frame = CGRect (x: self.x, y: newValue, width: self.width, height: self.height) } } /// With size public var width:CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } /// Height size public var height:CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } /// Size public var size: CGSize { get { return self.frame.size } set { self.frame = CGRect (origin: self.frame.origin, size: newValue) } } /// Position public var position: CGPoint { get { return self.frame.origin } set (value) { self.frame = CGRect (origin: value, size: self.frame.size) } } /// Position Center public var positionCenter: CGPoint { return CGPoint(x: width/2, y: height/2) } /** Set Anchor position - parameter anchorPosition: AnchorPosition */ public func setAnchorPosition (anchorPosition: AnchorPosition) { self.layer.anchorPoint = anchorPosition.rawValue } } /// ############################################################ /// /// Other /// /// ############################################################ /// extension UIView { /** Remove allSubView */ public func removeAllSubViews() { for subView :AnyObject in self.subviews { subView.removeFromSuperview() } } func toImage () -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) drawViewHierarchyInRect(bounds, afterScreenUpdates: false) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } } /// ############################################################ /// /// Animate /// /// ############################################################ /// // MARK: - UIView Extension Animate public extension UIView { /* --------------------------------------------------------------------------- */ /* Start and Stop Animate */ /* --------------------------------------------------------------------------- */ public func stopAnimation() { CATransaction.begin() self.layer.removeAllAnimations() CATransaction.commit() CATransaction.flush() } public func isBeingAnimated() -> Bool { return self.layer.animationKeys()?.count > 0 } /* --------------------------------------------------------------------------- */ /* Fad In & Out */ /* --------------------------------------------------------------------------- */ /** Fade In - parameter duration: NSTimeInterval ( default = 1.0 ) - parameter delay: NSTimeInterval ( default = 0 ) - parameter alpha: CGFloat ( default = 1.0 ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyFadeIn( duration duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, toAlpha: CGFloat = 1, completionEnd: ((Bool) -> ())? = nil) { UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { self.alpha = toAlpha }, completion: completionEnd) /* let animation = CABasicAnimation(keyPath:"opacity") animation.beginTime = CACurrentMediaTime() + delay; animation.duration = duration animation.fromValue = 0 animation.toValue = alpha animation.fillMode = kCAFillModeBoth CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey:"animateOpacity")*/ } /** Fade Out - parameter duration: NSTimeInterval ( default = 1.0 ) - parameter delay: NSTimeInterval ( default = 0.0 ) - parameter alpha: CGFloat ( default = 0 ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyFadeOut( duration duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, toAlpha: CGFloat = 0, completionEnd: ((Bool) -> ())? = nil) { UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { self.alpha = toAlpha }, completion: completionEnd) /* let animation = CABasicAnimation(keyPath:"opacity") animation.beginTime = CACurrentMediaTime() + delay; animation.duration = duration animation.fromValue = 1 animation.toValue = alpha animation.fillMode = kCAFillModeBoth CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey:"animateOpacity")*/ } /* --------------------------------------------------------------------------- */ /* Shake */ /* --------------------------------------------------------------------------- */ /** Shake Horizontally - parameter duration: duration ( default = 0.5 ) - parameter moveValues: moveValues ( default = [-12, 12, -8, 8, -4, 4, 0] ) - parameter completionEnd: (() -> ())? When animation is finished */ public func applyShakeHorizontally( duration duration:CFTimeInterval = 0.5, moveValues:[Float] = [-12, 12, -8, 8, -4, 4, 0], completionEnd: dispatch_block_t? = nil) { let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.values = moveValues CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey: "shake") } public func applyShakeVertically( duration duration:CFTimeInterval = 0.5, moveValues:[Float] = [(-12), (12), (-8), (8), (-4), (4), (0) ], completionEnd: (() -> ())) { let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.values = moveValues CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(animation, forKey: "shake") } /* --------------------------------------------------------------------------- */ /* Animates */ /* --------------------------------------------------------------------------- */ /** Set Animation Rotation on View - parameter angle: CGFloat ( example 360 = 360 degrees) - parameter duration: NSTimeInterval - parameter direction: UIViewContentMode ( .Left, .Right ) - parameter repeatCount: Float - parameter autoReverse: Bool - parameter completionEnd: (() -> ())? When animation is finished */ public func applyRotateToAngle( angle:CGFloat, duration:NSTimeInterval, direction:UIViewContentMode, repeatCount:Float = 0, autoReverse:Bool = false, completionEnd: dispatch_block_t? = nil ) { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = (direction == UIViewContentMode.Right ? angle.toDegreesToRadians : -angle.toDegreesToRadians) rotationAnimation.duration = duration rotationAnimation.autoreverses = autoReverse rotationAnimation.repeatCount = repeatCount rotationAnimation.removedOnCompletion = false rotationAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionLinear) CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(rotationAnimation,forKey:"transform.rotation.z") } /** Set animation Pulse on View - parameter toScale: CGFloat - parameter duration: NSTimeInterval - parameter repeatAnimate: Bool - parameter completionEnd: (() -> ())? When animation is finished */ public func applyPulseToSize( duration duration:NSTimeInterval, toScale:CGFloat, repeatAnimate:Bool, completionEnd: dispatch_block_t? = nil ) { let pulseAnimate = CABasicAnimation(keyPath: "transform.scale") pulseAnimate.duration = duration pulseAnimate.toValue = toScale pulseAnimate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pulseAnimate.autoreverses = true pulseAnimate.repeatCount = repeatAnimate ? Float.infinity : 0 CATransaction.setCompletionBlock(completionEnd) self.layer.addAnimation(pulseAnimate, forKey:"pulse") } @available(iOS 7,*) /** Motion Effects - parameter minimumRelativeValueX: Min Relative Value X ( default = -10.00 ) - parameter maximumRelativeValueX: Max Relative Value X ( default = 10.00 ) - parameter minimumRelativeValueY: Min Relative Value Y ( default = -10.00 ) - parameter maximumRelativeValueY: Max Relative Value Y ( default = 10.00 ) */ public func applyMotionEffects( minimumRelativeValueX:Float = -10.00, maximumRelativeValueX:Float = 10.00, minimumRelativeValueY:Float = -10.00, maximumRelativeValueY:Float = 10.00 ) { let horizontalEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type:.TiltAlongHorizontalAxis) horizontalEffect.minimumRelativeValue = minimumRelativeValueX horizontalEffect.maximumRelativeValue = maximumRelativeValueX let verticalEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) verticalEffect.minimumRelativeValue = minimumRelativeValueY verticalEffect.maximumRelativeValue = maximumRelativeValueY let motionEffectGroup = UIMotionEffectGroup() motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect] self.addMotionEffect(motionEffectGroup) } } /// ############################################################ /// /// Aspect /// /// ############################################################ /// // MARK: - The aspect public extension UIView { /** Set Border - parameter borderColor: UIColor ( default = UIColor.blackColor() ) - parameter borderWidth: CGFloat ( default = 1.0 ) */ public func applyBorder(borderColor:UIColor = UIColor.blackColor(),borderWidth:CGFloat = 1) { self.layer.borderColor = borderColor.CGColor self.layer.borderWidth = borderWidth self.clipsToBounds = true } /** Set Rounder - parameter radius: CGFloat */ public func applyRounder(radius:CGFloat) { self.layer.cornerRadius = radius self.clipsToBounds = true } /** Set Round */ public func applyRound() { self.layer.cornerRadius = self.width / 2 self.clipsToBounds = true } } // MARK: - Shadow public extension UIView { /** Plain Shadow <img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/> - parameter shadowColor: UIColor ( default = UIColor.blackColor() ) - parameter shadowOpacity: Float ( default = 0.4 ) - parameter shadowRadius: CGFloat ( default = 0.5 ) - parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: 10) ) */ public func applyPlainShadow( shadowColor:UIColor = UIColor.blackColor(), shadowOpacity:Float = 0.4, shadowRadius:CGFloat = 5, shadowOffset:CGSize = CGSize(width: 0, height: 10)) { self.layer.shadowColor = shadowColor.CGColor self.layer.shadowOffset = shadowOffset self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = shadowRadius } /** Curved Shadow <img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/> - parameter shadowOpacity: Float ( default = 0.3 ) - parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: -3) ) - parameter shadowColor: UIColor ( default = UIColor.blackColor() ) - parameter depth: CGFloat ( default = 11.0 ) - parameter lessDepth: CGFloat ( default = 0.8 ) - parameter curviness: CGFloat ( default = 5 ) - parameter radius: CGFloat ( default = 1 ) */ public func applyCurvedShadow( shadowOpacity shadowOpacity:Float = 0.3, shadowOffset:CGSize = CGSize(width: 0, height: -3), shadowColor:UIColor = UIColor.blackColor(), depth:CGFloat = 11.00 , lessDepth:CGFloat = 0.8, curviness:CGFloat = 5, radius:CGFloat = 1 ) { let path = UIBezierPath() // top left path.moveToPoint(CGPoint(x: radius, y: self.height)) // top right path.addLineToPoint(CGPoint(x: self.width - 2 * radius, y: self.height)) // bottom right + a little extra path.addLineToPoint(CGPoint(x: self.width - 2 * radius, y: self.height + depth)) // path to bottom left via curve path.addCurveToPoint( CGPoint(x: radius, y: self.height + depth), controlPoint1: CGPoint( x: self.width - curviness, y: self.height + (lessDepth * depth) - curviness), controlPoint2: CGPoint( x: curviness, y: self.height + (lessDepth * depth) - curviness)) self.layer.shadowPath = path.CGPath self.layer.shadowColor = shadowColor.CGColor self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = radius self.layer.shadowOffset = shadowOffset } /** Hover Shadow <img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/> */ public func applyHoverShadow() { let path = UIBezierPath(roundedRect: CGRect(x: 5, y: self.height + 5, width: self.width - 10, height: 15), cornerRadius: 10) self.layer.shadowPath = path.CGPath self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOpacity = 0.2 self.layer.shadowRadius = 5 self.layer.shadowOffset = CGSize(width: 0, height: 0) } /** Flat shadow <img src="http://yannickstephan.com/easyhelper/flatshadow.png" height="100" width="100"/> */ public func applyFlatShadow(){ self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOffset = CGSizeMake(0.0, 2.0) self.layer.masksToBounds = false self.layer.shadowRadius = 1.0 self.layer.shadowOpacity = 0.5 } }
mit
7b08f65dfdd5b219a96d4768d0bfa605
35.495918
203
0.532797
5.327078
false
false
false
false
zxl20zxl/YLSwiftLearn
YLSwiftLearn/MyPlayground.playground/Contents.swift
1
862
//: Playground - noun: a place where people can play import UIKit // HelloWorld var str:String = "Hello, playground" str + "s" let c:Character = "t" str.append(c) str.appendContentsOf("sdfasdfas") str let str2:String = "hello" str2 + "s" str2 // Dictionary var dic:Dictionary<String, String> = ["s":"1", "r":"2"] for (key, value) in dic { print("key:\(key), value:\(value)") } // Array var array:Array<String> = ["s", "t", "u"] var num = 1 for i in 0..<array.count { print("value:\(array[i])") num++ } for i in 0...100 { num++ } // Tuple var tuple = (404, "Not Found") tuple.0 tuple.1 var tuple2 = (s1:"value", s2:"hello") tuple2.s1 // Optional var opStr:String? = "Hello" print("this is \(opStr)") var count:Int? = 99 var i:Int = count! if let validCount = count { validCount } else { count }
apache-2.0
ac807fba4666e893f42110c7b3c9ec17
9.911392
55
0.589327
2.719243
false
false
false
false
cxchope/NyaaCatAPP_iOS
nyaacatapp/TableVC.swift
1
5904
// // TableVC.swift // nyaacatapp // // Created by 神楽坂雅詩 on 16/3/27. // Copyright © 2016年 KagurazakaYashi. All rights reserved. // import UIKit class TableVC: UITableViewController { var 链接:[[String]] = [[String]]() var 禁止游客浏览:Int = 0 //0:允许,1:只能看标题,2:封锁 override func viewDidLoad() { super.viewDidLoad() if (全局_用户名 == nil && 禁止游客浏览 == 2) { title = "禁止游客浏览" tableView.isHidden = true } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 链接.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let 单元格ID:String = "ECell" let 行数:Int = (indexPath as NSIndexPath).row var 单元格:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: 单元格ID) if(单元格 == nil) { 单元格 = UITableViewCell(style: .subtitle, reuseIdentifier: 单元格ID) 单元格?.accessoryType = .disclosureIndicator // 单元格?.backgroundColor = UIColor.clearColor() // 单元格?.detailTextLabel?.textColor = UIColor.lightGrayColor() // 单元格?.textLabel?.textColor = UIColor.blackColor() } let 当前链接:[String] = 链接[行数] let 当前名称:String = 当前链接[0] let 当前修正名称:String = 当前名称.substring(from: 当前名称.characters.index(当前名称.startIndex, offsetBy: 1)) let 名称和时间:[String] = 当前修正名称.components(separatedBy: "|") if (名称和时间.count >= 2) { 单元格?.textLabel?.text = 名称和时间[1] 单元格?.detailTextLabel?.text = 名称和时间[0] } // return 单元格! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let 行数:Int = (indexPath as NSIndexPath).row let 当前链接:[String] = 链接[行数] let 当前名称:String = 当前链接[0] let 名称日期:[String] = 当前名称.substring(from: 当前名称.characters.index(当前名称.startIndex, offsetBy: 1)).components(separatedBy: "|") //let 日期:String = 名称日期[0] let 名称:String = 名称日期[1] if (全局_用户名 == nil && 禁止游客浏览 == 1) { let 提示:UIAlertController = UIAlertController(title: "游客模式不能浏览此条目", message: 名称, preferredStyle: UIAlertControllerStyle.alert) let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) 提示.addAction(取消按钮) self.present(提示, animated: true, completion: nil) } else { let 网址:String = "\(全局_喵窩API["API域名"]!)\(当前链接[1])" let vc:BrowserVC = BrowserVC() self.navigationController?.pushViewController(vc, animated: true) vc.装入网页(网址, 标题: 名称) } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
a6025965489abf69972875ecf6a671b5
38.036232
157
0.643958
4.553677
false
false
false
false
matthew-compton/Photorama
Photorama/PhotosViewController.swift
1
2519
// // PhotosViewController.swift // Photorama // // Created by Matthew Compton on 10/22/15. // Copyright © 2015 Big Nerd Ranch. All rights reserved. // import UIKit class PhotosViewController: UIViewController, UICollectionViewDelegate { @IBOutlet var collectionView: UICollectionView! var store: PhotoStore! let photoDataSource = PhotoDataSource() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = photoDataSource collectionView.delegate = self store.fetchRecentPhotos() { (photosResult) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in switch photosResult { case let .Success(photos): print("Successfully found \(photos.count) recent photos.") self.photoDataSource.photos = photos case let .Failure(error): self.photoDataSource.photos.removeAll() print("Error fetching recent photos: \(error)") } self.collectionView.reloadSections(NSIndexSet(index: 0)) }) } } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let photo = photoDataSource.photos[indexPath.row] store.fetchImageForPhoto(photo) { (result) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in let photoIndex = self.photoDataSource.photos.indexOf(photo)! let photoIndexPath = NSIndexPath(forRow: photoIndex, inSection: 0) if let cell = self.collectionView.cellForItemAtIndexPath(photoIndexPath) as? PhotoCollectionViewCell { cell.updateWithImage(photo.image) } }) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowPhoto" { if let selectedIndexPath = collectionView.indexPathsForSelectedItems()?.first { let photo = photoDataSource.photos[selectedIndexPath.row] let destinationVC = segue.destinationViewController as! PhotoInfoViewController destinationVC.photo = photo destinationVC.store = store } } } }
apache-2.0
191cc2cf56954dc8afece5fbd8399edf
36.58209
146
0.604845
5.910798
false
false
false
false
cockscomb/HUDKit
Example/ViewController.swift
1
2547
// The MIT License (MIT) // // Copyright (c) 2016 Hiroki Kato // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import HUDKit class ViewController: UIViewController, UIViewControllerTransitioningDelegate { @IBAction func showProgress(sender: AnyObject) { let progress = HUDProgressViewController(status: "Doing...") presentViewController(progress, animated: true) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) { self.dismissViewControllerAnimated(true, completion: nil) return } return } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.destinationViewController { case let imageViewController as ImageViewController: imageViewController.modalPresentationStyle = .Custom imageViewController.transitioningDelegate = self imageViewController.image = UIImage(named: "Fuji.jpg") default: break } } func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let HUD = HUDPresentationController(presentedViewController: presented, presentingViewController: presenting) HUD.dismissWhenTapped = true return HUD } }
mit
1fdabd93de81c8f10b93e6c9ddc6f478
43.684211
219
0.723204
5.197959
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/ExerciseProgress.swift
1
2053
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import Stockpile public class ExerciseProgress: NSObject, NSSecureCoding, IncludedPullable { public static var supportsSecureCoding: Bool { return true } public var exercisesAvailable: Int? public var exercisesTaken: Int? public var pointsPossible: Double? public var pointsScored: Double? public var hasProgress: Bool { return !(self.pointsPossible?.isZero ?? true) } public var percentage: Double? { guard let scored = self.pointsScored else { return nil } guard let possible = self.pointsPossible, !possible.isZero else { return nil } return Double(scored) / Double(possible) } public required init(object: ResourceData) throws { self.exercisesAvailable = try object.value(for: "exercise_available") self.exercisesTaken = try object.value(for: "exercise_taken") self.pointsPossible = try object.value(for: "points_possible") self.pointsScored = try object.value(for: "points_scored") } public required init(coder decoder: NSCoder) { self.exercisesAvailable = decoder.decodeObject(of: NSNumber.self, forKey: "exercise_available")?.intValue self.exercisesTaken = decoder.decodeObject(of: NSNumber.self, forKey: "exercise_taken")?.intValue self.pointsPossible = decoder.decodeObject(of: NSNumber.self, forKey: "points_possible")?.doubleValue self.pointsScored = decoder.decodeObject(of: NSNumber.self, forKey: "points_scored")?.doubleValue } public func encode(with coder: NSCoder) { coder.encode(self.exercisesAvailable.map(NSNumber.init(value:)), forKey: "exercise_available") coder.encode(self.exercisesTaken.map(NSNumber.init(value:)), forKey: "exercise_taken") coder.encode(self.pointsPossible.map(NSNumber.init(value:)), forKey: "points_possible") coder.encode(self.pointsScored.map(NSNumber.init(value:)), forKey: "points_scored") } }
gpl-3.0
7fb71c27d56ec47c8283674f6bb4aa1e
40.877551
113
0.707602
4.153846
false
false
false
false
superk589/CGSSGuide
DereGuide/Settings/View/DonationQAView.swift
2
1618
// // DonationQAView.swift // DereGuide // // Created by zzk on 2017/1/3. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class DonationQAView: UIView { let questionLabel = UILabel() let answerLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) addSubview(questionLabel) questionLabel.snp.makeConstraints { (make) in make.top.left.equalToSuperview() make.height.equalTo(16) } questionLabel.font = .systemFont(ofSize: 14) addSubview(answerLabel) answerLabel.snp.makeConstraints { (make) in make.left.equalTo(questionLabel) make.right.equalToSuperview() make.top.equalTo(questionLabel.snp.bottom).offset(6) } answerLabel.textColor = .darkGray answerLabel.font = .systemFont(ofSize: 12) answerLabel.numberOfLines = 0 let line = UIView() addSubview(line) line.snp.makeConstraints { (make) in make.left.equalTo(questionLabel) make.right.equalToSuperview() make.top.equalTo(answerLabel.snp.bottom).offset(10) make.height.equalTo(1 / Screen.scale) make.bottom.equalToSuperview() } line.backgroundColor = .lightGray } func setup(question: String, answer:String) { questionLabel.text = question answerLabel.text = answer } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0468f8c486ac600cc18ae2d820173d85
26.87931
64
0.606679
4.382114
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorModel/Model/LabColorModel.swift
1
7616
// // LabColorModel.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct LabColorModel: ColorModel { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 3 } @inlinable @inline(__always) public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> { precondition(0..<numberOfComponents ~= i, "Index out of range.") switch i { case 0: return 0...100 default: return -128...128 } } /// The lightness dimension. public var lightness: Double /// The a color component. public var a: Double /// The b color component. public var b: Double @inlinable @inline(__always) public init() { self.lightness = 0 self.a = 0 self.b = 0 } @inlinable @inline(__always) public init(lightness: Double, a: Double, b: Double) { self.lightness = lightness self.a = a self.b = b } @inlinable @inline(__always) public init(lightness: Double, chroma: Double, hue: Double) { self.lightness = lightness self.a = chroma * cos(2 * .pi * hue) self.b = chroma * sin(2 * .pi * hue) } @inlinable public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } } extension LabColorModel { @inlinable @inline(__always) public static var black: LabColorModel { return LabColorModel() } } extension LabColorModel { @inlinable @inline(__always) public var hue: Double { get { return positive_mod(0.5 * atan2(b, a) / .pi, 1) } set { self = LabColorModel(lightness: lightness, chroma: chroma, hue: newValue) } } @inlinable @inline(__always) public var chroma: Double { get { return hypot(a, b) } set { self = LabColorModel(lightness: lightness, chroma: newValue, hue: hue) } } } extension LabColorModel { @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> LabColorModel { return LabColorModel(lightness: transform(lightness), a: transform(a), b: transform(b)) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, lightness) updateAccumulatingResult(&accumulator, a) updateAccumulatingResult(&accumulator, b) return accumulator } @inlinable @inline(__always) public func combined(_ other: LabColorModel, _ transform: (Double, Double) -> Double) -> LabColorModel { return LabColorModel(lightness: transform(self.lightness, other.lightness), a: transform(self.a, other.a), b: transform(self.b, other.b)) } } extension LabColorModel { public typealias Float16Components = FloatComponents<float16> public typealias Float32Components = FloatComponents<Float> @frozen public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents { public typealias Indices = Range<Int> @inlinable @inline(__always) public static var numberOfComponents: Int { return 3 } public var lightness: Scalar public var a: Scalar public var b: Scalar @inline(__always) public init() { self.lightness = 0 self.a = 0 self.b = 0 } @inline(__always) public init(lightness: Scalar, a: Scalar, b: Scalar) { self.lightness = lightness self.a = a self.b = b } @inlinable @inline(__always) public init(_ color: LabColorModel) { self.lightness = Scalar(color.lightness) self.a = Scalar(color.a) self.b = Scalar(color.b) } @inlinable @inline(__always) public init<T>(_ components: FloatComponents<T>) { self.lightness = Scalar(components.lightness) self.a = Scalar(components.a) self.b = Scalar(components.b) } @inlinable public subscript(position: Int) -> Scalar { get { return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue } } } @inlinable @inline(__always) public var model: LabColorModel { get { return LabColorModel(lightness: Double(lightness), a: Double(a), b: Double(b)) } set { self = FloatComponents(newValue) } } } } extension LabColorModel.FloatComponents { @inlinable @inline(__always) public func map(_ transform: (Scalar) -> Scalar) -> LabColorModel.FloatComponents<Scalar> { return LabColorModel.FloatComponents(lightness: transform(lightness), a: transform(a), b: transform(b)) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, lightness) updateAccumulatingResult(&accumulator, a) updateAccumulatingResult(&accumulator, b) return accumulator } @inlinable @inline(__always) public func combined(_ other: LabColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> LabColorModel.FloatComponents<Scalar> { return LabColorModel.FloatComponents(lightness: transform(self.lightness, other.lightness), a: transform(self.a, other.a), b: transform(self.b, other.b)) } }
mit
9278adf84f995006094799697931672c
29.95935
161
0.60583
4.587952
false
false
false
false
BinaryDennis/SwiftPocketBible
Extensions/UITableViewExtensions.swift
1
1734
public extension UITableView { /** This method adjustes the height of tableHeaderView and tableFooterView, assuming the custom header/footer views are setup using autolayout. **Note:** Only call this method if the custom header/footer view has a multi-line label. **Important** this method should be called in a view controllers `viewDidLayoutSubviews` method, like this ``` override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.sizeHeaderAndFooterToFit() } ``` */ public func sizeHeaderAndFooterToFit() { if let headerView = self.tableHeaderView { let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height var headerFrame = headerView.frame // If we don't have this check, viewDidLayoutSubviews() will get called // repeatedly, thus causing the app to hang if height != headerFrame.size.height { headerFrame.size.height = height headerView.frame = headerFrame self.tableHeaderView = headerView } } if let footerView = self.tableFooterView { let height = footerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height var footerFrame = footerView.frame // If we don't have this check, viewDidLayoutSubviews() will get called // repeatedly, thus causing the app to hang if height != footerFrame.size.height { footerFrame.size.height = height footerView.frame = footerFrame self.tableFooterView = footerView } } } }
mit
378b73bb0aae2022ac70675e11bb2da0
35.893617
97
0.635525
5.938356
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/HackerRank/PrimsMST/PrimsMSTNode.swift
1
1205
// // PrimsMSTNode.swift // WhiteBoardCodingChallenges // // Created by William Boles on 28/06/2016. // Copyright © 2016 Boles. All rights reserved. // import Foundation class PrimsMSTNode: NSObject { // MARK: Properties var value: Int var connected = false var edges: Dictionary = { return [PrimsMSTNode: PrimsMSTEdge]() }() // MARK: Lifecycle init(value: Int) { self.value = value super.init() } // MARK: Edge func addEdge(destination: PrimsMSTNode, weight: Int) { let existingEdge = edges[destination] if let existingEdge = existingEdge { if existingEdge.weight > weight { edges[destination] = PrimsMSTEdge(source: self, destination: destination, weight: weight) destination.addEdge(destination: self, weight: weight) } } else { edges[destination] = PrimsMSTEdge(source: self, destination: destination, weight: weight) destination.addEdge(destination: self, weight: weight) } } }
mit
ccf055eec4cdef9147ce2701af47d7fe
21.716981
105
0.550664
4.703125
false
false
false
false
barteljan/RocketChatAdapter
Example/Pods/VISPER-CommandBus/Pod/Classes/CommandBus/CompatibleCommandBus.swift
1
1742
// // CompatibleCommandBus.swift // Pods // // Created by Jan Bartel on 25.02.16. // // import Foundation public class CompatibleCommandBus: CommandBus,CompatibleCommandBusProtocol { let CommandNotFoundErrorDomain = "CommandNotFoundErrorDomain" //just for objective c compatability public func process(command: AnyObject!, completion: ((result: AnyObject?, error: AnyObject?) -> Void)?){ do{ try super.process(command) { (myResult : AnyObject?, myError: ErrorType?) -> Void in if(myError != nil){ completion?(result: myResult, error: (myError as! AnyObject)) }else{ completion?(result: myResult, error: nil) } } }catch let error { if(error is CommandHandlerNotFoundError){ let myError = error as! CommandHandlerNotFoundError let nsError = self.nsErrorFor(myError) completion?(result: nil, error: nsError) }else{ completion?(result: nil, error: (error as! AnyObject)) } } } func nsErrorFor(myError:CommandHandlerNotFoundError) -> NSError{ let userInfo : [NSObject : AnyObject] = [NSLocalizedDescriptionKey : "CommandHandler for command:" + String(myError.command) + " not found!"] let nsError = NSError(domain: self.CommandNotFoundErrorDomain, code: 2, userInfo: userInfo) return nsError } public func addHandler(handler:AnyObject){ super.addHandler(handler as! CommandHandlerProtocol) } public func removeHandler(handler:AnyObject){ super.removeHandler(handler as! CommandHandlerProtocol) } }
mit
0fe89d7965e0145f66926c8d0b946ae5
32.5
149
0.617107
4.772603
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/WordPressShareExtension/UIImageView+Extensions.swift
2
3991
import Foundation extension UIImageView { /// Downloads an image and updates the UIImageView Instance /// /// - Parameter url: The URL of the target image /// public func downloadImage(_ url: URL) { // Hit the cache if let cachedImage = Downloader.cache.object(forKey: url as AnyObject) as? UIImage { self.image = cachedImage return } // Cancel any previous OP's if let task = downloadTask { task.cancel() downloadTask = nil } // Helpers let scale = mainScreenScale let size = CGSize(width: blavatarSizeInPoints, height: blavatarSizeInPoints) // Hit the Backend var request = URLRequest(url: url) request.httpShouldHandleCookies = false request.addValue("image/*", forHTTPHeaderField: "Accept") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { [weak self] data, response, error in guard let data = data, let image = UIImage(data: data, scale: scale) else { return } DispatchQueue.main.async { // Resize if needed! var resizedImage = image if image.size.height > size.height || image.size.width > size.width { resizedImage = image.resizedImage(with: .scaleAspectFit, bounds: size, interpolationQuality: .high) } // Update the Cache Downloader.cache.setObject(resizedImage, forKey: url as AnyObject) self?.image = resizedImage } }) downloadTask = task task.resume() } /// Downloads a resized Blavatar, meant to perfectly fit the UIImageView's Dimensions /// /// - Parameter url: The URL of the target blavatar /// public func downloadBlavatar(_ url: URL) { var components = URLComponents(url: url, resolvingAgainstBaseURL: true) components?.query = String(format: Downloader.blavatarResizeFormat, blavatarSize) if let updatedURL = components?.url { downloadImage(updatedURL) } } /// Returns the desired Blavatar Side-Size, in pixels /// fileprivate var blavatarSize: Int { return blavatarSizeInPoints * Int(mainScreenScale) } /// Returns the desired Blavatar Side-Size, in points /// fileprivate var blavatarSizeInPoints: Int { var size = Downloader.defaultImageSize if !bounds.size.equalTo(CGSize.zero) { size = max(bounds.width, bounds.height) } return Int(size) } /// Returns the Main Screen Scale /// fileprivate var mainScreenScale: CGFloat { return UIScreen.main.scale } /// Stores the current DataTask, in charge of downloading the remote Image /// fileprivate var downloadTask: URLSessionDataTask? { get { return objc_getAssociatedObject(self, Downloader.taskKey) as? URLSessionDataTask } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, Downloader.taskKey, newValue, policy) } } /// Private helper structure /// fileprivate struct Downloader { /// Default Blavatar Image Size /// static let defaultImageSize = CGFloat(40) /// Blavatar Resize Query FormatString /// static let blavatarResizeFormat = "d=404&s=%d" /// Stores all of the previously downloaded images /// static let cache = NSCache<AnyObject, AnyObject>() /// Key used to associate a Download task to the current instance /// static let taskKey = "downloadTaskKey" } }
gpl-2.0
c3f18d0a850f56923252df3e5e672826
29.937984
108
0.58206
5.328438
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinUI/CoinView/Analytics/NewAnalyticsEvents+CoinView.swift
1
5428
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import FeatureCoinDomain extension AnalyticsEvents.New { enum CoinViewAnalyticsEvent: AnalyticsEvent { var type: AnalyticsEventType { .nabu } case coinViewOpen(currency: String, origin: String) case coinViewClosed(currency: String) case chartEngaged(currency: String, timeInterval: String, origin: Origin = .coinView) case chartDisengaged(currency: String, timeInterval: String, origin: Origin = .coinView) case chartTimeIntervalSelected(currency: String, timeInterval: String, origin: Origin = .coinView) case buySellClicked(type: TransactionType, origin: Origin = .coinView) case buyReceiveClicked(currency: String, type: TransactionType, origin: Origin = .coinView) case sendReceiveClicked(currency: String, type: TransactionType, origin: Origin = .coinView) case explainerViewed(currency: String, accountType: AccountType, origin: Origin = .coinView) case explainerAccepted(currency: String, accountType: AccountType, origin: Origin = .coinView) case hyperlinkClicked(currency: String, selection: Selection, origin: Origin = .coinView) case transactionTypeClicked( currency: String, accountType: AccountType, transactionType: TransactionType, origin: Origin = .coinView ) case walletsAccountsClicked(currency: String, accountType: AccountType, origin: Origin = .coinView) case walletsAccountsViewed(currency: String, accountType: AccountType, origin: Origin = .coinView) case connectToTheExchangeActioned(currency: String, origin: Origin = .coinView) case coinAddedToWatchlist(currency: String, origin: Origin = .coinView) case coinRemovedFromWatchlist(currency: String, origin: Origin = .coinView) enum Origin: String, StringRawRepresentable { case coinView = "COIN_VIEW" } enum Selection: String, StringRawRepresentable { case explorer = "EXPLORER" case learnMore = "LEARN_MORE" case officialWebsiteWeb = "OFFICIAL_WEBSITE_WEB" case viewLegal = "VIEW_LEGAL" case websiteWallet = "WEBSITE_WALLET" case whitePaper = "WHITE_PAPER" } enum TransactionType: String, StringRawRepresentable { case activity = "ACTIVITY" case add = "ADD" case buy = "BUY" case sell = "SELL" case receive = "RECEIVE" case send = "SEND" case deposit = "DEPOSIT" case rewardsSummary = "REWARDS_SUMMARY" case swap = "SWAP" case withdraw = "WITHDRAW" // swiftlint:disable cyclomatic_complexity init?(_ tag: Tag) { switch tag { case blockchain.ux.asset.account.activity: self = .activity case blockchain.ux.asset.account.buy: self = .buy case blockchain.ux.asset.account.receive: self = .receive case blockchain.ux.asset.account.rewards.summary: self = .rewardsSummary case blockchain.ux.asset.account.rewards.withdraw: self = .withdraw case blockchain.ux.asset.account.rewards.deposit: self = .add case blockchain.ux.asset.account.exchange.withdraw: self = .withdraw case blockchain.ux.asset.account.exchange.deposit: self = .deposit case blockchain.ux.asset.account.sell: self = .sell case blockchain.ux.asset.account.send: self = .send case blockchain.ux.asset.account.swap: self = .swap default: return nil } } } enum AccountType: String, StringRawRepresentable { case rewards = "REWARDS_ACCOUNT" case trading = "CUSTODIAL" case userKey = "USERKEY" case exchange = "EXCHANGE_ACCOUNT" init(_ account: Account.Snapshot) { switch account.accountType { case .privateKey: self = .userKey case .interest: self = .rewards case .trading: self = .trading case .exchange: self = .exchange } } } } } extension FeatureCoinDomain.Series { var analytics: String { switch self { case .now: return "LIVE" case .day: return "1D" case .week: return "1W" case .month: return "1M" case .year: return "1Y" case .all: return "ALL" default: return "NONE" } } } extension AnalyticsEventRecorderAPI { func record(event: AnalyticsEvents.New.CoinViewAnalyticsEvent) { record(event: event as AnalyticsEvent) } func record(events: [AnalyticsEvents.New.CoinViewAnalyticsEvent]) { record(events: events as [AnalyticsEvent]) } }
lgpl-3.0
5be8791be4887ea19915484f5933c6d6
34.940397
107
0.575272
4.871634
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LayoutInspector/LayoutInspector/Classes/UI Layer/AttributesWidget/TextAttributeCell.swift
2
1602
// // ObjectInspectionTextDataCell.swift // LayoutInspectorExample // // Created by Igor Savynskyi on 1/2/19. // Copyright © 2019 Ihor Savynskyi. All rights reserved. // import UIKit class TextAttributeCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var valueLabel: UILabel! @IBOutlet private weak var trailingSeparator: UIView! static func estimatedHeight(title: String, value: String?, cellWidth: CGFloat) -> CGFloat { let contentWidthConstraint = cellWidth - Layout.contentInsets.left - Layout.contentInsets.right let titleHeight = title.height(withConstrainedWidth: contentWidthConstraint, font: Styleguide.font) let valueHeight = value?.height(withConstrainedWidth: contentWidthConstraint, font: Styleguide.font) ?? 0 return titleHeight + valueHeight + Layout.contentInsets.top + Layout.contentInsets.bottom } // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() configureStyles() } } // MARK: - Nested types private extension TextAttributeCell { enum Layout { static let contentInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 4) } enum Styleguide { static let font: UIFont = .appH3 } } extension TextAttributeCell: Themeable { func configureStyles() { titleLabel.font = Styleguide.font titleLabel.textColor = .appLight valueLabel.font = Styleguide.font valueLabel.textColor = .appLight trailingSeparator.backgroundColor = .secondaryLightColor } }
mit
5f9fb9349be39d2292ee5b8740078c31
31.673469
113
0.700187
4.587393
false
false
false
false
Jnosh/swift
test/SourceKit/CodeFormat/indent-pound-if.swift
70
1158
#if os(iOS) class a { func b () { let i = 3 } } #else class a { func b () { let i = 3 } } #endif #if os(iOS) class a { func b () { let i = 3 } } #elseif os(OSX) class a { func b () { let i = 3 } } #endif print(false) // RUN: %sourcekitd-test -req=format -line=4 -length=1 %s -- -target x86_64-apple-macosx10.9 > %t.response // RUN: %sourcekitd-test -req=format -line=7 -length=1 %s -- -target x86_64-apple-macosx10.9 > %t.response // RUN: %sourcekitd-test -req=format -line=10 -length=1 %s -- -target x86_64-apple-macosx10.9 >> %t.response // RUN: %sourcekitd-test -req=format -line=16 -length=1 %s -- -target x86_64-apple-macosx10.9 >> %t.response // RUN: %sourcekitd-test -req=format -line=20 -length=1 %s -- -target x86_64-apple-macosx10.9 >> %t.response // RUN: %sourcekitd-test -req=format -line=22 -length=1 %s -- -target x86_64-apple-macosx10.9 >> %t.response // RUN: %FileCheck --strict-whitespace %s <%t.response // CHECK: key.sourcetext: "#else" // CHECK: key.sourcetext: " let i = 3" // CHECK: key.sourcetext: " func b () {" // CHECK: key.sourcetext: "#elseif os(OSX)" // CHECK: key.sourcetext: " func b () {"
apache-2.0
9919d49ba84a5bca9254918d6fb71298
27.243902
108
0.615717
2.637813
false
true
false
false
sora0077/QiitaKit
QiitaKit/src/Utility/Comment+JSON.swift
1
1120
// // Comment+JSON.swift // QiitaKit // // Created by 林達也 on 2015/06/24. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit func _Comment(object: AnyObject!) throws -> Comment { try validation(object) let object = object as! GetComment.SerializedObject return Comment( body: object["body"] as! String, created_at: object["created_at"] as! String, id: object["id"] as! String, rendered_body: object["rendered_body"] as! String, updated_at: object["updated_at"] as! String, user: try _User(object["user"]) ) } func _Comments(object: AnyObject!) throws -> [Comment] { try validation(object) let object = object as! [GetComment.SerializedObject] return try object.map { try _Comment($0) } } extension QiitaRequestToken where Response == Comment, SerializedObject == [String: AnyObject] { public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { return try _Comment(object) } }
mit
9b3be63daf82834cb34eedd1a3c417f4
25.97561
126
0.646474
4.096296
false
false
false
false
lukemetz/Paranormal
Paranormal/Paranormal/ThreadUtils.swift
3
2811
import Foundation import GPUImage private let _ThreadUtilsShared = ThreadUtils() enum ThreadState : Int { case Waiting = 0 case WorkTodo } public class ThreadUtils : NSObject { var gpuImageThread : NSThread? var editClosures : [() -> Void] = [] var updateClosures : [() -> Void] = [] var doneProcessing : Bool = true var lock : NSLock = NSLock() var conditionLock : NSConditionLock override init() { conditionLock = NSConditionLock(condition: ThreadState.Waiting.rawValue) super.init() gpuImageThread = NSThread(target: self, selector: NSSelectorFromString("threadMain"), object: nil) gpuImageThread?.start() } dynamic func threadMain() { while(true) { // TODO turn this off conditionLock.lockWhenCondition(ThreadState.WorkTodo.rawValue) conditionLock.unlockWithCondition(ThreadState.Waiting.rawValue) autoreleasepool { while (self.editClosures.count > 0) { self.doneProcessing = false self.lock.lock() let closure = self.editClosures.removeAtIndex(0) self.lock.unlock() closure() } while (self.updateClosures.count > 0) { self.doneProcessing = false self.lock.lock() let closure = self.updateClosures.removeLast() self.updateClosures = [] self.lock.unlock() closure() } self.doneProcessing = true } } } class var sharedInstance: ThreadUtils { return _ThreadUtilsShared } private class func runWork() { sharedInstance.conditionLock.lock() sharedInstance.conditionLock.unlockWithCondition(ThreadState.WorkTodo.rawValue) } public class func runGPUImage(block : () -> Void) { ThreadUtils.sharedInstance.doneProcessing = false sharedInstance.lock.lock() ThreadUtils.sharedInstance.updateClosures.append(block) sharedInstance.lock.unlock() runWork() } public class func runGPUImageDestructive(block : () -> Void) { ThreadUtils.sharedInstance.doneProcessing = false sharedInstance.lock.lock() ThreadUtils.sharedInstance.editClosures.append(block) sharedInstance.lock.unlock() runWork() } class func runCocos(closure : () -> Void) { if NSThread.isMainThread() { closure() } else { NSOperationQueue.mainQueue().addOperationWithBlock(closure) } } public class func doneProcessingGPUImage() -> Bool { return sharedInstance.doneProcessing; } }
mit
ea1a9a1b7b88f4e0d6a2405fa7307022
29.89011
87
0.593383
4.984043
false
false
false
false
pietrorea/UniqueConstraintsSample
UniqueConstraintsSample/UniqueConstraintsSample/AppDelegate.swift
1
6414
// // AppDelegate.swift // UniqueConstraintsSample // // Created by Pietro Rea on 11/15/15. // Copyright © 2015 Pietro Rea. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let rootVC = window?.rootViewController if let viewController = rootVC as? ViewController { viewController.context = managedObjectContext } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.pietrorea.UniqueConstraintsSample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("UniqueConstraintsSample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
3c5e89fb41391d8580f9fdcbec8903a8
53.347458
291
0.719164
5.960037
false
false
false
false