repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lieonCX/Live
Live/Others/Lib/RITLImagePicker/Photofiles/Navigation/RITLPhotoNavigationViewModel.swift
1
1463
// // RITLPhotoNavigationViewModel.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/10. // Copyright © 2017年 YueWen. All rights reserved. // import UIKit let RITLPhotoOriginSize:CGSize = CGSize(width: -100, height: -100) /// 主导航控制器的viewModel class RITLPhotoNavigationViewModel: RITLBaseViewModel { /// 最大的选择数量,默认为9 var maxNumberOfSelectedPhoto = 9 { willSet { guard newValue > 0 else { return } RITLPhotoCacheManager.sharedInstance.maxNumeberOfSelectedPhoto = newValue } } /// 当前图片的规格,默认为RITLPhotoOriginSize,原始比例 var imageSize = RITLPhotoOriginSize { willSet { RITLPhotoCacheManager.sharedInstance.imageSize = newValue } } /// 获取图片之后的闭包 var completeUsingImage:(([UIImage]) -> Void)? { willSet { RITLPhotoBridgeManager.sharedInstance.completeUsingImage = newValue } } /// 获取图片数据之后的闭包 var completeUsingData:(([Data]) -> Void)? { willSet { RITLPhotoBridgeManager.sharedInstance.completeUsingData = newValue } } deinit { print("\(self.self)deinit") } }
mit
NetFunctional/reddit4watch
Reddit4Watch WatchKit Extension/ThumbnailPostInterfaceController.swift
1
1885
// // ThumbnailPostInterfaceController.swift // Reddit4Watch // // Created by Gregory Hogue on 2015-01-30. // Copyright (c) 2015 NetFunctional. All rights reserved. // import WatchKit import Foundation class ThumbnailPostInterfaceController: WKInterfaceController { var redditURL: NSString = "" @IBOutlet weak var postTitleLabel: WKInterfaceLabel! @IBOutlet weak var postThumbnailImage: WKInterfaceImage! @IBOutlet weak var postScoreLabel: WKInterfaceLabel! @IBOutlet weak var postSubredditLabel: WKInterfaceLabel! @IBOutlet weak var postAuthorLabel: WKInterfaceLabel! @IBOutlet weak var postDateLabel: WKInterfaceLabel! @IBAction func iPhoneButtonAction() { println(redditURL) WKInterfaceController.openParentApplication(["redditURL": redditURL], reply: {(reply, error) -> Void in println("Reply to openParentApplication received from iPhone app") }) } init(context: AnyObject?) { super.init() if let post = context as? NSDictionary { redditURL = (post["permalink"] as? String)! postTitleLabel.setText(post["title"] as? String) postScoreLabel.setText(toString(post["score"] as! Int)) postSubredditLabel.setText(post["subreddit"] as? String) postAuthorLabel.setText(post["author"] as? String) let url = post["url"] as? String postThumbnailImage.setImage(UIImage(data: NSData(contentsOfURL: NSURL(string: (post["thumbnail"] as? String)!)!)!)) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM d, yyyy, h:mm a" postDateLabel.setText(dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(post["created"] as! Int)))) } } }
bsd-2-clause
BrooksWon/ios-charts
Charts/Classes/Renderers/LineScatterCandleRadarChartRenderer.swift
59
1255
// // LineScatterCandleRadarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 29/7/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class LineScatterCandleRadarChartRenderer: ChartDataRendererBase { public override init(animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) } /// Draws vertical & horizontal highlight-lines if enabled. /// :param: context /// :param: points /// :param: horizontal /// :param: vertical public func drawHighlightLines(#context: CGContext, points: UnsafePointer<CGPoint>, horizontal: Bool, vertical: Bool) { // draw vertical highlight lines if vertical { CGContextStrokeLineSegments(context, points, 2) } // draw horizontal highlight lines if horizontal { var pts = UnsafePointer<CGPoint>() CGContextStrokeLineSegments(context, points.advancedBy(2), 2) } } }
apache-2.0
zqqf16/SYM
SYM/UI/MainWindowController.swift
1
6958
// The MIT License (MIT) // // Copyright (c) 2017 - present zqqf16 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Cocoa import Combine extension NSImage { static let alert: NSImage = #imageLiteral(resourceName: "alert") static let symbol: NSImage = #imageLiteral(resourceName: "symbol") } class MainWindowController: NSWindowController { // Toolbar items @IBOutlet var symButton: NSButton! @IBOutlet var downloadItem: DownloadToolbarItem! @IBOutlet var deviceItem: NSToolbarItem! @IBOutlet var indicator: NSProgressIndicator! @IBOutlet var dsymPopUpButton: DsymToolBarButton! var isSymbolicating: Bool = false { didSet { DispatchQueue.main.async { if self.isSymbolicating { self.indicator.startAnimation(nil) self.indicator.isHidden = false } else { self.indicator.stopAnimation(nil) self.indicator.isHidden = true } } } } private var crashCancellable = Set<AnyCancellable>() // Dsym private var dsymManager = DsymManager() private weak var dsymViewController: DsymViewController? private var downloaderCancellable: AnyCancellable? private var downloadTask: DsymDownloadTask? private weak var downloadStatusViewController: DownloadStatusViewController? // Crash var crashContentViewController: ContentViewController! { if let vc = contentViewController as? ContentViewController { return vc } return nil } var crashDocument: CrashDocument? { return self.document as? CrashDocument } override func windowDidLoad() { super.windowDidLoad() windowFrameAutosaveName = "MainWindow" deviceItem.isEnabled = MDDeviceMonitor.shared().deviceConnected dsymPopUpButton.dsymManager = dsymManager NotificationCenter.default.addObserver(self, selector: #selector(updateDeviceButton(_:)), name: NSNotification.Name.MDDeviceMonitor, object: nil) downloaderCancellable = DsymDownloader.shared.$tasks .receive(on: DispatchQueue.main) .map { [weak self] tasks -> DsymDownloadTask? in if let uuid = self?.crashDocument?.crashInfo?.uuid { return tasks[uuid] } return nil }.sink { [weak self] task in self?.bind(task: task) } } required init?(coder: NSCoder) { super.init(coder: coder) } deinit { NotificationCenter.default.removeObserver(self) } override var document: AnyObject? { didSet { crashCancellable.forEach { cancellable in cancellable.cancel() } guard let document = document as? CrashDocument else { crashContentViewController.document = nil return } crashContentViewController.document = document document.$crashInfo .receive(on: DispatchQueue.main) .sink { [weak self] crashInfo in if let crash = crashInfo { self?.dsymManager.update(crash) } } .store(in: &crashCancellable) document.$isSymbolicating .receive(on: DispatchQueue.main) .assign(to: \.isSymbolicating, on: self) .store(in: &crashCancellable) } } // MARK: Notifications @objc func updateDeviceButton(_: Notification) { deviceItem.isEnabled = MDDeviceMonitor.shared().deviceConnected } @objc func crashDidSymbolicated(_: Notification) { isSymbolicating = false } // MARK: IBActions @IBAction func symbolicate(_: AnyObject?) { let content = crashDocument?.textStorage.string ?? "" if content.strip().isEmpty { return } isSymbolicating = true let dsyms = dsymManager.dsymFiles.values.compactMap { $0.binaryPath } crashDocument?.symbolicate(withDsymPaths: dsyms) } @IBAction func showDsymInfo(_: Any) { guard dsymManager.crash != nil else { return } let storyboard = NSStoryboard(name: NSStoryboard.Name("Dsym"), bundle: nil) let vc = storyboard.instantiateController(withIdentifier: "DsymViewController") as! DsymViewController vc.dsymManager = dsymManager vc.bind(task: downloadTask) dsymViewController = vc contentViewController?.presentAsSheet(vc) } @IBAction func downloadDsym(_: AnyObject?) { startDownloading() } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let vc = segue.destinationController as? DownloadStatusViewController { vc.delegate = self downloadStatusViewController = vc } } } extension MainWindowController: NSToolbarItemValidation { func validateToolbarItem(_ item: NSToolbarItem) -> Bool { return item.isEnabled } } extension MainWindowController: DownloadStatusViewControllerDelegate { func bind(task: DsymDownloadTask?) { downloadTask = task downloadStatusViewController?.bind(task: task) downloadItem.bind(task: task) dsymViewController?.bind(task: task) if let files = task?.dsymFiles { dsymManager.dsymFileDidUpdate(files) } } func startDownloading() { if let crash = dsymManager.crash { DsymDownloader.shared.download(crashInfo: crash, fileURL: nil) } } func cancelDownload() { downloadTask?.cancel() } func currentDownloadTask() -> DsymDownloadTask? { return downloadTask } }
mit
nguyenantinhbk77/practice-swift
Multitasking/Performing Task after a delay/Performing Task after a delay/AppDelegate.swift
3
246
// // AppDelegate.swift // Performing Task after a delay // // Created by Domenico Solazzo on 12/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
mit
RaviDesai/RSDRestServices
Pod/Classes/ResponseParsers/APIDataResponseParser.swift
2
1285
// // NSDataResponseParser.swift // CEVFoundation // // Created by Ravi Desai on 6/10/15. // Copyright (c) 2015 CEV. All rights reserved. // import Foundation public class APIDataResponseParser : APIResponseParserProtocol { public typealias T = NSData public init() { self.acceptTypes = nil } public init(acceptTypes: [String]) { self.acceptTypes = acceptTypes } public private(set) var acceptTypes: [String]? public class func convertToSerializable(response: NetworkResponse) -> (NSData?, NSError?) { let data: NSData? = response.getData() let error: NSError? = response.getError() return (data, error) } public class func convertToSerializableArray(response: NetworkResponse) -> ([NSData]?, NSError?) { let data: NSData? = response.getData() let error: NSError? = response.getError() return (data != nil ? [data!] : nil, error) } public func Parse(response: NetworkResponse) -> (NSData?, NSError?) { return APIDataResponseParser.convertToSerializable(response) } public func ParseToArray(response: NetworkResponse) -> ([NSData]?, NSError?) { return APIDataResponseParser.convertToSerializableArray(response) } }
mit
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Controllers/TableViewControllers/TableViewCells/BugDetails.swift
1
1275
// // BugDetailCells.swift // bugTrap // // Created by Colby L Williams on 8/23/14. // Copyright (c) 2014 bugTrap. All rights reserved. // import Foundation import CoreGraphics struct BugDetails { enum DetailType { case Images case Selection (String, String) case TextField (String, String) case TextView (String, String) case DateDisplay (String, String) case DatePicker (NSDate, String) func cellId() -> String { switch self { case .Images: return "BtEmbeddedImageCollectionViewTableViewCell" case .Selection: return "BtTitlePlaceholderTableViewCell" case .TextField: return "BtTextFieldTableViewCell" case .TextView: return "BtTextViewTableViewCell" case .DateDisplay: return "BtDateDisplayTableViewCell" case .DatePicker: return "BtDatePickerTableViewCell" } } func cellHeight() -> CGFloat { switch self { case .Images: return 142.0 case .Selection: return 44.0 case .TextField: return 44.0 case .TextView: return 100.0 case .DateDisplay: return 44.0 case .DatePicker: return 163.0 } } func isDate() -> Bool { switch self { case .Images, .Selection, .TextField, .TextView: return false case .DateDisplay, .DatePicker: return true } } } }
mit
skutnii/4swivl
TestApp/TestApp/PersonCell.swift
1
2381
// // PersonCell.swift // TestApp // // Created by Serge Kutny on 9/17/15. // Copyright © 2015 skutnii. All rights reserved. // import UIKit protocol AvatarViewer : class { func viewAvatar(forPerson person:Person?) -> () } class PersonCell : UITableViewCell { @IBOutlet var avatarView : UIImageView? = nil @IBOutlet var nameLabel : UILabel? = nil @IBOutlet var profileLabel : UILabel? = nil @IBOutlet var infoView : UITextView? = nil @IBOutlet var avatarOverlay : UIView? = nil { didSet { if nil != avatarOverlay { avatarOverlay!.addGestureRecognizer(UITapGestureRecognizer(target:self, action:(NSSelectorFromString("viewAvatar")))) } } } weak var avatarViewDelegate : AvatarViewer? = nil @IBAction func viewAvatar() { avatarViewDelegate?.viewAvatar(forPerson: self.person) } private var _onAvatarChange : Callback<UIImage, Person>? = nil var person : Person? = nil { willSet { person?.avatar.preview.removeObserver(_onAvatarChange) } didSet { _onAvatarChange = person?.avatar.preview.addObserver({ [weak self] (from: UIImage?, to: UIImage?, person: AnyObject) in guard person === self?.person else { return } self?.layoutSubviews() }) } } override func layoutSubviews() { super.layoutSubviews() let name = NSMutableAttributedString(string: person?.login ?? "") let link = NSMutableAttributedString(string:person?.profileLink ?? "") name.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(20.0), NSForegroundColorAttributeName: UIColor.whiteColor()], range: NSMakeRange(0, name.length)) link.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(16.0)], range: NSMakeRange(0, link.length)) let text = NSMutableAttributedString(string:"") text.appendAttributedString(name) text.appendAttributedString(NSAttributedString(string:"\n\n")) text.appendAttributedString(link) avatarView?.image = self.person?.avatar.preview[] self.infoView?.attributedText = text } }
mit
jad6/JadKit
JadKit/Protocols/DynamicList.swift
1
13920
// // DynamicList.swift // JadKit // // Created by Jad Osseiran on 7/13/15. // Copyright © 2016 Jad Osseiran. All rights reserved. // // -------------------------------------------- // // Implements the protocol and their extensions to get a Core Data backed fetched list going. // // -------------------------------------------- // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import CoreData /** The basic beahviour that a fetched list needs to implement. The core of a fetched list is a `NSFetchedResultsController` object that the conforming object will need to create in order to properly calculate the list data. */ public protocol DynamicList: List, NSFetchedResultsControllerDelegate { /// A fetched object needs to conform to `NSFetchRequestResult`, restrict it to a `Object` in the /// protocol extensions. associatedtype FetchedObject: NSFetchRequestResult /// The fetched results controller that will be used to populate the list /// dynamically as the backing store is updated. var fetchedResultsController: NSFetchedResultsController<FetchedObject>! { get set } } /** Protocol extension to implement the basic fetched list methods. */ public extension DynamicList where Object == FetchedObject { /// The number of sections fetched by the `fetchedResultsController`. var sectionCount: Int { return fetchedResultsController?.sections?.count ?? 0 } /// The index titles for the fetched list. var sectionIndexTitles: [String]? { return fetchedResultsController?.sectionIndexTitles } /** The number of rows in a section fetched by the `fetchedResultsController`. - parameter section: The section in which the row count will be returned. - returns: The number of rows in a given section. `0` if the section is not found. */ func itemCount(at section: Int) -> Int { if let sections = fetchedResultsController?.sections { return sections[section].numberOfObjects } return 0 } /** Conveneient helper method to ensure that a given index path is valid. - note: This method is implemented by a protocol extension if the object conforms to either `DynamicList` or `StaticList` - parameter indexPath: The index path to check for existance. - returns: `true` iff the index path is valid for your data source. */ func isValid(indexPath: IndexPath) -> Bool { guard indexPath.section < sectionCount && indexPath.section >= 0 else { return false } return indexPath.row < itemCount(at: indexPath.section) && indexPath.row >= 0 } /** Convenient helper method to find the object at a given index path. This method works well with `isValidIndexPath:`. - note: This method is implemented by a protocol extension if the object conforms to either `DynamicList` or `StaticList` - parameter indexPath: The index path to retreive the object for. - returns: An optional with the corresponding object at an index path or nil if the index path is invalid. */ func object(at indexPath: IndexPath) -> Object? { guard isValid(indexPath: indexPath) else { return nil } return fetchedResultsController?.object(at: indexPath) } /** Helper method to grab the title for a header for a given section. - parameter section: The section for the header's title to grab. - returns: The header title for the section or `nil` if none is found. */ func titleForHeader(at section: Int) -> String? { guard isValid(indexPath: IndexPath(row: 0, section: section)) else { return nil } return fetchedResultsController?.sections?[section].name } } // MARK: Table /** Protocol to set up the conformance to the various protocols to allow for a valid table view protocol extension implementation. */ public protocol DynamicTableList: DynamicList, UITableViewDataSource, UITableViewDelegate { /// The table view that will be updated as the `fetchedResultsController` /// is updated. var tableView: UITableView! { get set } } /** Protocol extension to implement the table view delegate & data source methods. */ public extension DynamicTableList where ListView == UITableView, Cell == UITableViewCell, Object == FetchedObject { /** Method to call in `tableView:cellForRowAtIndexPath:`. - parameter indexPath: An index path locating a row in `tableView` */ func cell(at indexPath: IndexPath) -> UITableViewCell { let identifier = cellIdentifier(at: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) if let object = object(at: indexPath) { listView(tableView, configureCell: cell, withObject: object, atIndexPath: indexPath) } return cell } /** Method to call in `tableView:didSelectRowAtIndexPath:`. - parameter indexPath: An index path locating the new selected row in `tableView`. */ func didSelectItem(at indexPath: IndexPath) { if let object = object(at: indexPath) { listView(tableView, didSelectObject: object, atIndexPath: indexPath) } } } /** Protocol extension to implement the fetched results controller sdelegate methods. */ public extension DynamicTableList where ListView == UITableView, Cell == UITableViewCell, Object == FetchedObject { /** Method to call in `controllerWillChangeContent:`. */ func willChangeContent() { tableView.beginUpdates() } /** Method to call in `controller:didChangeSection:atIndex:forChangeType:`. - parameter sectionIndex: The index of the changed section. - parameter type: The type of change (insert or delete). Valid values are `NSFetchedResultsChangeInsert` and `NSFetchedResultsChangeDelete`. */ func didChangeSection(_ sectionIndex: Int, withChangeType type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .automatic) case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic) case .update: tableView.reloadSections(IndexSet(integer: sectionIndex), with: .automatic) default: // FIXME: Figure out what to do with .Move break } } /** Method to call in `controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:`. - parameter indexPath: The index path of the changed object (this value is `nil` for insertions). - parameter type: The type of change. For valid values see `NSFetchedResultsChangeType` - parameter newIndexPath: The destination path for the object for insertions or moves (this value is `nil` for a deletion). */ func didChangeObject(at indexPath: IndexPath?, withChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .automatic) case .delete: tableView.deleteRows(at: [indexPath!], with: .automatic) case .update: tableView.reloadRows(at: [indexPath!], with: .automatic) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } /** Method to call in `controllerDidChangeContent:` */ func didChangeContent() { tableView.endUpdates() } } // MARK: Collection /** Protocol to set up the conformance to the various protocols to allow for a valid collection view protocol extension implementation. */ public protocol DynamicCollectionList: DynamicList, UICollectionViewDataSource, UICollectionViewDelegate { /// The collection view to update with the fetched changes. var collectionView: UICollectionView? { get set } /// Classes that conform to this protocol need only to initialise this /// property. It is an array of block operations used to hold the section /// and row changes so that the collection view can be animated in the same /// way a table view controller handles section changes. var changeOperations: [BlockOperation] { get set } } /** Protocol extension to implement the custom source methods. */ public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell, Object == FetchedObject { /** Cancel the queued up collection view row & section changes. */ func cancelChangeOperations() { for operation: BlockOperation in changeOperations { operation.cancel() } changeOperations.removeAll(keepingCapacity: false) } } /** Protocol extension to implement the collection view delegate & data source methods. */ public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell, Object == FetchedObject { /** Method to call in `collectionView:cellForItemAtIndexPath:`. - parameter indexPath: The index path that specifies the location of the item. */ func cell(at indexPath: IndexPath) -> UICollectionViewCell { let identifier = cellIdentifier(at: indexPath) let cell = collectionView!.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) if let object = object(at: indexPath) { listView(collectionView!, configureCell: cell, withObject: object, atIndexPath: indexPath) } return cell } /** Method to call in `collectionView:didSelectItemAtIndexPath:`. - parameter indexPath: The index path of the cell that was selected. */ func didSelectItem(at indexPath: IndexPath) { if let object = object(at: indexPath) { listView(collectionView!, didSelectObject: object, atIndexPath: indexPath) } } } /** Protocol extension to implement the fetched results controller sdelegate methods. */ public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell, Object == FetchedObject { /** Method to call in `controllerWillChangeContent:`. */ func willChangeContent() { self.changeOperations.removeAll(keepingCapacity: false) } /** Method to call in `controller:didChangeSection:atIndex:forChangeType:`. - parameter sectionIndex: The index of the changed section. - parameter type: The type of change (insert or delete). Valid values are `NSFetchedResultsChangeInsert` and `NSFetchedResultsChangeDelete`. */ func didChangeSection(_ sectionIndex: Int, withChangeType type: NSFetchedResultsChangeType) { let indexSet = IndexSet(integer: sectionIndex) switch type { case .insert: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.insertSections(indexSet) }) case .update: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.reloadSections(indexSet) }) case .delete: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.deleteSections(indexSet) }) default: break } } /** Method to call in `controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:`. - parameter indexPath: The index path of the changed object (this value is `nil` for insertions). - parameter type: The type of change. For valid values see `NSFetchedResultsChangeType` - parameter newIndexPath: The destination path for the object for insertions or moves (this value is `nil` for a deletion). */ func didChangeObject(at indexPath: IndexPath?, withChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.insertItems(at: [newIndexPath!]) }) case .update: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.reloadItems(at: [indexPath!]) }) case .move: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.moveItem(at: indexPath!, to: newIndexPath!) }) case .delete: changeOperations.append( BlockOperation { [weak self] in self?.collectionView!.deleteItems(at: [indexPath!]) }) } } /** Method to call in `controllerDidChangeContent:` */ func didChangeContent() { for section in fetchedResultsController.sections! { print(section.numberOfObjects) } collectionView!.performBatchUpdates({ for operation in self.changeOperations { operation.start() } }, completion: { [weak self] finished in self?.changeOperations.removeAll(keepingCapacity: false) }) } }
bsd-2-clause
Mattmlm/codepathtwitter
Codepath Twitter/Codepath Twitter/ComposeTweetViewController.swift
1
2200
// // ComposeTweetViewController.swift // Codepath Twitter // // Created by admin on 10/4/15. // Copyright © 2015 mattmo. All rights reserved. // import UIKit class ComposeTweetViewController: UIViewController { @IBOutlet weak var tweetField: UITextField! var replyToTweet: Tweet? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#55ACEE"); self.navigationController?.navigationBar.translucent = false; self.navigationController?.navigationBar.tintColor = UIColor.whiteColor(); if replyToTweet != nil { self.tweetField.text = "@\((replyToTweet!.user?.screenname)!) " } self.tweetField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onCancelButtonPressed(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil); } @IBAction func onTweetButtonPressed(sender: AnyObject) { let dict = NSMutableDictionary() dict["status"] = tweetField.text! if replyToTweet != nil { dict["in_reply_to_status_id"] = replyToTweet!.idString! } TwitterClient.sharedInstance.composeTweetWithCompletion(dict) { (tweet, error) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.dismissViewControllerAnimated(true, completion: nil); }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
eoger/firefox-ios
ClientTests/FxADeepLinkingTests.swift
2
1728
/* 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 UIKit import XCTest @testable import Client import Shared class FxADeepLinkingTests: XCTestCase { var profile: MockProfile! var vc: FxAContentViewController! var expectUrl = URL(string: "https://accounts.firefox.com/signin?service=sync&context=fx_ios_v1&signin=test&utm_source=somesource&entrypoint=one") override func setUp() { super.setUp() self.profile = MockProfile() self.vc = FxAContentViewController(profile: self.profile) } func testLaunchWithNilOptions() { let testUrl = self.vc.createFxAURLWith(nil, profile: self.profile) // Should use default urls for nil options XCTAssertEqual(testUrl, self.vc.profile.accountConfiguration.signInURL) } func testLaunchWithOptions() { let url = URL(string: "firefox://fxa-signin?signin=test&utm_source=somesource&entrypoint=one&ignore=this") let query = url!.getQuery() let fxaOptions = FxALaunchParams(query: query) let testUrl = self.vc.createFxAURLWith(fxaOptions, profile: self.profile) XCTAssertEqual(testUrl, expectUrl!) } func testDoesntOverrideServiceContext() { let url = URL(string: "firefox://fxa-signin?service=asdf&context=123&signin=test&entrypoint=one&utm_source=somesource&ignore=this") let query = url!.getQuery() let fxaOptions = FxALaunchParams(query: query) let testUrl = self.vc.createFxAURLWith(fxaOptions, profile: self.profile) XCTAssertEqual(testUrl, expectUrl!) } }
mpl-2.0
benlangmuir/swift
test/Constraints/incomplete_function_ref.swift
29
647
// RUN: %target-typecheck-verify-swift struct MyCollection<Element> { // expected-note {{'Element' declared as parameter to type 'MyCollection'}} func map<T>(_ transform: (Element) -> T) -> MyCollection<T> { // expected-note 2 {{in call to function 'map'}} fatalError("implement") } } MyCollection.map // expected-error{{generic parameter 'Element' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{13-13=<Any>}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} let a = MyCollection<Int>() a.map // expected-error{{generic parameter 'T' could not be inferred}}
apache-2.0
TalkingBibles/TBMultiAppearanceButton
TBMultiAppearanceButton/TBSystemDefaults.swift
1
1954
// // The MIT License (MIT) // // TBMultiAppearanceButton // Copyright (c) 2015 Talking Bibles International and Stephen Clay Smith // // 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 /// TBSystemDefaults has static functions that return default values from UIKit. struct TBSystemDefaults { static func titleColorForState(state: UIControlState) -> UIColor? { let tempView = UIButton() return tempView.titleColorForState(state) } static func titleShadowColorForState(state: UIControlState) -> UIColor? { let tempView = UIButton() return tempView.titleShadowColorForState(state) } static func backgroundImageForState(state: UIControlState) -> UIImage? { let tempView = UIButton() return tempView.backgroundImageForState(state) } static func imageForState(state: UIControlState) -> UIImage? { let tempView = UIButton() return tempView.imageForState(state) } }
mit
larrynatalicio/15DaysofAnimationsinSwift
Animation 08 - GradientAnimation/GradientAnimation/LoadingLabel.swift
1
2860
// // LoadingLabel.swift // GradientAnimation // // Created by Larry Natalicio on 4/23/16. // Copyright © 2016 Larry Natalicio. All rights reserved. // import UIKit @IBDesignable class LoadingLabel: UIView { // MARK: - Types struct Constants { struct Fonts { static let loadingLabel = "HelveticaNeue-UltraLight" } } // MARK: - Properties let gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() // Configure gradient. gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) let colors = [UIColor.gray.cgColor, UIColor.white.cgColor, UIColor.gray.cgColor] gradientLayer.colors = colors let locations = [0.25, 0.5, 0.75] gradientLayer.locations = locations as [NSNumber]? return gradientLayer }() let textAttributes: [String: AnyObject] = { let style = NSMutableParagraphStyle() style.alignment = .center return [NSFontAttributeName: UIFont(name: Constants.Fonts.loadingLabel, size: 70.0)!, NSParagraphStyleAttributeName: style] }() @IBInspectable var text: String! { didSet { setNeedsDisplay() // Create a temporary graphic context in order to render the text as an image. UIGraphicsBeginImageContextWithOptions(frame.size, false, 0) text.draw(in: bounds, withAttributes: textAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Use image to create a mask on the gradient layer. let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.clear.cgColor maskLayer.frame = bounds.offsetBy(dx: bounds.size.width, dy: 0) maskLayer.contents = image?.cgImage gradientLayer.mask = maskLayer } } // MARK: - View Life Cycle override func layoutSubviews() { gradientLayer.frame = CGRect(x: -bounds.size.width, y: bounds.origin.y, width: 2 * bounds.size.width, height: bounds.size.height) } override func didMoveToWindow() { super.didMoveToWindow() layer.addSublayer(gradientLayer) let gradientAnimation = CABasicAnimation(keyPath: "locations") gradientAnimation.fromValue = [0.0, 0.0, 0.25] gradientAnimation.toValue = [0.75, 1.0, 1.0] gradientAnimation.duration = 1.7 gradientAnimation.repeatCount = Float.infinity gradientAnimation.isRemovedOnCompletion = false gradientAnimation.fillMode = kCAFillModeForwards gradientLayer.add(gradientAnimation, forKey: nil) } }
mit
nofelmahmood/Seam
Tests/CoreData/Models/Task+CoreDataProperties.swift
3
434
// // Task+CoreDataProperties.swift // Seam // // Created by Nofel Mahmood on 05/11/2015. // Copyright © 2015 CloudKitSpace. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Task { @NSManaged var name: String? @NSManaged var tags: NSSet? }
mit
tzef/BmoViewPager
Example/BmoViewPager/SingleViewControllers/NumberViewController.swift
1
778
// // NumberViewController.swift // BmoViewPager // // Created by LEE ZHE YU on 2017/6/4. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit class NumberViewController: UIViewController { @IBOutlet var numberLabel: UILabel! var numberText: String? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init(number: Int) { self.init(nibName: "NumberViewController", bundle: nil) numberText = "\(number)" } override func viewDidLoad() { super.viewDidLoad() numberLabel.text = numberText } }
mit
esttorhe/MammutAPI
Sources/MammutAPI/Mappers/MentionMapper.swift
1
877
// // Created by Esteban Torres on 21.04.17. // Copyright (c) 2017 Esteban Torres. All rights reserved. // import Foundation internal class MentionMapper: ModelMapping { typealias Model = Mention func map(json: ModelMapping.JSONDictionary) -> Result<Model, MammutAPIError.MappingError> { guard let id = json["id"] as? Int, let urlString = json["url"] as? String, let url = URL(string: urlString), let username = json["username"] as? String, let acct = json["acct"] as? String else { return .failure(MammutAPIError.MappingError.incompleteModel) } let mention = Mention( id: id, url: url, username: username, acct: acct ) return .success(mention) } }
mit
slavapestov/swift
test/SILGen/switch.swift
1
38061
// RUN: %target-swift-frontend -enable-experimental-patterns -emit-silgen %s | FileCheck %s func markUsed<T>(t: T) {} // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int, Int), y: (Int, Int)) -> Bool { return x.0 == y.0 && x.1 == y.1 } // Some fake predicates for pattern guards. func runced() -> Bool { return true } func funged() -> Bool { return true } func ansed() -> Bool { return true } func foo() -> Int { return 0 } func bar() -> Int { return 0 } func foobar() -> (Int, Int) { return (0, 0) } func a() {} func b() {} func c() {} func d() {} func e() {} func f() {} func g() {} // CHECK-LABEL: sil hidden @_TF6switch5test1FT_T_ func test1() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1bFT_T_ b() } // CHECK-LABEL: sil hidden @_TF6switch5test2FT_T_ func test2() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() case _: // The second case is unreachable. b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test3FT_T_ func test3() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case _ where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NO_CASE2]]: // CHECK: br [[CASE2:bb[0-9]+]] case _: // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test4FT_T_ func test4() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1bFT_T_ b() } // CHECK-LABEL: sil hidden @_TF6switch5test5FT_T_ func test5() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case _ where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] // CHECK: [[YES_CASE2]]: case (_, _) where funged(): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: br [[CASE3:bb[0-9]+]] case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch5test6FT_T_ func test6() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si case (_, _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() case (_, _): // The second case is unreachable. b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test7FT_T_ func test7() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (_, _) where runced(): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: br [[CASE2:bb[0-9]+]] case (_, _): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } c() // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ } // CHECK-LABEL: sil hidden @_TF6switch5test8FT_T_ func test8() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6foobarFT_TSiSi_ // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case foobar(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case (foo(), _): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE3_GUARD:bb[0-9]+]], [[NOT_CASE3:bb[0-9]+]] // CHECK: [[CASE3_GUARD]]: // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NOT_CASE3_GUARD:bb[0-9]+]] case (_, bar()) where runced(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[NOT_CASE3_GUARD]]: // CHECK: [[NOT_CASE3]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE4_GUARD_1:bb[0-9]+]], [[NOT_CASE4_1:bb[0-9]+]] // CHECK: [[CASE4_GUARD_1]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE4_GUARD_2:bb[0-9]+]], [[NOT_CASE4_2:bb[0-9]+]] // CHECK: [[CASE4_GUARD_2]]: // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4_3:bb[0-9]+]] case (foo(), bar()) where funged(): // CHECK: [[CASE4]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[NOT_CASE4_3]]: // CHECK: [[NOT_CASE4_2]]: // CHECK: [[NOT_CASE4_1]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE5_GUARD_1:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]] // CHECK: [[CASE5_GUARD_1]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE5:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]] // CHECK: [[YES_CASE5]]: case (foo(), bar()): // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() // CHECK: [[NOT_CASE5]]: // CHECK: br [[CASE6:bb[0-9]+]] case _: // CHECK: [[CASE6]]: // CHECK: function_ref @_TF6switch1fFT_T_ // CHECK: br [[CONT]] f() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1gFT_T_ g() } // CHECK-LABEL: sil hidden @_TF6switch5test9FT_T_ func test9() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (foo(), _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch6foobarFT_TSiSi_ // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case foobar(): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: br [[CASE3:bb[0-9]+]] case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch6test10FT_T_ func test10() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (foo()...bar(), _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: br [[CASE2:bb[0-9]+]] case _: // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } protocol P { func p() } struct X : P { func p() {} } struct Y : P { func p() {} } struct Z : P { func p() {} } // CHECK-LABEL: sil hidden @_TF6switch10test_isa_1FT1pPS_1P__T_ func test_isa_1(p p: P) { // CHECK: [[PTMPBUF:%[0-9]+]] = alloc_stack $P // CHECK-NEXT: copy_addr %0 to [initialization] [[PTMPBUF]] : $*P switch p { // CHECK: [[TMPBUF:%[0-9]+]] = alloc_stack $X // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in [[TMPBUF]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] case is X: // CHECK: [[IS_X]]: // CHECK-NEXT: load [[TMPBUF]] // CHECK-NEXT: dealloc_stack [[TMPBUF]] // CHECK-NEXT: destroy_addr [[PTMPBUF]] // CHECK-NEXT: dealloc_stack [[PTMPBUF]] a() // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: case is Y: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[Y_CONT:bb[0-9]+]] b() // CHECK: [[IS_NOT_Y]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Z in {{%.*}} : $*Z, [[IS_Z:bb[0-9]+]], [[IS_NOT_Z:bb[0-9]+]] // CHECK: [[IS_Z]]: case is Z: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[Z_CONT:bb[0-9]+]] c() // CHECK: [[IS_NOT_Z]]: case _: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch10test_isa_2FT1pPS_1P__T_ func test_isa_2(p p: P) { switch (p, foo()) { // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] // CHECK: [[IS_X]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case (is X, foo()): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case (is Y, foo()): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: [[IS_NOT_Y]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[CASE3:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] case (is X, _): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // -- case (is Y, foo()): // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4:bb[0-9]+]] case (is Y, bar()): // CHECK: [[CASE4]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[NOT_CASE4]]: // CHECK: br [[CASE5:bb[0-9]+]] // CHECK: [[IS_NOT_Y]]: // CHECK: br [[CASE5]] case _: // CHECK: [[CASE5]]: // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1fFT_T_ f() } class B {} class C : B {} class D1 : C {} class D2 : D1 {} class E : C {} // CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_1FT1xCS_1B_T_ func test_isa_class_1(let x x: B) { // CHECK: strong_retain %0 switch x { // CHECK: checked_cast_br [[X:%.*]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]] // CHECK: [[IS_D1]]([[CAST_D1:%.*]]): // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case is D1 where runced(): // CHECK: strong_release [[CAST_D1]] // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NO_CASE1]]: // CHECK: [[IS_NOT_D1]]: // CHECK: checked_cast_br [[X]] : $B to $D2, [[IS_D2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]] // CHECK: [[IS_D2]]([[CAST_D2:%.*]]): case is D2: // CHECK: strong_release %0 // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_D2]]: // CHECK: checked_cast_br [[X]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]] // CHECK: [[IS_E]]([[CAST_E:%.*]]): // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case is E where funged(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[NO_CASE3]]: // CHECK: [[IS_NOT_E]]: // CHECK: checked_cast_br [[X]] : $B to $C, [[IS_C:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]] // CHECK: [[IS_C]]([[CAST_C:%.*]]): case is C: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[IS_NOT_C]]: default: // CHECK: strong_release [[X]] // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() } // CHECK: [[CONT]]: // CHECK: strong_release %0 f() } // CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_2FT1xCS_1B_Ps9AnyObject_ func test_isa_class_2(x x: B) -> AnyObject { // CHECK: strong_retain [[X:%0]] switch x { // CHECK: checked_cast_br [[X]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]] // CHECK: [[IS_D1]]([[CAST_D1:%.*]]): // CHECK: strong_retain [[CAST_D1]] // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] case let y as D1 where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D1]] // CHECK: strong_release [[X]] : $B // CHECK: br [[CONT:bb[0-9]+]]([[RET]] : $AnyObject) a() return y // CHECK: [[NO_CASE1]]: // CHECK: strong_release [[CAST_D1]] // CHECK: [[IS_NOT_D1]]: // CHECK: checked_cast_br [[X]] : $B to $D2, [[CASE2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]] case let y as D2: // CHECK: [[CASE2]]([[CAST_D2:%.*]]): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D2]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) b() return y // CHECK: [[IS_NOT_D2]]: // CHECK: checked_cast_br [[X]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]] // CHECK: [[IS_E]]([[CAST_E:%.*]]): // CHECK: strong_retain [[CAST_E]] // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case let y as E where funged(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_E]] // CHECK: strong_release [[X]] : $B // CHECK: br [[CONT]]([[RET]] : $AnyObject) c() return y // CHECK: [[NO_CASE3]]: // CHECK strong_release [[CAST_E]] // CHECK: [[IS_NOT_E]]: // CHECK: checked_cast_br [[X]] : $B to $C, [[CASE4:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]] case let y as C: // CHECK: [[CASE4]]([[CAST_C:%.*]]): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_C]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) d() return y // CHECK: [[IS_NOT_C]]: default: // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[X]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) e() return x } // CHECK: [[CONT]]([[T0:%.*]] : $AnyObject): // CHECK: strong_release [[X]] // CHECK: return [[T0]] } enum MaybePair { case Neither case Left(Int) case Right(String) case Both(Int, String) } // CHECK-LABEL: sil hidden @_TF6switch12test_union_1FT1uOS_9MaybePair_T_ func test_union_1(u u: MaybePair) { switch u { // CHECK: switch_enum [[SUBJECT:%.*]] : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: // CHECK-NOT: release case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): // CHECK-NOT: release case (.Left): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String): case var .Right: // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]([[TUP:%.*]] : $(Int, String)): case .Both: // CHECK: release_value [[TUP]] : $(Int, String) // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK-NOT: switch_enum [[SUBJECT]] // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_2FT1uOS_9MaybePair_T_ func test_union_2(u u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: default [[DEFAULT:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // -- missing .Both case // CHECK: [[DEFAULT]]: // CHECK: unreachable } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_3FT1uOS_9MaybePair_T_ func test_union_3(u u: MaybePair) { // CHECK: retain_value [[SUBJECT:%0]] switch u { // CHECK: switch_enum [[SUBJECT]] : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: default [[DEFAULT:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String): case .Right: // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[DEFAULT]]: // -- Ensure the fully-opaque value is destroyed in the default case. // CHECK: release_value [[SUBJECT]] : // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] default: d() } // CHECK: [[CONT]]: // CHECK-NOT: switch_enum [[SUBJECT]] // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: release_value [[SUBJECT]] e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_4FT1uOS_9MaybePair_T_ func test_union_4(u u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither(_): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left(_): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right(_): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]({{%.*}}): case .Both(_): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_5FT1uOS_9MaybePair_T_ func test_union_5(u u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither(): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left(_): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right(_): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]({{%.*}}): case .Both(_, _): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } enum MaybeAddressOnlyPair { case Neither case Left(P) case Right(String) case Both(P, String) } // CHECK-LABEL: sil hidden @_TF6switch22test_union_addr_only_1FT1uOS_20MaybeAddressOnlyPair_T_ func test_union_addr_only_1(u u: MaybeAddressOnlyPair) { switch u { // CHECK: switch_enum_addr [[ENUM_ADDR:%.*]] : $*MaybeAddressOnlyPair, // CHECK: case #MaybeAddressOnlyPair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]: // CHECK: [[P:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Left!enumelt.1 case .Left(_): // CHECK: destroy_addr [[P]] // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]: // CHECK: [[STR_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Right!enumelt.1 // CHECK: [[STR:%.*]] = load [[STR_ADDR]] case .Right(_): // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]: // CHECK: [[P_STR_TUPLE:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Both!enumelt.1 case .Both(_): // CHECK: destroy_addr [[P_STR_TUPLE]] // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } enum Generic<T, U> { case Foo(T) case Bar(U) } // Check that switching over a generic instance generates verified SIL. func test_union_generic_instance(u u: Generic<Int, String>) { switch u { case .Foo(var x): a() case .Bar(var y): b() } c() } enum Foo { case A, B } // CHECK-LABEL: sil hidden @_TF6switch22test_switch_two_unionsFT1xOS_3Foo1yS0__T_ func test_switch_two_unions(x x: Foo, y: Foo) { // CHECK: [[T0:%.*]] = tuple (%0 : $Foo, %1 : $Foo) // CHECK: [[X:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 0 // CHECK: [[Y:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 1 // CHECK: switch_enum [[Y]] : $Foo, case #Foo.A!enumelt: [[IS_CASE1:bb[0-9]+]], default [[IS_NOT_CASE1:bb[0-9]+]] switch (x, y) { // CHECK: [[IS_CASE1]]: case (_, Foo.A): // CHECK: function_ref @_TF6switch1aFT_T_ a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: switch_enum [[X]] : $Foo, case #Foo.B!enumelt: [[IS_CASE2:bb[0-9]+]], default [[IS_NOT_CASE2:bb[0-9]+]] // CHECK: [[IS_CASE2]]: case (Foo.B, _ ): // CHECK: function_ref @_TF6switch1bFT_T_ b() // CHECK: [[IS_NOT_CASE2]]: // CHECK: switch_enum [[Y]] : $Foo, case #Foo.B!enumelt: [[IS_CASE3:bb[0-9]+]], default [[UNREACHABLE:bb[0-9]+]] // CHECK: [[IS_CASE3]]: case (_, Foo.B): // CHECK: function_ref @_TF6switch1cFT_T_ c() // CHECK: [[UNREACHABLE]]: // CHECK: unreachable } } struct StructPatternTest { var x: Int var y: String } // CHECK-LABEL: sil hidden @_TF6switch19test_struct_patternFT1sVS_17StructPatternTest_T_ func test_struct_pattern(s s: StructPatternTest) { switch s { // CHECK: [[X:%.*]] = struct_extract [[S:%.*]] : $StructPatternTest, #StructPatternTest.x // CHECK: [[Y:%.*]] = struct_extract [[S]] : $StructPatternTest, #StructPatternTest.y // CHECK: retain_value [[Y]] // CHECK: cond_br {{%.*}}, [[IS_CASE1:bb[0-9]+]], [[IS_NOT_CASE1:bb[0-9]+]] // CHECK: [[IS_CASE1]]: // CHECK: release_value [[Y]] // CHECK: release_value [[S]] case StructPatternTest(x: 0): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: cond_br {{%.*}}, [[IS_CASE2:bb[0-9]+]], [[IS_NOT_CASE2:bb[0-9]+]] // CHECK: [[IS_CASE2]]: // CHECK: release_value [[Y]] // CHECK: release_value [[S]] case StructPatternTest(y: ""): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_CASE2]]: // CHECK: release_value [[Y]] // CHECK: release_value [[S]] case (StructPatternTest(x: _)): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } struct StructPatternTestAO { var x: Int var y: P } func ~=(a: P, b: P) -> Bool { return true } // CHECK-LABEL: sil hidden @_TF6switch22test_struct_pattern_aoFT1sVS_19StructPatternTestAO1pPS_1P__T_ func test_struct_pattern_ao(s s: StructPatternTestAO, p: P) { // CHECK: [[S:%.*]] = alloc_stack $StructPatternTestAO // CHECK: copy_addr %0 to [initialization] [[S]] // CHECK: [[T0:%.*]] = struct_element_addr [[S]] : $*StructPatternTestAO, #StructPatternTestAO.x // CHECK: [[X:%.*]] = load [[T0]] // CHECK: [[T0:%.*]] = struct_element_addr [[S]] : $*StructPatternTestAO, #StructPatternTestAO.y // CHECK: [[Y:%.*]] = alloc_stack $P // CHECK: copy_addr [[T0]] to [initialization] [[Y]] switch s { // CHECK: cond_br {{%.*}}, [[IS_CASE1:bb[0-9]+]], [[IS_NOT_CASE1:bb[0-9]+]] // CHECK: [[IS_CASE1]]: // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[S]] // CHECK: dealloc_stack [[S]] case StructPatternTestAO(x: 0): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: [[TEMP:%.*]] = alloc_stack $P // CHECK: copy_addr [[Y]] to [initialization] [[TEMP]] // CHECK: cond_br {{%.*}}, [[IS_CASE2:bb[0-9]+]], [[IS_NOT_CASE2:bb[0-9]+]] // CHECK: [[IS_CASE2]]: case StructPatternTestAO(y: p): // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[S]] // CHECK: dealloc_stack [[S]] // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_CASE2]]: // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: br [[IS_CASE3:bb[0-9]+]] // CHECK: [[IS_CASE3]]: // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[S]] // CHECK: dealloc_stack [[S]] case StructPatternTestAO(x: _): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: destroy_addr %0 : $*StructPatternTestAO d() } class ClassPatternTest { var x: Int = 0 var y: String = "" } // CHECK-LABEL: sil hidden @_TF6switch18test_class_patternFT1kCS_16ClassPatternTest_T_ // CHECK: bb0([[C:%.*]] : $ClassPatternTest): func test_class_pattern(k k: ClassPatternTest) { switch k { // CHECK: [[XM:%.*]] = class_method [[C]] : $ClassPatternTest, #ClassPatternTest.x!getter.1 // CHECK: [[X:%.*]]= apply [[XM:%.*]]([[C]]) // CHECK: [[YM:%.*]] = class_method [[C]] : $ClassPatternTest, #ClassPatternTest.y!getter.1 // CHECK: [[Y:%.*]]= apply [[YM:%.*]]([[C]]) // CHECK: cond_br {{%.*}}, [[IS_CASE1:bb[0-9]+]], [[IS_NOT_CASE1:bb[0-9]+]] // CHECK: [[IS_CASE1]]: case ClassPatternTest(x: 0): // CHECK: release_value [[Y]] // CHECK: strong_release [[C]] // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: cond_br {{%.*}}, [[IS_CASE2:bb[0-9]+]], [[IS_NOT_CASE2:bb[0-9]+]] // CHECK: [[IS_CASE2]]: case ClassPatternTest(y: ""): // CHECK: release_value [[Y]] // CHECK: strong_release [[C]] // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_CASE2]]: case ClassPatternTest(x: _): // CHECK: release_value [[Y]] // CHECK: strong_release [[C]] // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } class SubclassTestA : ClassPatternTest {} class SubclassTestB : ClassPatternTest {} // CHECK-LABEL: sil hidden @{{.*}}test_class_pattern_with_isa_1 // CHECK: bb0([[C:%.*]] : $ClassPatternTest): func test_class_pattern_with_isa_1(k k: ClassPatternTest) { switch k { // CHECK: [[XM:%.*]] = class_method %0 : $ClassPatternTest, #ClassPatternTest.x!getter.1 // CHECK: [[X:%.*]] = apply [[XM:%.*]](%0) // CHECK: cond_br {{%.*}}, [[IS_CASE1:bb[0-9]+]], [[IS_NOT_CASE1:bb[0-9]+]] // CHECK: [[IS_CASE1]]: case ClassPatternTest(x: 0): // CHECK: strong_release [[C]] // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: checked_cast_br [[C]] : $ClassPatternTest to $SubclassTestA, [[IS_A:bb[0-9]+]], [[IS_NOT_A:bb[0-9]+]] // CHECK: [[IS_A]]([[A:%.*]] : $SubclassTestA): case is SubclassTestA: // CHECK: strong_release %0 // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_A]]: // CHECK: [[YM:%.*]] = class_method %0 : $ClassPatternTest, #ClassPatternTest.y!getter.1 // CHECK: [[Y:%.*]] = apply [[YM:%.*]](%0) // CHECK: cond_br {{%.*}}, [[IS_CASE3:bb[0-9]+]], [[IS_NOT_CASE3:bb[0-9]+]] // CHECK: [[IS_CASE3]]: case ClassPatternTest(y: ""): // CHECK: release_value [[Y]] // CHECK: strong_release %0 // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_NOT_CASE3]]: // CHECK: release_value [[Y]] // CHECK: checked_cast_br %0 : $ClassPatternTest to $SubclassTestB, [[IS_B:bb[0-9]+]], [[IS_NOT_B:bb[0-9]+]] // CHECK: [[IS_B]]([[B:%.*]] : $SubclassTestB): case is SubclassTestB: // CHECK: strong_release %0 // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[IS_NOT_B]]: // CHECK: strong_release %0 // CHECK: unreachable } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } func test_class_pattern_with_isa_2(k k: ClassPatternTest) { switch k { case is SubclassTestA: a() case ClassPatternTest(x: 0): b() case is SubclassTestB: c() case ClassPatternTest(y: ""): d() } e() } // <rdar://problem/14826416> func rdar14826416<T, U>(t t: T, u: U) { switch t { case is Int: markUsed("Int") case is U: markUsed("U") case _: markUsed("other") } } // CHECK-LABEL: sil hidden @_TF6switch12rdar14826416 // CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to Int in {{%.*}} : $*Int, [[IS_INT:bb[0-9]+]], [[ISNT_INT:bb[0-9]+]] // CHECK: [[ISNT_INT]]: // CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to U in {{%.*}} : $*U, [[ISNT_INT_IS_U:bb[0-9]+]], [[ISNT_INT_ISNT_U:bb[0-9]+]] // <rdar://problem/14835992> class Rdar14835992 {} class SubRdar14835992 : Rdar14835992 {} // CHECK-LABEL: sil hidden @_TF6switch12rdar14835992 func rdar14835992<T, U>(t t: Rdar14835992, tt: T, uu: U) { switch t { case is SubRdar14835992: markUsed("Sub") case is T: markUsed("T") case is U: markUsed("U") case _: markUsed("other") } } struct StructWithComputedProperty { var foo: Int { return 0 } } // rdar://15859432 // CHECK-LABEL: sil hidden @{{.*}}StructWithComputedProperty // CHECK: function_ref{{.*}}StructWithComputedProperty.foo.getter func testStructWithComputedProperty(s s : StructWithComputedProperty) { switch s { case StructWithComputedProperty(foo: let a): markUsed(a) } } // <rdar://problem/17272985> enum ABC { case A, B, C } // CHECK-LABEL: sil hidden @_TF6switch18testTupleWildcardsFTOS_3ABCS0__T_ // CHECK: [[X:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 0 // CHECK: [[Y:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 1 // CHECK: switch_enum [[X]] : $ABC, case #ABC.A!enumelt: [[X_A:bb[0-9]+]], default [[X_NOT_A:bb[0-9]+]] // CHECK: [[X_A]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: [[X_NOT_A]]: // CHECK: switch_enum [[Y]] : $ABC, case #ABC.A!enumelt: [[Y_A:bb[0-9]+]], case #ABC.B!enumelt: [[Y_B:bb[0-9]+]], case #ABC.C!enumelt: [[Y_C:bb[0-9]+]] // CHECK-NOT: default // CHECK: [[Y_A]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: [[Y_B]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: [[Y_C]]: // CHECK: switch_enum [[X]] : $ABC, case #ABC.C!enumelt: [[X_C:bb[0-9]+]], default [[X_NOT_C:bb[0-9]+]] // CHECK: [[X_C]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: [[X_NOT_C]]: // CHECK: function_ref @_TF6switch1eFT_T_ func testTupleWildcards(x: ABC, _ y: ABC) { switch (x, y) { case (.A, _): a() case (_, .A): b() case (_, .B): c() case (.C, .C): d() default: e() } } enum LabeledScalarPayload { case Payload(name: Int) } // CHECK-LABEL: sil hidden @_TF6switch24testLabeledScalarPayloadFOS_20LabeledScalarPayloadP_ func testLabeledScalarPayload(lsp: LabeledScalarPayload) -> Any { // CHECK: switch_enum {{%.*}}, case #LabeledScalarPayload.Payload!enumelt.1: bb1 switch lsp { // CHECK: bb1([[TUPLE:%.*]] : $(name: Int)): // CHECK: [[X:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[ANY_X_ADDR:%.*]] = init_existential_addr {{%.*}}, $Int // CHECK: store [[X]] to [[ANY_X_ADDR]] case let .Payload(x): return x } } // There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch19testOptionalPatternFGSqSi_T_ func testOptionalPattern(value : Int?) { // CHECK: switch_enum %0 : $Optional<Int>, case #Optional.Some!enumelt.1: bb1, case #Optional.None!enumelt: [[NILBB:bb[0-9]+]] switch value { case 1?: a() case 2?: b() case nil: d() default: e() } } // x? and .None should both be considered "similar" and thus handled in the same // switch on the enum kind. There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch19testOptionalEnumMixFGSqSi_Si func testOptionalEnumMix(a : Int?) -> Int { // CHECK: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.Some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.None!enumelt: [[NILBB:bb[0-9]+]] switch a { case let x?: return 0 // CHECK: [[SOMEBB]](%3 : $Int): // CHECK-NEXT: debug_value %3 : $Int, let, name "x" // CHECK: integer_literal $Builtin.Int2048, 0 case .None: return 42 // CHECK: [[NILBB]]: // CHECK: integer_literal $Builtin.Int2048, 42 } } // x? and nil should both be considered "similar" and thus handled in the same // switch on the enum kind. There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch26testOptionalEnumMixWithNilFGSqSi_Si func testOptionalEnumMixWithNil(a : Int?) -> Int { // CHECK: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.Some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.None!enumelt: [[NILBB:bb[0-9]+]] switch a { case let x?: return 0 // CHECK: [[SOMEBB]](%3 : $Int): // CHECK-NEXT: debug_value %3 : $Int, let, name "x" // CHECK: integer_literal $Builtin.Int2048, 0 case nil: return 42 // CHECK: [[NILBB]]: // CHECK: integer_literal $Builtin.Int2048, 42 } }
apache-2.0
SmallPlanetSwift/PlanetSwift
Sources/PlanetSwift/PlanetViewController.swift
1
5966
// // PlanetViewController.swift // PlanetSwift // // Created by Brad Bambara on 1/21/15. // Copyright (c) 2015 Small Planet. All rights reserved. // // swiftlint:disable line_length // swiftlint:disable cyclomatic_complexity import UIKit public typealias AnchorageAction = ((String, UIView, UIView, UIView?, UIView?, [String: Object]) -> Void) open class PlanetViewController: UIViewController { open var planetViews = [PlanetView]() var idMappings = [String: Object]() @IBInspectable open var titleBundlePath: String? open var mainBundlePath: String? open var navigationBarHidden = false open var persistentViews = false open var statusBarStyle: UIStatusBarStyle = .default open var titleXmlView: View? open var mainXmlView: View? private var anchorageAction: AnchorageAction? open var safeAreaInsets: UIEdgeInsets { if #available(iOS 11.0, *) { if let navController = self.navigationController { return navController.view.safeAreaInsets } if let window = UIApplication.shared.windows.first { return window.safeAreaInsets } } return UIEdgeInsets.zero } open func unloadViews() { view.removeFromSuperview() view = nil titleXmlView = nil mainXmlView = nil idMappings.removeAll() planetViews.removeAll() } open func loadPlanetViews(_ anchorage:@escaping AnchorageAction) { navigationItem.title = self.title if let titleBundlePath = titleBundlePath, let titleXmlView = PlanetUI.readFromFile(String(bundlePath: titleBundlePath)) as? View { navigationItem.titleView = titleXmlView.view titleXmlView.visit { $0.gaxbDidPrepare() } searchXMLObject(titleXmlView) self.titleXmlView = titleXmlView } if let mainBundlePath = mainBundlePath, let mainXmlView = PlanetUI.readFromFile(String(bundlePath: mainBundlePath)) as? View { view.addSubview(mainXmlView.view) mainXmlView.visit { $0.gaxbDidPrepare() } searchXMLObject(mainXmlView) self.mainXmlView = mainXmlView } if self.mainXmlView != nil || self.titleXmlView != nil { // Overriding loadView because we need a function where the view exists // but child view controllers have not been loaded yet searchForPlanetView(view) for planetView in planetViews { if let xmlObj = planetView.xmlView { searchXMLObject(xmlObj) xmlObj.visit(decorate) } } } self.anchorageAction = anchorage let mirror = Mirror(reflecting: self) var validKeys: [String: Bool] = [:] for case let (label?, _) in mirror.children { validKeys[label] = true } // we cannot just iterate over the idMappings because the ordering is // not garaunteed, therefor we walk over them in XML order if let mainXmlView = mainXmlView { mainXmlView.visit { if let mmm = ($0 as? View) { if let objectID = mmm.id { let view = mmm.view if let parent = view.superview { if let idx = parent.subviews.firstIndex(of: view) { let prev: UIView? = idx > 0 ? parent.subviews[idx-1] : nil let next: UIView? = idx < parent.subviews.count-1 ? parent.subviews[idx+1] : nil if validKeys[objectID] != nil { setValue(view, forKey: objectID) } anchorage(objectID, view, parent, prev, next, idMappings) } else { if validKeys[objectID] != nil { setValue(view, forKey: objectID) } anchorage(objectID, view, parent, nil, nil, idMappings) } } } } } } } func searchXMLObject(_ xmlObj: Object) { xmlObj.visit { [unowned self] (element: GaxbElement) -> Void in if let xmlController = element as? Controller { xmlController.controllerObject = self } if let xmlObject = element as? Object, let objectId = xmlObject.id { self.idMappings[objectId] = xmlObject } } } open func decorate(_ element: GaxbElement) { // Override decorate in your controller class if you need a // handle on the XML views from your PlanetView } func searchForPlanetView(_ searchedView: UIView) { if let foundView = searchedView as? PlanetView { planetViews.append(foundView) } for child in searchedView.subviews { searchForPlanetView(child as UIView) } } open func objectForId<T>(_ objID: String) -> T? { guard let foundObj = idMappings[objID] as? T else { return nil } return foundObj } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) navigationController?.setNavigationBarHidden(navigationBarHidden, animated: true) self.setNeedsStatusBarAppearanceUpdate() } open override var preferredStatusBarStyle: UIStatusBarStyle { return statusBarStyle } open override func viewDidDisappear(_ animated: Bool) { if persistentViews == false { // Unload all exisiting views unloadViews() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) } }
mit
hayleyqinn/windWeather
风生/Pods/Alamofire/Source/ServerTrustPolicy.swift
303
12898
// // ServerTrustPolicy.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. open class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. open let policies: [String: ServerTrustPolicy] /// Initializes the `ServerTrustPolicyManager` instance with the given policies. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key /// pinning for host3 and disabling evaluation for host4. /// /// - parameter policies: A dictionary of all policies mapped to a particular host. /// /// - returns: The new `ServerTrustPolicyManager` instance. public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /// Returns the `ServerTrustPolicy` for the given host if applicable. /// /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override /// this method and implement more complex mapping implementations such as wildcards. /// /// - parameter host: The host to use when searching for a matching policy. /// /// - returns: The server trust policy for the given host if found. open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension URLSession { private struct AssociatedKeys { static var managerKey = "URLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when /// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust /// with a given set of criteria to determine whether the server trust is valid and the connection should be made. /// /// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other /// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged /// to route all communication over an HTTPS connection with pinning enabled. /// /// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to /// validate the host provided by the challenge. Applications are encouraged to always /// validate the host in production environments to guarantee the validity of the server's /// certificate chain. /// /// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is /// considered valid if one of the pinned certificates match one of the server certificates. /// By validating both the certificate chain and host, certificate pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered /// valid if one of the pinned public keys match one of the server certificate public keys. /// By validating both the certificate chain and host, public key pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. /// /// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. public enum ServerTrustPolicy { case performDefaultEvaluation(validateHost: Bool) case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case disableEvaluation case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) // MARK: - Bundle Location /// Returns all certificates within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `.cer` files. /// /// - returns: All certificates within the given bundle. public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) }.joined()) for path in paths { if let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, let certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /// Returns all public keys within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `*.cer` files. /// /// - returns: All public keys within the given bundle. public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificates(in: bundle) { if let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /// Evaluates whether the server trust is valid for the given host. /// /// - parameter serverTrust: The server trust to evaluate. /// - parameter host: The host of the challenge protection space. /// /// - returns: Whether the server trust is valid. public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .performDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) serverTrustIsValid = trustIsValid(serverTrust) case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateData(for: serverTrust) let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData == pinnedCertificateData { serverTrustIsValid = true break outerLoop } } } } case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .disableEvaluation: serverTrustIsValid = true case let .customEvaluation(closure): serverTrustIsValid = closure(serverTrust, host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(_ trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType.unspecified let proceed = SecTrustResultType.proceed isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateData(for trust: SecTrust) -> [Data] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateData(for: certificates) } private func certificateData(for certificates: [SecCertificate]) -> [Data] { return certificates.map { SecCertificateCopyData($0) as Data } } // MARK: - Private - Public Key Extraction private static func publicKeys(for trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKey(for certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
mit
Ellusioists/TimingRemind
TimingRemind/Views/TableViewCell.swift
1
1512
// // TableViewCell.swift // TimingRemind // // Created by Channing Kuo on 2017/10/9. // Copyright © 2017年 Channing Kuo. All rights reserved. // import UIKit class TableViewCell: UITableViewCell { var labelName, labelValue: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = UITableViewCellSelectionStyle.none accessoryType = UITableViewCellAccessoryType.disclosureIndicator labelName = UILabel() labelName.textColor = .white labelName.textAlignment = .left labelName.backgroundColor = .clear contentView.addSubview(labelName) labelValue = UILabel() labelValue.textColor = .white labelValue.textAlignment = .right labelValue.backgroundColor = .clear labelValue.lineBreakMode = .byTruncatingTail contentView.addSubview(labelValue) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() labelName.frame = CGRect(x: 20, y: 0, width: 100, height: 50) labelValue.frame = CGRect(x: 120, y: 0, width: contentView.bounds.width - 120, height: 50) } public func updateUIString(name: String, value: String) { labelName.text = name labelValue.text = value } }
mit
xwu/swift
test/Compatibility/attr_override.swift
10
17289
// RUN: %target-typecheck-verify-swift -swift-version 4 @override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}} func virtualAttributeCanNotBeUsedInSource() {} class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}} // expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}} override @inline(never) func f1() {} } class DuplicateOverrideBase { func f1() {} class func cf1() {} class func cf2() {} class func cf3() {} class func cf4() {} } class DuplicateOverrideDerived : DuplicateOverrideBase { override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } class A { func f0() { } func f1() { } // expected-note{{overridden declaration is here}} var v1: Int { return 5 } var v2: Int { return 5 } // expected-note{{overridden declaration is here}} var v4: String { return "hello" }// expected-note{{attempt to override property here}} var v5: A { return self } var v6: A { return self } var v7: A { // expected-note{{attempt to override property here}} get { return self } set { } } var v8: Int = 0 // expected-note {{attempt to override property here}} var v9: Int { return 5 } // expected-note{{attempt to override property here}} var v10: Int { return 5 } // expected-note{{attempt to override property here}} subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return "hello" } set { } } subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return "hello" } set { } } subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return self } } subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return self } set { } } func overriddenInExtension() {} // expected-note {{overri}} } class B : A { override func f0() { } func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }} override func f2() { } // expected-error{{method does not override any method from its superclass}} override var v1: Int { return 5 } var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}} override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}} override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}} // Covariance override var v5: B { return self } override var v6: B { get { return self } set { } } override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}} get { return self } set { } } // Stored properties override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}} override var v9: Int // expected-error{{cannot override with a stored property 'v9'}} lazy override var v10: Int = 5 // expected-warning{{cannot override with a stored property 'v10'}} override subscript (i: Int) -> String { get { return "hello" } set { } } subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }} get { return "hello" } set { } } override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}} get { return "hello" } set { } } // Covariant override subscript (i: Int8) -> B { get { return self } } override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}} get { return self } set { } } override init() { } override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}} override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}} } extension B { override func overriddenInExtension() {} // expected-error{{overri}} } struct S { override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}} } extension S { override func ef() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}} } enum E { override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}} } protocol P { override func f() // expected-error{{method does not override any method from its parent protocol}} } override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}} // Invalid 'override' on declarations inside closures. var rdar16654075a = { override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}} } var rdar16654075b = { class A { override func foo() {} // expected-error{{method does not override any method from its superclass}} } } var rdar16654075c = { () -> () in override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}} () } var rdar16654075d = { () -> () in class A { override func foo() {} // expected-error {{method does not override any method from its superclass}} } A().foo() } var rdar16654075e = { () -> () in class A { func foo() {} } class B : A { override func foo() {} } A().foo() } class C { init(string: String) { } // expected-note{{overridden declaration is here}} required init(double: Double) { } // expected-note 3{{overridden required initializer is here}} convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}} } class D1 : C { override init(string: String) { super.init(string: string) } required init(double: Double) { } convenience init() { self.init(string: "hello") } } class D2 : C { init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }} // FIXME: Would like to remove the space after 'override' as well. required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}} override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}} } class D3 : C { override init(string: String) { super.init(string: string) } override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}} } class D4 : C { // "required override" only when we're overriding a non-required // designated initializer with a required initializer. required override init(string: String) { super.init(string: string) } required init(double: Double) { } } class D5 : C { // "required override" only when we're overriding a non-required // designated initializer with a required initializer. required convenience override init(string: String) { self.init(double: 5.0) } required init(double: Double) { } } class D6 : C { init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }} } // rdar://problem/18232867 class C_empty_tuple { init() { } } class D_empty_tuple : C_empty_tuple { override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}} } class C_with_let { let x = 42 // expected-note {{attempt to override property here}} } class D_with_let : C_with_let { override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}} } // <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available class C21311590 { override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}} } class B21311590 : C21311590 {} _ = C21311590() _ = B21311590() class MismatchOptionalBase { func param(_: Int?) {} func paramIUO(_: Int!) {} func result() -> Int { return 0 } func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 } func functionParam(x: ((Int) -> Int)?) {} func tupleParam(x: (Int, Int)?) {} func compositionParam(x: (P1 & P2)?) {} func nameAndTypeMismatch(label: Int?) {} func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}} func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}} var prop: Int = 0 // expected-note {{attempt to override property here}} var optProp: Int? // expected-note {{attempt to override property here}} var getProp: Int { return 0 } // expected-note {{attempt to override property here}} var getOptProp: Int? { return nil } init(param: Int?) {} init() {} // expected-note {{non-failable initializer 'init()' overridden here}} subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}} get { return () } set {} } subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}} get { return 0 } set {} } subscript(get a: Int?) -> Void { return () } subscript(get b: Void) -> Int { return 0 } subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}} return () } subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}} return () } } protocol P1 {} protocol P2 {} class MismatchOptional : MismatchOptionalBase { override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}} override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{32-32=?}} override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}} override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil } // expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}} // expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{47-47=?}} // expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{55-56=}} override func functionParam(x: @escaping (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{56-56=)?}} override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}} override func compositionParam(x: P1 & P2) {} // expected-error {{cannot override instance method parameter of type '(P1 & P2)?' with non-optional type 'P1 & P2'}} {{37-37=(}} {{44-44=)?}} override func nameAndTypeMismatch(_: Int) {} // expected-error@-1 {{argument labels for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }} // expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}} override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}} override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}} override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}} get { return nil } set {} } override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}} get { return 0 } set {} } override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}} override var getOptProp: Int { return 0 } // okay override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}} override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}} override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}} get { return () } set {} } override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}} get { return nil } set {} } override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}} return () } override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}} return nil } override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}} return () } override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}} return () } } class MismatchOptional2 : MismatchOptionalBase { override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}} // None of these are overrides because we didn't say 'override'. Since they're // not exact matches, they shouldn't result in errors. func param(_: Int) {} func ambiguousOverride(a: Int, b: Int) {} // This is covariant, so we still assume it's meant to override. func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} } class MismatchOptional3 : MismatchOptionalBase { override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}} } // Make sure we remap the method's innermost generic parameters // to the correct depth class GenericBase<T> { func doStuff<U>(t: T, u: U) {} init<U>(t: T, u: U) {} } class ConcreteSub : GenericBase<Int> { override func doStuff<U>(t: Int, u: U) {} override init<U>(t: Int, u: U) {} } class ConcreteBase { init<U>(t: Int, u: U) {} func doStuff<U>(t: Int, u: U) {} } class GenericSub<T> : ConcreteBase { override init<U>(t: Int, u: U) {} override func doStuff<U>(t: Int, u: U) {} } // Issue with generic parameter index class MoreGenericSub1<T, TT> : GenericBase<T> { override func doStuff<U>(t: T, u: U) {} } class MoreGenericSub2<TT, T> : GenericBase<T> { override func doStuff<U>(t: T, u: U) {} } // Issue with insufficient canonicalization when // comparing types protocol SI {} protocol CI {} protocol Sequence { associatedtype I : SI // expected-note{{declared here}} } protocol Collection : Sequence { associatedtype I : CI // expected-warning{{redeclaration of associated type 'I'}} } class Index<F, T> { func map(_ f: F) -> T {} } class CollectionIndex<C : Collection> : Index<C, C.I> { override func map(_ f: C) -> C.I {} }
apache-2.0
sunfei/RxSwift
RxDataSourceStarterKit/DataSources/RxTableViewSectionedReloadDataSource.swift
3
886
// // RxTableViewSectionedReloadDataSource.swift // RxExample // // Created by Krunoslav Zaher on 6/27/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class RxTableViewSectionedReloadDataSource<S: SectionModelType> : RxTableViewSectionedDataSource<S> , RxTableViewDataSourceType { typealias Element = [S] func tableView(tableView: UITableView, observedEvent: Event<Element>) { switch observedEvent { case .Next(let boxedSections): setSections(boxedSections.value) tableView.reloadData() case .Error(let error): #if DEBUG fatalError("Binding error to UI") #endif case .Completed: break } } }
mit
joerocca/GitHawk
Classes/Issues/Comments/Summary/IssueCommentSummaryModel.swift
1
557
// // IssueCommentSummaryModel.swift // Freetime // // Created by Ryan Nystrom on 5/22/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueCommentSummaryModel: ListDiffable { let summary: String init(summary: String) { self.summary = summary } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return summary as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } }
mit
remirobert/MyCurrency
MyCurrency/Network.swift
1
410
// // Network.swift // MyCurrency // // Created by Remi Robert on 09/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit class Network { func perform(ressource: Ressource, completion: @escaping ([CurrencyModel]?) -> Void) { URLSession.shared.dataTask(with: ressource.url) { (data, _, _) in completion(ressource.parse(data)) }.resume() } }
mit
overtake/TelegramSwift
packages/HackUtils/Package.swift
1
992
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "HackUtils", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "HackUtils", targets: ["HackUtils"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "HackUtils", dependencies: [], path: ".", publicHeadersPath: "Sources/HackUtils"), ] )
gpl-2.0
brentsimmons/Evergreen
Mac/AppDefaults.swift
1
12010
// // AppDefaults.swift // NetNewsWire // // Created by Brent Simmons on 9/22/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import AppKit enum FontSize: Int { case small = 0 case medium = 1 case large = 2 case veryLarge = 3 } final class AppDefaults { static let defaultThemeName = "Default" static var shared = AppDefaults() private init() {} struct Key { static let firstRunDate = "firstRunDate" static let windowState = "windowState" static let activeExtensionPointIDs = "activeExtensionPointIDs" static let lastImageCacheFlushDate = "lastImageCacheFlushDate" static let sidebarFontSize = "sidebarFontSize" static let timelineFontSize = "timelineFontSize" static let timelineSortDirection = "timelineSortDirection" static let timelineGroupByFeed = "timelineGroupByFeed" static let detailFontSize = "detailFontSize" static let openInBrowserInBackground = "openInBrowserInBackground" static let subscribeToFeedsInDefaultBrowser = "subscribeToFeedsInDefaultBrowser" static let articleTextSize = "articleTextSize" static let refreshInterval = "refreshInterval" static let addWebFeedAccountID = "addWebFeedAccountID" static let addWebFeedFolderName = "addWebFeedFolderName" static let addFolderAccountID = "addFolderAccountID" static let importOPMLAccountID = "importOPMLAccountID" static let exportOPMLAccountID = "exportOPMLAccountID" static let defaultBrowserID = "defaultBrowserID" static let currentThemeName = "currentThemeName" // Hidden prefs static let showDebugMenu = "ShowDebugMenu" static let timelineShowsSeparators = "CorreiaSeparators" static let showTitleOnMainWindow = "KafasisTitleMode" static let feedDoubleClickMarkAsRead = "GruberFeedDoubleClickMarkAsRead" static let suppressSyncOnLaunch = "DevroeSuppressSyncOnLaunch" #if !MAC_APP_STORE static let webInspectorEnabled = "WebInspectorEnabled" static let webInspectorStartsAttached = "__WebInspectorPageGroupLevel1__.WebKit2InspectorStartsAttached" #endif } private static let smallestFontSizeRawValue = FontSize.small.rawValue private static let largestFontSizeRawValue = FontSize.veryLarge.rawValue let isDeveloperBuild: Bool = { if let dev = Bundle.main.object(forInfoDictionaryKey: "DeveloperEntitlements") as? String, dev == "-dev" { return true } return false }() var isFirstRun: Bool = { if let _ = UserDefaults.standard.object(forKey: Key.firstRunDate) as? Date { return false } firstRunDate = Date() return true }() var windowState: [AnyHashable : Any]? { get { return UserDefaults.standard.object(forKey: Key.windowState) as? [AnyHashable : Any] } set { UserDefaults.standard.set(newValue, forKey: Key.windowState) } } var activeExtensionPointIDs: [[AnyHashable : AnyHashable]]? { get { return UserDefaults.standard.object(forKey: Key.activeExtensionPointIDs) as? [[AnyHashable : AnyHashable]] } set { UserDefaults.standard.set(newValue, forKey: Key.activeExtensionPointIDs) } } var lastImageCacheFlushDate: Date? { get { return AppDefaults.date(for: Key.lastImageCacheFlushDate) } set { AppDefaults.setDate(for: Key.lastImageCacheFlushDate, newValue) } } var openInBrowserInBackground: Bool { get { return AppDefaults.bool(for: Key.openInBrowserInBackground) } set { AppDefaults.setBool(for: Key.openInBrowserInBackground, newValue) } } // Special case for this default: store/retrieve it from the shared app group // defaults, so that it can be resolved by the Safari App Extension. var subscribeToFeedDefaults: UserDefaults { if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String, let appGroupDefaults = UserDefaults(suiteName: appGroupID) { return appGroupDefaults } else { return UserDefaults.standard } } var subscribeToFeedsInDefaultBrowser: Bool { get { return subscribeToFeedDefaults.bool(forKey: Key.subscribeToFeedsInDefaultBrowser) } set { subscribeToFeedDefaults.set(newValue, forKey: Key.subscribeToFeedsInDefaultBrowser) } } var sidebarFontSize: FontSize { get { return fontSize(for: Key.sidebarFontSize) } set { AppDefaults.setFontSize(for: Key.sidebarFontSize, newValue) } } var timelineFontSize: FontSize { get { return fontSize(for: Key.timelineFontSize) } set { AppDefaults.setFontSize(for: Key.timelineFontSize, newValue) } } var detailFontSize: FontSize { get { return fontSize(for: Key.detailFontSize) } set { AppDefaults.setFontSize(for: Key.detailFontSize, newValue) } } var addWebFeedAccountID: String? { get { return AppDefaults.string(for: Key.addWebFeedAccountID) } set { AppDefaults.setString(for: Key.addWebFeedAccountID, newValue) } } var addWebFeedFolderName: String? { get { return AppDefaults.string(for: Key.addWebFeedFolderName) } set { AppDefaults.setString(for: Key.addWebFeedFolderName, newValue) } } var addFolderAccountID: String? { get { return AppDefaults.string(for: Key.addFolderAccountID) } set { AppDefaults.setString(for: Key.addFolderAccountID, newValue) } } var importOPMLAccountID: String? { get { return AppDefaults.string(for: Key.importOPMLAccountID) } set { AppDefaults.setString(for: Key.importOPMLAccountID, newValue) } } var exportOPMLAccountID: String? { get { return AppDefaults.string(for: Key.exportOPMLAccountID) } set { AppDefaults.setString(for: Key.exportOPMLAccountID, newValue) } } var defaultBrowserID: String? { get { return AppDefaults.string(for: Key.defaultBrowserID) } set { AppDefaults.setString(for: Key.defaultBrowserID, newValue) } } var currentThemeName: String? { get { return AppDefaults.string(for: Key.currentThemeName) } set { AppDefaults.setString(for: Key.currentThemeName, newValue) } } var showTitleOnMainWindow: Bool { return AppDefaults.bool(for: Key.showTitleOnMainWindow) } var showDebugMenu: Bool { return AppDefaults.bool(for: Key.showDebugMenu) } var feedDoubleClickMarkAsRead: Bool { get { return AppDefaults.bool(for: Key.feedDoubleClickMarkAsRead) } set { AppDefaults.setBool(for: Key.feedDoubleClickMarkAsRead, newValue) } } var suppressSyncOnLaunch: Bool { get { return AppDefaults.bool(for: Key.suppressSyncOnLaunch) } set { AppDefaults.setBool(for: Key.suppressSyncOnLaunch, newValue) } } #if !MAC_APP_STORE var webInspectorEnabled: Bool { get { return AppDefaults.bool(for: Key.webInspectorEnabled) } set { AppDefaults.setBool(for: Key.webInspectorEnabled, newValue) } } var webInspectorStartsAttached: Bool { get { return AppDefaults.bool(for: Key.webInspectorStartsAttached) } set { AppDefaults.setBool(for: Key.webInspectorStartsAttached, newValue) } } #endif var timelineSortDirection: ComparisonResult { get { return AppDefaults.sortDirection(for: Key.timelineSortDirection) } set { AppDefaults.setSortDirection(for: Key.timelineSortDirection, newValue) } } var timelineGroupByFeed: Bool { get { return AppDefaults.bool(for: Key.timelineGroupByFeed) } set { AppDefaults.setBool(for: Key.timelineGroupByFeed, newValue) } } var timelineShowsSeparators: Bool { return AppDefaults.bool(for: Key.timelineShowsSeparators) } var articleTextSize: ArticleTextSize { get { let rawValue = UserDefaults.standard.integer(forKey: Key.articleTextSize) return ArticleTextSize(rawValue: rawValue) ?? ArticleTextSize.large } set { UserDefaults.standard.set(newValue.rawValue, forKey: Key.articleTextSize) } } var refreshInterval: RefreshInterval { get { let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval) return RefreshInterval(rawValue: rawValue) ?? RefreshInterval.everyHour } set { UserDefaults.standard.set(newValue.rawValue, forKey: Key.refreshInterval) } } func registerDefaults() { #if DEBUG let showDebugMenu = true #else let showDebugMenu = false #endif let defaults: [String : Any] = [Key.sidebarFontSize: FontSize.medium.rawValue, Key.timelineFontSize: FontSize.medium.rawValue, Key.detailFontSize: FontSize.medium.rawValue, Key.timelineSortDirection: ComparisonResult.orderedDescending.rawValue, Key.timelineGroupByFeed: false, "NSScrollViewShouldScrollUnderTitlebar": false, Key.refreshInterval: RefreshInterval.everyHour.rawValue, Key.showDebugMenu: showDebugMenu, Key.currentThemeName: Self.defaultThemeName] UserDefaults.standard.register(defaults: defaults) // It seems that registering a default for NSQuitAlwaysKeepsWindows to true // is not good enough to get the system to respect it, so we have to literally // set it as the default to get it to take effect. This overrides a system-wide // setting in the System Preferences, which is ostensibly meant to "close windows" // in an app, but has the side-effect of also not preserving or restoring any state // for the window. Since we've switched to using the standard state preservation and // restoration mechanisms, and because it seems highly unlikely any user would object // to NetNewsWire preserving this state, we'll force the preference on. If this becomes // an issue, this could be changed to proactively look for whether the default has been // set _by the user_ to false, and respect that default if it is so-set. // UserDefaults.standard.set(true, forKey: "NSQuitAlwaysKeepsWindows") // TODO: revisit the above when coming back to state restoration issues. } func actualFontSize(for fontSize: FontSize) -> CGFloat { switch fontSize { case .small: return NSFont.systemFontSize case .medium: return actualFontSize(for: .small) + 1.0 case .large: return actualFontSize(for: .medium) + 4.0 case .veryLarge: return actualFontSize(for: .large) + 8.0 } } } private extension AppDefaults { static var firstRunDate: Date? { get { return AppDefaults.date(for: Key.firstRunDate) } set { AppDefaults.setDate(for: Key.firstRunDate, newValue) } } func fontSize(for key: String) -> FontSize { // Punted till after 1.0. return .medium // var rawFontSize = int(for: key) // if rawFontSize < smallestFontSizeRawValue { // rawFontSize = smallestFontSizeRawValue // } // if rawFontSize > largestFontSizeRawValue { // rawFontSize = largestFontSizeRawValue // } // return FontSize(rawValue: rawFontSize)! } static func setFontSize(for key: String, _ fontSize: FontSize) { setInt(for: key, fontSize.rawValue) } static func string(for key: String) -> String? { return UserDefaults.standard.string(forKey: key) } static func setString(for key: String, _ value: String?) { UserDefaults.standard.set(value, forKey: key) } static func bool(for key: String) -> Bool { return UserDefaults.standard.bool(forKey: key) } static func setBool(for key: String, _ flag: Bool) { UserDefaults.standard.set(flag, forKey: key) } static func int(for key: String) -> Int { return UserDefaults.standard.integer(forKey: key) } static func setInt(for key: String, _ x: Int) { UserDefaults.standard.set(x, forKey: key) } static func date(for key: String) -> Date? { return UserDefaults.standard.object(forKey: key) as? Date } static func setDate(for key: String, _ date: Date?) { UserDefaults.standard.set(date, forKey: key) } static func sortDirection(for key:String) -> ComparisonResult { let rawInt = int(for: key) if rawInt == ComparisonResult.orderedAscending.rawValue { return .orderedAscending } return .orderedDescending } static func setSortDirection(for key: String, _ value: ComparisonResult) { if value == .orderedAscending { setInt(for: key, ComparisonResult.orderedAscending.rawValue) } else { setInt(for: key, ComparisonResult.orderedDescending.rawValue) } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/20614-no-stacktrace.swift
11
266
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A { var _ = [ let { struct A { let e, T { protocol A { deinit { { func i( ) { class case ,
mit
mightydeveloper/swift
validation-test/compiler_crashers/26867-std-function-func-swift-type-subst.swift
9
323
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{ class B func f{ class a<T where B:a{class A{ class a class A class A:a{ func a<I where B:a
apache-2.0
Maheepk/MKLabel
Example/MKLabel/AppDelegate.swift
1
2152
// // AppDelegate.swift // MKLabel // // Created by Maheep Kaushal on 02/02/2016. // Copyright (c) 2016 Maheep Kaushal. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ProcedureKit/ProcedureKit
Tests/ProcedureKitStressTests/BlockProcedureStressTests.swift
2
1779
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import XCTest import TestingProcedureKit @testable import ProcedureKit class CancelBlockProcedureStessTests: StressTestCase { func test__cancel_block_procedure() { stress(level: .custom(10, 5_000)) { batch, _ in batch.dispatchGroup.enter() // enter once for cancel batch.dispatchGroup.enter() // enter once for finish let block = BlockProcedure { this in // prevent the BlockProcedure from finishing before it is cancelled while false == this.isCancelled { usleep(10) } this.finish() } block.addDidCancelBlockObserver { _, _ in batch.dispatchGroup.leave() // leave once for cancel } block.addDidFinishBlockObserver { _, _ in batch.dispatchGroup.leave() // leave once for finish } batch.queue.addOperation(block) block.cancel() } } func test_cancel_or_finish_block_procedure() { // NOTE: // It is possible for a BlockProcedure to finish prior to the call to // `block.cancel()` (depending on timing) and thus not all of the // BlockProcedures created below may be effectively cancelled. // However, all of the BlockProcedures should finish. stress(level: .custom(10, 5_000)) { batch, _ in batch.dispatchGroup.enter() let block = BlockProcedure { } block.addDidFinishBlockObserver { _, _ in batch.dispatchGroup.leave() } batch.queue.addOperation(block) block.cancel() } } }
mit
slightair/SwiftGraphics
Demos/SwiftGraphics_OSX_UITest/HandleEditor/Scratch.swift
3
538
// // Scratch.swift // HandleEditor // // Created by Jonathan Wight on 11/17/14. // Copyright (c) 2014 schwa.io. All rights reserved. // import SwiftGraphics // MARK: - protocol Drawable { func draw(context: CGContext) } extension Rectangle: Drawable { func draw(context: CGContext) { context.strokeRect(self.frame) } } extension Line: Drawable { func draw(context: CGContext) { } } extension LineSegment: Drawable { func draw(context: CGContext) { context.strokeLine(start, end) } }
bsd-2-clause
jtaxen/FindShelter
Pods/FBAnnotationClusteringSwift/Pod/Classes/FBAnnotationClusterView.swift
1
4238
// // FBAnnotationClusterView.swift // FBAnnotationClusteringSwift // // Created by Robert Chen on 4/2/15. // Copyright (c) 2015 Robert Chen. All rights reserved. // import Foundation import MapKit open class FBAnnotationClusterView : MKAnnotationView { var count = 0 var fontSize:CGFloat = 12 var imageName = "clusterSmall" var loadExternalImage : Bool = false var borderWidth:CGFloat = 3 var countLabel:UILabel? = nil //var option : FBAnnotationClusterViewOptions? = nil public init(annotation: MKAnnotation?, reuseIdentifier: String?, options: FBAnnotationClusterViewOptions?){ super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) let cluster:FBAnnotationCluster = annotation as! FBAnnotationCluster count = cluster.annotations.count // change the size of the cluster image based on number of stories switch count { case 0...5: fontSize = 12 if (options != nil) { loadExternalImage=true; imageName = (options?.smallClusterImage)! } else { imageName = "clusterSmall" } borderWidth = 3 case 6...15: fontSize = 13 if (options != nil) { loadExternalImage=true; imageName = (options?.mediumClusterImage)! } else { imageName = "clusterMedium" } borderWidth = 4 default: fontSize = 14 if (options != nil) { loadExternalImage=true; imageName = (options?.largeClusterImage)! } else { imageName = "clusterLarge" } borderWidth = 5 } backgroundColor = UIColor.clear setupLabel() setTheCount(count) } // required override public init(frame: CGRect) { // super.init(frame: frame) // // } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupLabel(){ countLabel = UILabel(frame: bounds) if let countLabel = countLabel { countLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] countLabel.textAlignment = .center countLabel.backgroundColor = UIColor.clear countLabel.textColor = UIColor(red: 5/255, green: 56/255, blue: 126/255, alpha: 1.0) countLabel.adjustsFontSizeToFitWidth = true countLabel.minimumScaleFactor = 2 countLabel.numberOfLines = 1 countLabel.font = UIFont(name: "Futura", size: fontSize) countLabel.baselineAdjustment = .alignCenters addSubview(countLabel) } } func setTheCount(_ localCount:Int){ count = localCount; countLabel?.text = "\(localCount)" setNeedsLayout() } override open func layoutSubviews() { // Images are faster than using drawRect: let imageAsset = UIImage(named: imageName, in: (!loadExternalImage) ? Bundle(for: FBAnnotationClusterView.self) : nil, compatibleWith: nil) //UIImage(named: imageName)! countLabel?.frame = self.bounds image = imageAsset centerOffset = CGPoint.zero // adds a white border around the green circle layer.borderColor = UIColor(red: 5/255, green: 56/255, blue: 126/255, alpha: 1.0).cgColor layer.borderWidth = borderWidth layer.cornerRadius = self.bounds.size.width / 2 } } open class FBAnnotationClusterViewOptions : NSObject { var smallClusterImage : String var mediumClusterImage : String var largeClusterImage : String public init (smallClusterImage : String, mediumClusterImage : String, largeClusterImage : String) { self.smallClusterImage = smallClusterImage; self.mediumClusterImage = mediumClusterImage; self.largeClusterImage = largeClusterImage; } }
mit
ryanbaldwin/Restivus
Tests/GettableSpec.swift
1
2796
// // GettableSpec.swift // Restivus // // Created by Ryan Baldwin on 2017-08-28. //Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Quick import Nimble @testable import Restivus extension Gettable { var baseURL: String { return "http://google.ca" } } class GettableSpec: QuickSpec { override func spec() { describe("A default Gettable") { var context: [String: Any]! beforeEach { context = ["method": HTTPMethod.get, "restable": AnyRestable<Person>(GetPersonRequest()), "encodable": AnyRestable<Person>(EncodableGetPersonRequest(personId: "123"))] } itBehavesLike("a Restable") { context } } describe("A gettable with a dateDecodingStrategy") { it("It decodes the response data according to the dateDecodingStrategy") { let gettable = DateRequest() let currentDateString = "2018-06-12T20:00:00.000-04:00" let currentDate = gettable.dateFormatter().date(from: currentDateString)! let data = """ { "date": "\(currentDateString)" } """.data(using: .utf8)! var dateResponse: DateResponse? = nil // NOTE: We use a dummy url response here as the `dataTaskCompletionHandler` needs it. // As long as this method gets a success statusCode (ie. 200) from an HTTPURLResponse, it will proceed to decode the data passed in. // We want to verify that it is decoding it according to the `dateDecodingStrategy` of the `DateRequest` let response = HTTPURLResponse(url: URL(string: "http://google.ca")!, statusCode: 200, httpVersion: nil, headerFields: nil) gettable.dataTaskCompletionHandler(data: data, response: response, error: nil) { response in if case let .success(tempDateResponse) = response { dateResponse = tempDateResponse } } expect(dateResponse).toNot(beNil()) // compare the dates let currentComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: currentDate) let actualComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateResponse!.date) expect(currentComponents).toNot(beNil()) expect(currentComponents) == actualComponents } } } }
apache-2.0
sweetmandm/Validate
Tests/ValidateTests/OnFieldTests.swift
1
1486
// // OnFieldTests.swift // Validate // // Created by sweetman on 4/30/17. // Copyright © 2017 tinfish. All rights reserved. // import XCTest @testable import Validate class OnFieldTests: XCTestCase { var subject: OnField! let field = FieldObject() let reason = "There is a problem." override func setUp() { subject = OnField(reason: reason, field: field) } func testReason() { XCTAssertTrue( subject.reason == reason ) } func testField() { XCTAssertTrue( subject.field as? FieldObject == field ) } func testNeutralStyleApplication() { subject.applyNeutralStyle() XCTAssertTrue( field.called.count == 1 ) XCTAssertTrue( field.called.contains("applyNeutralStyle()") ) } func testValidStyleApplication() { subject.applyValidStyle() XCTAssertTrue( field.called.count == 1 ) XCTAssertTrue( field.called.contains("applyValidStyle()") ) } func testInvalidStyleApplication() { subject.applyInvalidStyle() XCTAssertTrue( field.called.count == 1 ) XCTAssertTrue( field.called.contains("applyInvalidStyle(error:)") ) XCTAssertTrue( field.withError as? OnField === subject ) } }
mit
ualch9/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/ShadowSelectionTableViewCell.swift
3
1286
// // ShadowSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/25/18. // Copyright (c) 2018 huri000@gmail.com. All rights reserved. // import UIKit import SwiftEntryKit class ShadowSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Drop Shadow" descriptionValue = "A drop shadow effect that can be applied to the entry" insertSegments(by: ["Off", "On"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.shadow { case .none: segmentedControl.selectedSegmentIndex = 0 case .active(with: _): segmentedControl.selectedSegmentIndex = 1 } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.shadow = .none case 1: let value = EKAttributes.Shadow.Value(color: .black, opacity: 0.5, radius: 10, offset: .zero) attributesWrapper.attributes.shadow = .active(with: value) default: break } } }
apache-2.0
Flinesoft/CSVImporter
UsageExamples.playground/Contents.swift
1
6291
import Foundation import CSVImporter import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: Get the path to an example CSV file (see Resources folder of this Playground). let path = Bundle.main.path(forResource: "Teams", ofType: "csv")! //: ## CSVImporter //: The CSVImporter class is the class which includes all the import logic. //: ### init<T>(path:) //: First create an instance of CSVImporter. Let's do this with the default type `[String]` like this: let defaultImporter = CSVImporter<[String]>(path: path) let stringImporter = CSVImporter<[String]>(contentString: try! String(contentsOfFile: path)) //: ### Basic import: .startImportingRecords & .onFinish //: For a basic line-by-line import of your file start the import and use the `.onFinish` callback. The import is done asynchronously but all callbacks (like `.onFinish`) are called on the main thread. defaultImporter.startImportingRecords { $0 }.onFinish { importedRecords in type(of: importedRecords) importedRecords.count // number of all records importedRecords[100] // this is a single record importedRecords // array with all records (in this case an array of arrays) } stringImporter.startImportingRecords { $0 }.onFinish { importedRecords in type(of: importedRecords) importedRecords.count // number of all records importedRecords[100] // this is a single record importedRecords // array with all records (in this case an array of arrays) } //: ### Synchronous import: .importRecords //: Line-by-line import which results in the end result immediately. Works synchronously. let results = defaultImporter.importRecords { $0 } results //: ### .onFail //: In case your path was wrong the chainable `.onFail` callback will be called instead of the `.onFinish`. let wrongPathImporter = CSVImporter<[String]>(path: "a/wrong/path") wrongPathImporter.startImportingRecords { $0 }.onFail { _ = ".onFail called because the path is wrong" }.onFinish { importedRecords in _ = ".onFinish is never called here because the path is wrong" } //: ### .onProgress //: If you want to show progress to your users you can use the `.onProgress` callback. It will be called multiple times a second with the current number of lines already processed. defaultImporter.startImportingRecords { $0 }.onProgress { importedDataLinesCount in importedDataLinesCount "Progress Update in main thread: \(importedDataLinesCount) lines were imported" } //: ### .startImportingRecords(structure:) //: Some CSV files offer some structural information about the data on the first line (the header line). You can also tell CSVImporter to use this first line to return a dictionary where the structure information are used as keys. The default data type for structural imports therefore is a String dictionary (`[String: String]`). let structureImporter = CSVImporter<[String: String]>(path: path) structureImporter.startImportingRecords(structure: { headerValues in _ = headerValues // the structural information from the first line as a [String] }){ $0 }.onFinish { importedRecords in type(of: importedRecords) importedRecords.count // the number of all imported records importedRecords[99] // this is a single record } //: ### .startImportingRecords(mapper:) //: You don't need to use the default types `[String]` for the default importer. You can use your own type by proving your own mapper instead of `{ $0 }` from the examples above. The mapper gets a `[String]` and needs to return your own type. // Let's define our own class: class Team { let year: String, league: String init(year: String, league: String) { self.year = year self.league = league } } // Now create an importer for our own type and start importing: let teamsDefaultImporter = CSVImporter<Team>(path: path) teamsDefaultImporter.startImportingRecords { recordValues -> Team in return Team(year: recordValues[0], league: recordValues[1]) }.onFinish { importedRecords in type(of: importedRecords) // the type is now [Team] importedRecords.count // number of all imported records let aTeam = importedRecords[100] aTeam.year aTeam.league } //: ### .startImportingRecords(structure:recordMapper:) //: You can also use a record mapper and use structured data together. In this case the mapper gets a `[String: String]` and needs to return with your own type again. let teamsStructuredImporter = CSVImporter<Team>(path: path) teamsStructuredImporter.startImportingRecords(structure: { headerValues in _ = headerValues // the structure form the first line of the CSV file }) { recordValues -> Team in return Team(year: recordValues["yearID"]!, league: recordValues["lgID"]!) }.onFinish { (importedRecords) -> Void in type(of: importedRecords) // the type is now [Team] importedRecords.count // number of all imported records let aTeam = importedRecords[99] aTeam.year aTeam.league } //: Note that the structural importer is slower than the default importer. //: You can also build an importer with a file URL //: Get the file URL to an example CSV file (see Resources folder of this Playground). let fileURL = Bundle.main.url(forResource: "Teams.csv", withExtension: nil)! //: ## CSVImporter //: The CSVImporter class is the class that includes all the import logic. //: ### init<T>(path:) //: First create an instance of CSVImporter. Let's do this with the default type `[String]` like this: let fileURLImporter = CSVImporter<[String]>(url: fileURL) //: ### Basic import: .startImportingRecords & .onFinish //: For a basic line-by-line import of your file start the import and use the `.onFinish` callback. The import is done asynchronously but all callbacks (like `.onFinish`) are called on the main thread. fileURLImporter?.startImportingRecords { $0 }.onFinish { importedRecords in type(of: importedRecords) importedRecords.count // number of all records importedRecords[100] // this is a single record importedRecords // array with all records (in this case an array of arrays) }
mit
pawan007/SmartZip
SmartZip/Library/Managers/Analytics Manager/AnalyticsManager.swift
1
3284
// // AnalyticsManager.swift // // Created by Geetika Gupta on 06/04/16. // Copyright © 2016 Modi. All rights reserved. // import UIKit import Mixpanel //import Flurry_iOS_SDK enum PlatformType { case MixPannel case Flurry case GoogleAnalytics } class AnalyticsManager: NSObject { var platformType: PlatformType = .MixPannel // MARK: - Singleton Instance private static let _sharedManager = AnalyticsManager() class func sharedManager() -> AnalyticsManager { return _sharedManager } private override init() { super.init() // customize initialization } /** Method to initialize track tool as per their selection. - parameter tool: A type of track tool */ func initializeTracker() { switch self.platformType { case .Flurry: break // Flurry.startSession(Constants.Tokens.FLURRY_APP_ID); // Flurry.setCrashReportingEnabled(true) case .GoogleAnalytics: self.googleAnalyserInitialize() default: break // .MixPannel: Mixpanel.sharedInstanceWithToken(Constants.Tokens.MIX_PANNEL_TOKEN) } } /** Track event on particular event. - parameter eventName: A String is a event name which we want to given for track - parameter attributes: A Dictionary to ass more attribute - parameter tool: track tool which contain type of tool which we want to prefer for tracking - parameter screenName: A String is a screen name */ func trackEvent(eventName: String, attributes: NSDictionary?, screenName: String?) { switch self.platformType { case .Flurry: break // Flurry.logEvent(eventName, withParameters: attributes as! [NSObject : AnyObject]) case .GoogleAnalytics: break // let tracker = GAI.sharedInstance().defaultTracker // tracker.set(kGAIEvent, value: eventName) // // let builder = GAIDictionaryBuilder.createEventWithCategory(eventName, action: nil, label:screenName, value: 0) // tracker.send(builder.build() as [NSObject : AnyObject]) default: // .MixPannel: Mixpanel.sharedInstance().track(eventName, properties: (attributes as! [NSObject : AnyObject])) //Plan selected) } } /** A initializer method to initiate google analyser for start tracking. */ func googleAnalyserInitialize () { //var configureError:NSError? //GGLContext.sharedInstance().configureWithError(&configureError) //assert(configureError == nil, "Error configuring Google services: \(configureError)") // let gai = GAI.sharedInstance() // let tracker:GAITracker = gai.trackerWithTrackingId(GOOGLE_ANALYTICS_APP_ID) // Enable Remarketing, Demographics & Interests reports. // tracker.allowIDFACollection = true // Optional: configure GAI options. // gai.trackUncaughtExceptions = true // report uncaught exceptions // gai.LogManager.logLevel = GAILogLevel.Verbose // remove before app release } }
mit
austinzheng/swift
test/Inputs/conditional_conformance_basic_conformances.swift
2
16543
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public struct IsP3: P3 {} public struct Single<A> {} extension Single: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Single.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE6normalyyF"(%swift.type* [[A]], i8** [[A_P2]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Single.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func single_generic<T: P2>(_: T.Type) { takes_p1(Single<T>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func single_concrete() { takes_p1(Single<IsP2>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances15single_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Single<IsP2> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public struct Double<B, C> {} extension Double: P1 where B: P2, C: P3 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Double.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE6normalyyF"(%swift.type* [[B]], %swift.type* [[C]], i8** [[B_P2]], i8** [[C_P3]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Double.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) { takes_p1(Double<U, V>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF"(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %U, %swift.type* %V) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %U.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** %V.P3, i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_generic_concrete<X: P2>(_: X.Type) { takes_p1(Double<X, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF"(%swift.type*, %swift.type* %X, i8** %X.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %X, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ {{.*}} }>* }>, <{ {{.*}} }>* @"$s42conditional_conformance_basic_conformances4IsP3VMf", i32 0, i32 1) to %swift.type*)) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %X.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_concrete_concrete() { takes_p1(Double<IsP2, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances016double_concrete_F0yyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Double<IsP2, IsP3> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } func dynamicCastToP1(_ value: Any) -> P1? { return value as? P1 } protocol P4 {} typealias P4Typealias = P4 protocol P5 {} struct SR7101<T> {} extension SR7101 : P5 where T == P4Typealias {}
apache-2.0
austinzheng/swift
benchmark/single-source/Memset.swift
34
931
//===--- Memset.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let Memset = BenchmarkInfo( name: "Memset", runFunction: run_Memset, tags: [.validation]) @inline(never) func memset(_ a: inout [Int], _ c: Int) { for i in 0..<a.count { a[i] = c } } @inline(never) public func run_Memset(_ N: Int) { var a = [Int](repeating: 0, count: 10_000) for _ in 1...50*N { memset(&a, 1) memset(&a, 0) } CheckResults(a[87] == 0) }
apache-2.0
ualch9/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Source/Model/EKSimpleMessage.swift
3
718
// // EKSimpleMessage.swift // SwiftEntryKit // // Created by Daniel Huri on 6/1/18. // Copyright (c) 2018 huri000@gmail.com. All rights reserved. // import Foundation public struct EKSimpleMessage { /** The image view descriptor */ public let image: EKProperty.ImageContent? /** The title label descriptor */ public let title: EKProperty.LabelContent /** The description label descriptor */ public let description: EKProperty.LabelContent public init(image: EKProperty.ImageContent? = nil, title: EKProperty.LabelContent, description: EKProperty.LabelContent) { self.image = image self.title = title self.description = description } }
apache-2.0
ReiVerdugo/uikit-fundamentals
step4.8-roshamboWithHistory-solution/RockPaperScissors/HistoryViewController.swift
1
1663
// // File.swift // RockPaperScissors // // Created by Jason on 11/14/14. // Copyright (c) 2014 Gabrielle Miller-Messner. All rights reserved. // import Foundation import UIKit // MARK: - HistoryViewController : UIViewController, UITableViewDelegate, UITableViewDataSource class HistoryViewController : UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Properties var history: [RPSMatch]! // MARK: Outlets @IBOutlet weak var tableView: UITableView! // MARK: Table View Delegate func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return history.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellID = "HistoryCell" let cell = tableView.dequeueReusableCellWithIdentifier(CellID, forIndexPath: indexPath) let match = self.history[indexPath.row] cell.textLabel!.text = victoryStatusDescription(match) cell.detailTextLabel!.text = "\(match.p1) vs. \(match.p2)" return cell } // MARK: Victory Status func victoryStatusDescription(match: RPSMatch) -> String { if (match.p1 == match.p2) { return "Tie." } else if (match.p1.defeats(match.p2)) { return "Win!" } else { return "Loss." } } // MARK: Actions @IBAction func dismissHistory(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
Pandanx/PhotoPickerController
Classes/PhotoGridController.swift
1
13543
// // PhotoGridController.swift // Photos // // Created by 张晓鑫 on 2017/6/1. // Copyright © 2017年 Wang. All rights reserved. // import UIKit import Photos let screenWidth:CGFloat = UIScreen.main.bounds.width let screenHeigth:CGFloat = UIScreen.main.bounds.height class PhotoGridController: UIViewController { var completeItem: UIBarButtonItem! = UIBarButtonItem() var collectionView: UICollectionView! ///后去到的结果 存放PHAsset var assetsFetchResults: PHFetchResult<PHAsset>! ///带缓存的图片管理对象 var imageMannger: PHCachingImageManager! ///预览图大小 open var assetGridThumbnailSize: CGSize! //原图大小 var realImageSize: CGSize! ///与缓存Rect var previousPreheatRect: CGRect! ///最多可选择的个数 var maxSelected = 9 ///点击完成时的回调 var completeHandler:((_ assets:[PHAsset]) ->())? var shouldDeleteAfterExport: Bool = false lazy var selectedLabel: ImageSelectedLabel = { let tempLabel = ImageSelectedLabel(toolBar:self.navigationController!.toolbar) return tempLabel }() override func viewDidLoad() { super.viewDidLoad() //设置流对象layout let collectionLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() collectionLayout.minimumLineSpacing = 1 collectionLayout.minimumInteritemSpacing = 1 collectionLayout.sectionInset = UIEdgeInsets.zero collectionLayout.itemSize = CGSize(width:screenWidth/4.0-1, height:screenWidth/4.0-1) collectionView = UICollectionView(frame:view.bounds, collectionViewLayout: collectionLayout) collectionView.register(PhotoGridCell.self, forCellWithReuseIdentifier: "PhotoGridCollectionCell") collectionView.backgroundColor = UIColor.white //并设置允许多选 collectionView.allowsMultipleSelection = true collectionView.delegate = self collectionView.dataSource = self self.view.addSubview(collectionView) completeItem = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.plain, target: self, action: #selector(finishSelected)) let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) self.toolbarItems = [flexibleItem, completeItem] if assetsFetchResults == nil { //如果没有传入值 则获取所有资源 let allPhotoOption = PHFetchOptions() allPhotoOption.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] assetsFetchResults = PHAsset.fetchAssets(with: allPhotoOption) } //初始化和重置缓存 imageMannger = PHCachingImageManager() self.resetCachedAssets() let rightBarItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel)) navigationItem.rightBarButtonItem = rightBarItem completeItem.action = #selector(finishSelected) disableItems() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //计算出小图大小(为targetSize做准备) let scale = UIScreen.main.scale let cellSize = (self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize assetGridThumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale) realImageSize = CGSize(width: screenWidth * scale, height: screenHeigth * scale) self.navigationController!.isToolbarHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController!.isToolbarHidden = true selectedLabel.selectedNumber = 0 } // 是否页面加载完毕 , 加载完毕后再做缓存 否则数值可能有误 var didLoad = false override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) didLoad = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func enableItems() { completeItem.isEnabled = true } fileprivate func disableItems() { completeItem.isEnabled = false } /** 重置缓存 */ func resetCachedAssets() { imageMannger.stopCachingImagesForAllAssets() previousPreheatRect = CGRect.zero } /** 取消 */ func cancel() { navigationController?.dismiss(animated: true, completion: nil) } /** 获取已选择个数 */ func selectedCount() -> Int { return self.collectionView.indexPathsForSelectedItems?.count ?? 0 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension PhotoGridController { /** 点击完成调出图片资源 */ func finishSelected() { var assets:[PHAsset] = [] // let manager = PHImageManager.default() let option = PHImageRequestOptions() option.isSynchronous = true option.resizeMode = .fast if let indexPaths = collectionView.indexPathsForSelectedItems { indexPaths.forEach({ (indexPath) in assets.append(assetsFetchResults[indexPath.row]) }) } self.dismiss(animated: true) { self.completeHandler?(assets) } } func assetToUIImage(asset: PHAsset, isThumbImage:Bool) -> UIImage? { var image: UIImage? // 新建一个默认类型的图像管理器imageManager let imageManager = PHImageManager.default() // 新建一个PHImageRequestOptions对象 let imageRequestOption = PHImageRequestOptions() // PHImageRequestOptions是否有效 imageRequestOption.isSynchronous = true // 缩略图的压缩模式设置为无 imageRequestOption.resizeMode = .none // 缩略图的质量为高质量,不管加载时间花多少 imageRequestOption.deliveryMode = .highQualityFormat // 按照PHImageRequestOptions指定的规则取出图片 imageManager.requestImage(for: asset, targetSize: isThumbImage ? assetGridThumbnailSize : PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOption, resultHandler: { (result, _ info) -> Void in image = result }) return image } } // MARK: - UICollectionViewDelegate&&UICollectionViewDataSource extension PhotoGridController:UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.assetsFetchResults.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoGridCollectionCell", for: indexPath) as! PhotoGridCell let asset = self.assetsFetchResults[indexPath.row] imageMannger.requestImage(for: asset, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil) { (image, info) in cell.imageView.image = image switch asset.mediaType { case .video: cell.duration = asset.duration default: break } } return cell } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? PhotoGridCell { let selectedCount = self.selectedCount() selectedLabel.selectedNumber = selectedCount if selectedCount == 0 { self.disableItems() } cell.showAnim() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? PhotoGridCell { let selectedCount = self.selectedCount() if selectedCount > self.maxSelected { //选择个数大于选择数 设置为不选中状态 collectionView.deselectItem(at: indexPath, animated: false) selectedLabel.animateMaxSelected() } else { selectedLabel.selectedNumber = selectedCount if selectedCount > 0 && !self.completeItem.isEnabled{ self.enableItems() } cell.showAnim() } } } /** 滚动中更新缓存 */ func scrollViewDidScroll(_ scrollView: UIScrollView) { self.updateChachedAssets() } func updateChachedAssets() { let isViewVisible = self.isViewLoaded && didLoad if !isViewVisible { return } var preheatRect = self.collectionView.bounds preheatRect = preheatRect.insetBy(dx: 0, dy: -0.5*preheatRect.height) let delta = abs(preheatRect.midY - self.previousPreheatRect.midY) if delta > collectionView.bounds.size.height / 3.0 { var addIndexPaths = [IndexPath]() var removedIndexPaths = [IndexPath]() self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: { (removedRect) in let indexPaths = self.collectionView.indexPathsForElementsInRect(removedRect) removedIndexPaths = removedIndexPaths.filter({ (indexPath) -> Bool in return !indexPaths.contains(indexPath) }) }, addedHandler: { (addedRect) in let indexPaths = self.collectionView.indexPathsForElementsInRect(addedRect) indexPaths.forEach({ (indexPath) in addIndexPaths.append(indexPath) }) }) let assetsToStartCaching = self.assetsAtIndexPaths(addIndexPaths) let assetsStopCaching = self.assetsAtIndexPaths(removedIndexPaths) self.imageMannger.startCachingImages(for: assetsToStartCaching, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil) self.imageMannger.stopCachingImages(for: assetsStopCaching, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil) self.previousPreheatRect = preheatRect } } func computeDifferenceBetweenRect(_ oldRect:CGRect, andRect newRect:CGRect, removedHandler:((_ removedRect:CGRect)->())?, addedHandler:((_ addedRect:CGRect)->())?) { //判断两个矩形是否相交 if newRect.intersects(oldRect) { let oldMaxY = oldRect.maxY let newMaxY = newRect.maxY let oldMinY = oldRect.minY let newMinY = oldRect.minY if newMaxY > oldMaxY { let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: newMaxY - oldMaxY) addedHandler?(rectToAdd) } if oldMinY > newMinY { let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: oldMinY - newMinY) addedHandler?(rectToAdd) } if newMaxY < oldMaxY { let rectToRemove = CGRect(x: newRect.origin.x, y: newMaxY, width:newRect.size.width, height: oldMaxY - newMaxY) removedHandler?(rectToRemove) } if oldMinY < newMinY { let rectToRemove = CGRect(x: newRect.origin.x, y: oldMinY, width:newRect.size.width, height: newMinY - oldMinY) removedHandler?(rectToRemove) } } else { addedHandler?(newRect) removedHandler?(oldRect) } } func assetsAtIndexPaths(_ indexPaths:[IndexPath]) -> [PHAsset] { var assets = [PHAsset]() indexPaths.forEach { (indexPath) in let asset = self.assetsFetchResults[indexPath.row] assets.append(asset) } return assets } } extension UICollectionView { func indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect) if let allLayoutAttributes = allLayoutAttributes , allLayoutAttributes.count == 0 { var indexPaths = [IndexPath]() allLayoutAttributes.forEach({ (attribute) in let indexPath = attribute.indexPath indexPaths.append(indexPath) }) return indexPaths }else { return [] } } }
mit
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift
71
5688
// // SerialDispatchQueueScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import struct Foundation.TimeInterval import struct Foundation.Date import Dispatch /** Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure that even if concurrent dispatch queue is passed, it's transformed into a serial one. It is extremely important that this scheduler is serial, because certain operator perform optimizations that rely on that property. Because there is no way of detecting is passed dispatch queue serial or concurrent, for every queue that is being passed, worst case (concurrent) will be assumed, and internal serial proxy dispatch queue will be created. This scheduler can also be used with internal serial queue alone. In case some customization need to be made on it before usage, internal serial queue can be customized using `serialQueueConfiguration` callback. */ public class SerialDispatchQueueScheduler : SchedulerType { public typealias TimeInterval = Foundation.TimeInterval public typealias Time = Date /// - returns: Current time. public var now : Date { return Date() } let configuration: DispatchQueueConfiguration init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) } /** Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. - parameter internalSerialQueueName: Name of internal serial dispatch queue. - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. */ public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) serialQueueConfiguration?(queue) self.init(serialQueue: queue, leeway: leeway) } /** Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. - parameter queue: Possibly concurrent dispatch queue used to perform work. - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. */ public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { // Swift 3.0 IUO let serialQueue = DispatchQueue(label: internalSerialQueueName, attributes: [], target: queue) self.init(serialQueue: serialQueue, leeway: leeway) } /** Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. - parameter qos: Identifier for global dispatch queue with specified quality of service class. - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. */ @available(iOS 8, OSX 10.10, *) public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) } /** Schedules an action to be executed immediatelly. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { return self.scheduleInternal(state, action: action) } func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { return self.configuration.schedule(state, action: action) } /** Schedules an action to be executed. - parameter state: State passed to the action to be executed. - parameter dueTime: Relative time after which to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) } /** Schedules a periodic piece of work. - parameter state: State passed to the action to be executed. - parameter startAfter: Period after which initial work should be run. - parameter period: Period for running the work periodically. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) } }
mit
ls1intum/ArTEMiS
src/main/resources/templates/swift/solution/Sources/${packageNameFolder}Lib/Client.swift
1
2302
import Foundation public class Client { /** Main method. Add code to demonstrate your implementation here. */ public static func main() { /// Init Context and Policy let sortingContext = Context() let policy = Policy(sortingContext) /// Run 10 times to simulate different sorting strategies for _ in 0 ..< 10 { let dates: [Date] = createRandomDatesList() sortingContext.setDates(dates) policy.configure() print("Unsorted Array of course dates = ") printDateList(dates) print() sortingContext.sort() print("Sorted Array of course dates = ") printDateList(sortingContext.getDates()) print() } } /// Generates an Array of random Date objects with random Array size between 5 and 15. private static func createRandomDatesList() -> [Date] { let listLength: Int = randomIntegerWithin(5, 15) var list = [Date]() let dateFormat = DateFormatter() dateFormat.dateFormat = "dd.MM.yyyy" dateFormat.timeZone = TimeZone(identifier: "UTC") let lowestDate: Date! = dateFormat.date(from: "08.11.2016") let highestDate: Date! = dateFormat.date(from: "15.04.2017") for _ in 0 ..< listLength { let randomDate: Date! = randomDateWithin(lowestDate, highestDate) list.append(randomDate) } return list } /// Creates a random Date within given Range private static func randomDateWithin(_ low: Date, _ high: Date) -> Date { let randomSeconds: Double = randomDoubleWithin(low.timeIntervalSince1970, high.timeIntervalSince1970) return Date(timeIntervalSince1970: randomSeconds) } /// Creates a random Double within given Range private static func randomDoubleWithin(_ low: Double, _ high: Double) -> Double { return Double.random(in: low...high) } /// Creates a random Integer within given Range private static func randomIntegerWithin(_ low: Int, _ high: Int) -> Int { return Int.random(in: low...high) } /// Prints out given Array of Date objects private static func printDateList(_ list: [Date]) { print(list) } }
mit
toashd/SwiftCenteredTabBar
SwiftCenteredTabBar/TSDCenterTabBarController.swift
1
2172
// // TSDCenteredTabBarController.swift // SwiftCenteredTabBar // // Created by Tobias Schmid on 03.06.14. // Copyright (c) 2014 toashd. All rights reserved. // import UIKit class TSDCenteredTabBarController: UITabBarController { var centerButton : UIButton! override func viewDidLoad() { super.viewDidLoad() var buttonImage = UIImage(named: "tabBarCameraCenter") var buttonImageActive = UIImage(named: "tabBarCameraCenterActive") self.addCenterButtonWithImage( buttonImage, highlightImage: buttonImageActive, target: self, action:Selector("buttonPressed:") ) } override func tabBar(tabBar: UITabBar!, didSelectItem item: UITabBarItem!) { if item == self.tabBar.items[self.tabBar.items.count / 2] as NSObject { centerButton.selected = true } else { centerButton.selected = false } } func addCenterButtonWithImage(buttonImage: UIImage, highlightImage: UIImage, target: AnyObject, action: Selector) { var button : UIButton! = UIButton.buttonWithType(UIButtonType.Custom) as UIButton button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height) button.setBackgroundImage(buttonImage, forState: UIControlState.Normal) button.setBackgroundImage(highlightImage, forState: UIControlState.Selected) button.setBackgroundImage(highlightImage, forState: UIControlState.Highlighted) var heightDifference = buttonImage.size.height - self.tabBar.frame.size.height if heightDifference < 0 { button.center = self.tabBar.center } else { var center = self.tabBar.center center.y = center.y - heightDifference / 2.0 button.center = center } button.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) self.centerButton = button } func buttonPressed(sender: AnyObject) { self.selectedIndex = self.tabBar.items.count / 2 centerButton.selected = true } }
mit
xshfsky/WeiBo
WeiBo/WeiBo/Classes/Discover/Controller/DiscoverTableViewController.swift
1
3576
// // DiscoverTableViewController.swift // WeiBo // // Created by Miller on 15/9/26. // Copyright © 2015年 Xie Yufeng. All rights reserved. // import UIKit class DiscoverTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !isLogin == true { if isLogin == false { visiterView?.setVisterViewInfo(false, imageNamed: "visitordiscover_image_message", title: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") return } return } // 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 numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // 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. } */ }
mit
Incipia/Goalie
Goalie/UIButton+Extensions.swift
1
737
// // UIButton+Extensions.swift // Goalie // // Created by Gregory Klein on 12/30/15. // Copyright © 2015 Incipia. All rights reserved. // import UIKit extension UIButton { func removeAllActionsForTarget(_ target: AnyObject) { let events = UIControlEvents.touchUpInside if let actions = actions(forTarget: target, forControlEvent: events) { for action in actions { removeTarget(target, action: Selector(stringLiteral: action), for: events) } } } func updateTarget(_ target: AnyObject, selectorName: String) { removeAllActionsForTarget(target) addTarget(target, action: Selector(stringLiteral: selectorName), for: UIControlEvents.touchUpInside) } }
apache-2.0
GagSquad/SwiftCommonUtil
CommonUtil/CommonUtil/CacheUtil.swift
1
970
// // CacheUtil.swift // CommonUtil // // Created by lijunjie on 15/12/4. // Copyright © 2015年 lijunjie. All rights reserved. // import Foundation public class CacheUtil { var cache: NSCache = NSCache() private static let share = CacheUtil() private init () {} public func shareCache() -> NSCache { return cache } public func systemMemoryCacheSet(key: NSCoding, value: AnyObject) { self.shareCache().setObject(value, forKey: key) } public func systemMemoryCacheRemove(key: AnyObject) { self.shareCache().removeObjectForKey(key) } public func systemMemoryCacheGetValue(key:AnyObject) -> AnyObject? { return self.shareCache().objectForKey(key) } public func systemMemoryCacheEmptyValue(key:AnyObject) -> Bool { return (self.systemMemoryCacheGetValue(key) == nil) } } public let SharedCacheUtil: CacheUtil = CacheUtil.share
gpl-2.0
tjw/swift
test/Runtime/demangleToMetadata.swift
1
10666
// RUN: %empty-directory(%t) // RUN: %target-build-swift -parse-stdlib %s -module-name main -o %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test import Swift import StdlibUnittest let DemangleToMetadataTests = TestSuite("DemangleToMetadata") DemangleToMetadataTests.test("malformed mangled names") { expectNil(_typeByMangledName("blah")) } DemangleToMetadataTests.test("tuple types") { expectEqual(type(of: ()), _typeByMangledName("yt")!) expectEqual(type(of: ((), ())), _typeByMangledName("yt_ytt")!) expectEqual(type(of: ((), b: ())), _typeByMangledName("yt_yt1bt")!) expectEqual(type(of: (a: (), ())), _typeByMangledName("yt1a_ytt")!) expectEqual(type(of: (a: (), b: ())), _typeByMangledName("yt1a_yt1bt")!) // Initial creation of metadata via demangling a type name. expectNotNil(_typeByMangledName("yt1a_yt3bcdt")) } func f0() { } var f0_thin: @convention(thin) () -> Void = f0 var f0_c: @convention(c) () -> Void = f0 #if _runtime(_ObjC) var f0_block: @convention(block) () -> Void = f0 #endif func f0_throws() throws { } func f1(x: ()) { } func f2(x: (), y: ()) { } func f1_variadic(x: ()...) { } func f1_inout(x: inout ()) { } func f1_shared(x: __shared AnyObject) { } func f1_owned(x: __owned AnyObject) { } func f2_variadic_inout(x: ()..., y: inout ()) { } DemangleToMetadataTests.test("function types") { // Conventions expectEqual(type(of: f0), _typeByMangledName("yyc")!) expectEqual(type(of: f0_thin), _typeByMangledName("yyXf")!) expectEqual(type(of: f0_c), _typeByMangledName("yyXC")!) #if _runtime(_ObjC) expectEqual(type(of: f0_block), _typeByMangledName("yyXB")!) #endif // Throwing functions expectEqual(type(of: f0_throws), _typeByMangledName("yyKc")!) // More parameters. expectEqual(type(of: f1), _typeByMangledName("yyyt_tc")!) expectEqual(type(of: f2), _typeByMangledName("yyyt_yttc")!) // Variadic parameters. expectEqual(type(of: f1_variadic), _typeByMangledName("yyytd_tc")!) // Inout parameters. expectEqual(type(of: f1_inout), _typeByMangledName("yyytzc")!) // Ownership parameters. expectEqual(type(of: f1_shared), _typeByMangledName("yyyXlhc")!) expectEqual(type(of: f1_owned), _typeByMangledName("yyyXlnc")!) // Mix-and-match. expectEqual(type(of: f2_variadic_inout), _typeByMangledName("yyytd_ytztc")!) // A function type that hasn't been built before. expectEqual("(Int, Float, Double, String, Character, UInt, Bool) -> ()", String(describing: _typeByMangledName("yySi_SfSdSSs9CharacterVSuSbtc")!)) } DemangleToMetadataTests.test("metatype types") { expectEqual(type(of: type(of: ())), _typeByMangledName("ytm")!) expectEqual(type(of: type(of: f0)), _typeByMangledName("yycm")!) } func f2_any_anyobject(_: Any, _: AnyObject) { } class C { } protocol P1 { } protocol P2 { } protocol P3 { } func f1_composition(_: P1 & P2) { } func f1_composition_anyobject(_: AnyObject & P1) { } func f1_composition_superclass(_: C & P1 & P2) { } DemangleToMetadataTests.test("existential types") { // Any, AnyObject expectEqual(type(of: f2_any_anyobject), _typeByMangledName("yyyp_yXltc")!) // References to protocols. expectEqual(type(of: f1_composition), _typeByMangledName("yy4main2P1_4main2P2pc")!) // Reference to protocol with AnyObject. expectEqual(type(of: f1_composition_anyobject), _typeByMangledName("yy4main2P1_Xlc")!) // References to superclass. expectEqual(type(of: f1_composition_superclass), _typeByMangledName("yy4main2P1_4main2P2AA1CCXcc")!) // Demangle an existential type that hasn't been seen before. expectEqual("P1 & P2 & P3", String(describing: _typeByMangledName("4main2P1_4main2P24main2P3p")!)) } DemangleToMetadataTests.test("existential metatype types") { // Any expectEqual(type(of: Any.self), _typeByMangledName("ypm")!) // AnyObject expectEqual(type(of: AnyObject.self), _typeByMangledName("yXlm")!) // References to metatype of protocols. expectEqual(type(of: (P1 & P2).self), _typeByMangledName("4main2P1_4main2P2pm")!) // References to metatype involving protocols and superclass. expectEqual(type(of: (C & P1 & P2).self), _typeByMangledName("4main2P1_4main2P2AA1CCXcm")!) } struct S { struct Nested { } } enum E { case e } DemangleToMetadataTests.test("nominal types") { // Simple Struct expectEqual(type(of: S()), _typeByMangledName("4main1SV")!) // Simple Enum expectEqual(type(of: E.e), _typeByMangledName("4main1EO")!) // Simple Class expectEqual(type(of: C()), _typeByMangledName("4main1CC")!) // Swift standard library types expectEqual(type(of: Int()), _typeByMangledName("Si")!) expectEqual(type(of: Int16()), _typeByMangledName("s5Int16V")!) // Nested struct expectEqual(type(of: S.Nested()), _typeByMangledName("4main1SV6NestedV")!) // Class referenced by "ModuleName.ClassName" syntax. expectEqual(type(of: C()), _typeByMangledName("main.C")!) } protocol P4 { associatedtype Assoc1 associatedtype Assoc2 } extension S: P4 { typealias Assoc1 = Int typealias Assoc2 = String } DemangleToMetadataTests.test("substitutions") { // Type parameter substitutions. expectEqual(type(of: (1, 3.14159, "Hello")), _typeByMangledName("yyx_q_qd__t", substitutions: [[Int.self, Double.self], [String.self]])!) // Associated type substitutions expectEqual(type(of: (S(), 1, "Hello")), _typeByMangledName("x_6Assoc14main2P4PQz6Assoc24main2P4PQzt", substitutions: [[S.self]])!) } enum EG<T, U> { case a } class CG3<T, U, V> { } DemangleToMetadataTests.test("simple generic specializations") { expectEqual([Int].self, _typeByMangledName("SaySiG")!) expectEqual(EG<Int, String>.self, _typeByMangledName("4main2EGOySiSSG")!) expectEqual(CG3<Int, Double, String>.self, _typeByMangledName("4main3CG3CySiSdSSG")!) } extension EG { struct NestedSG<V> { } } extension C { enum Nested<T, U> { case a struct Innermore { struct Innermost<V> { } } } } class CG2<T, U> { class Inner<V> { struct Innermost<W1, W2, W3, W4> { } } } DemangleToMetadataTests.test("nested generic specializations") { expectEqual(EG<Int, String>.NestedSG<Double>.self, _typeByMangledName("4main2EGO8NestedSGVySiSS_SdG")!) expectEqual(C.Nested<Int, String>.Innermore.Innermost<Double>.self, _typeByMangledName("4main1CC6NestedO9InnermoreV9InnermostVy_SiSS__SdG")!) expectEqual(CG2<Int, String>.Inner<Double>.self, _typeByMangledName("4main3CG2C5InnerCySiSS_SdG")!) expectEqual( CG2<Int, String>.Inner<Double>.Innermost<Int8, Int16, Int32, Int64>.self, _typeByMangledName("4main3CG2C5InnerC9InnermostVySiSS_Sd_s4Int8Vs5Int16Vs5Int32Vs5Int64VG")!) } DemangleToMetadataTests.test("demangle built-in types") { expectEqual(Builtin.Int8.self, _typeByMangledName("Bi8_")!) expectEqual(Builtin.Int16.self, _typeByMangledName("Bi16_")!) expectEqual(Builtin.Int32.self, _typeByMangledName("Bi32_")!) expectEqual(Builtin.Int64.self, _typeByMangledName("Bi64_")!) expectEqual(Builtin.Int128.self, _typeByMangledName("Bi128_")!) expectEqual(Builtin.Int256.self, _typeByMangledName("Bi256_")!) expectEqual(Builtin.Int512.self, _typeByMangledName("Bi512_")!) expectEqual(Builtin.NativeObject.self, _typeByMangledName("Bo")!) expectEqual(Builtin.BridgeObject.self, _typeByMangledName("Bb")!) expectEqual(Builtin.UnsafeValueBuffer.self, _typeByMangledName("BB")!) } class CG4<T: P1, U: P2> { struct InnerGeneric<V: P3> { } } struct ConformsToP1: P1 { } struct ConformsToP2: P2 { } struct ConformsToP3: P3 { } DemangleToMetadataTests.test("protocol conformance requirements") { expectEqual(CG4<ConformsToP1, ConformsToP2>.self, _typeByMangledName("4main3CG4CyAA12ConformsToP1VAA12ConformsToP2VG")!) expectEqual(CG4<ConformsToP1, ConformsToP2>.InnerGeneric<ConformsToP3>.self, _typeByMangledName("4main3CG4C12InnerGenericVyAA12ConformsToP1VAA12ConformsToP2V_AA12ConformsToP3VG")!) // Failure cases: failed conformance requirements. expectNil(_typeByMangledName("4main3CG4CyAA12ConformsToP1VAA12ConformsToP1VG")) expectNil(_typeByMangledName("4main3CG4CyAA12ConformsToP2VAA12ConformsToP2VG")) expectNil(_typeByMangledName("4main3CG4C12InnerGenericVyAA12ConformsToP1VAA12ConformsToP2V_AA12ConformsToP2VG")) } struct SG5<T: P4> where T.Assoc1: P1, T.Assoc2: P2 { } struct ConformsToP4a : P4 { typealias Assoc1 = ConformsToP1 typealias Assoc2 = ConformsToP2 } struct ConformsToP4b : P4 { typealias Assoc1 = ConformsToP1 typealias Assoc2 = ConformsToP1 } struct ConformsToP4c : P4 { typealias Assoc1 = ConformsToP2 typealias Assoc2 = ConformsToP2 } DemangleToMetadataTests.test("associated type conformance requirements") { expectEqual(SG5<ConformsToP4a>.self, _typeByMangledName("4main3SG5VyAA13ConformsToP4aVG")!) // Failure cases: failed conformance requirements. expectNil(_typeByMangledName("4main3SG5VyAA13ConformsToP4bVG")) expectNil(_typeByMangledName("4main3SG5VyAA13ConformsToP4cVG")) expectNil(_typeByMangledName("4main3SG5VyAA12ConformsToP1cVG")) } struct SG6<T: P4> where T.Assoc1 == T.Assoc2 { } struct SG7<T: P4> where T.Assoc1 == Int { } struct SG8<T: P4> where T.Assoc1 == [T.Assoc2] { } struct ConformsToP4d : P4 { typealias Assoc1 = [ConformsToP2] typealias Assoc2 = ConformsToP2 } DemangleToMetadataTests.test("same-type requirements") { // Concrete type. expectEqual(SG7<S>.self, _typeByMangledName("4main3SG7VyAA1SVG")!) // Other associated type. expectEqual(SG6<ConformsToP4b>.self, _typeByMangledName("4main3SG6VyAA13ConformsToP4bVG")!) expectEqual(SG6<ConformsToP4c>.self, _typeByMangledName("4main3SG6VyAA13ConformsToP4cVG")!) // Structural type. expectEqual(SG8<ConformsToP4d>.self, _typeByMangledName("4main3SG8VyAA13ConformsToP4dVG")!) // Failure cases: types don't match. expectNil(_typeByMangledName("4main3SG7VyAA13ConformsToP4aVG")) expectNil(_typeByMangledName("4main3SG6VyAA13ConformsToP4aVG")) expectNil(_typeByMangledName("4main3SG8VyAA13ConformsToP4cVG")) } struct SG9<T: AnyObject> { } DemangleToMetadataTests.test("AnyObject requirements") { expectEqual(SG9<C>.self, _typeByMangledName("4main3SG9VyAA1CCG")!) // Failure cases: failed AnyObject constraint. expectNil(_typeByMangledName("4main3SG9VyAA1SVG")) } struct SG10<T: C> { } class C2 : C { } class C3 { } DemangleToMetadataTests.test("superclass requirements") { expectEqual(SG10<C>.self, _typeByMangledName("4main4SG10VyAA1CCG")!) expectEqual(SG10<C2>.self, _typeByMangledName("4main4SG10VyAA2C2CG")!) // Failure cases: not a subclass. expectNil(_typeByMangledName("4main4SG10VyAA2C3CG")) } runAllTests()
apache-2.0
badoo/Chatto
ChattoAdditions/sources/Input/ChatInputBar.swift
1
12165
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 public protocol ChatInputBarDelegate: AnyObject { func inputBarShouldBeginTextEditing(_ inputBar: ChatInputBar) -> Bool func inputBarDidBeginEditing(_ inputBar: ChatInputBar) func inputBarDidEndEditing(_ inputBar: ChatInputBar) func inputBarDidChangeText(_ inputBar: ChatInputBar) func inputBarSendButtonPressed(_ inputBar: ChatInputBar) func inputBar(_ inputBar: ChatInputBar, shouldFocusOnItem item: ChatInputItemProtocol) -> Bool func inputBar(_ inputBar: ChatInputBar, didLoseFocusOnItem item: ChatInputItemProtocol) func inputBar(_ inputBar: ChatInputBar, didReceiveFocusOnItem item: ChatInputItemProtocol) func inputBarDidShowPlaceholder(_ inputBar: ChatInputBar) func inputBarDidHidePlaceholder(_ inputBar: ChatInputBar) } @objc open class ChatInputBar: ReusableXibView { public var pasteActionInterceptor: PasteActionInterceptor? { get { return self.textView.pasteActionInterceptor } set { self.textView.pasteActionInterceptor = newValue } } public weak var delegate: ChatInputBarDelegate? public weak var presenter: ChatInputBarPresenter? public var shouldEnableSendButton = { (inputBar: ChatInputBar) -> Bool in return !inputBar.textView.text.isEmpty } public var inputTextView: UITextView? { return self.textView } @IBOutlet weak var scrollView: HorizontalStackScrollView! @IBOutlet weak var textView: ExpandableTextView! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var topBorderHeightConstraint: NSLayoutConstraint! @IBOutlet var constraintsForHiddenTextView: [NSLayoutConstraint]! @IBOutlet var constraintsForVisibleTextView: [NSLayoutConstraint]! @IBOutlet var constraintsForVisibleSendButton: [NSLayoutConstraint]! @IBOutlet var constraintsForHiddenSendButton: [NSLayoutConstraint]! @IBOutlet var tabBarContainerHeightConstraint: NSLayoutConstraint! class open func loadNib() -> ChatInputBar { let view = Bundle.resources.loadNibNamed(self.nibName(), owner: nil, options: nil)!.first as! ChatInputBar view.translatesAutoresizingMaskIntoConstraints = false view.frame = CGRect.zero return view } override class func nibName() -> String { return "ChatInputBar" } open override func awakeFromNib() { super.awakeFromNib() self.topBorderHeightConstraint.constant = 1 / UIScreen.main.scale self.textView.scrollsToTop = false self.textView.delegate = self self.textView.placeholderDelegate = self self.scrollView.scrollsToTop = false self.sendButton.isEnabled = false } open override func updateConstraints() { if self.showsTextView { NSLayoutConstraint.activate(self.constraintsForVisibleTextView) NSLayoutConstraint.deactivate(self.constraintsForHiddenTextView) } else { NSLayoutConstraint.deactivate(self.constraintsForVisibleTextView) NSLayoutConstraint.activate(self.constraintsForHiddenTextView) } if self.showsSendButton { NSLayoutConstraint.deactivate(self.constraintsForHiddenSendButton) NSLayoutConstraint.activate(self.constraintsForVisibleSendButton) } else { NSLayoutConstraint.deactivate(self.constraintsForVisibleSendButton) NSLayoutConstraint.activate(self.constraintsForHiddenSendButton) } super.updateConstraints() } open var showsTextView: Bool = true { didSet { self.setNeedsUpdateConstraints() self.setNeedsLayout() self.updateIntrinsicContentSizeAnimated() } } open var showsSendButton: Bool = true { didSet { self.setNeedsUpdateConstraints() self.setNeedsLayout() self.updateIntrinsicContentSizeAnimated() } } public var maxCharactersCount: UInt? // nil -> unlimited private func updateIntrinsicContentSizeAnimated() { let options: UIView.AnimationOptions = [.beginFromCurrentState, .allowUserInteraction] UIView.animate(withDuration: 0.25, delay: 0, options: options, animations: { () -> Void in self.invalidateIntrinsicContentSize() self.layoutIfNeeded() }, completion: nil) } open override func layoutSubviews() { self.updateConstraints() // Interface rotation or size class changes will reset constraints as defined in interface builder -> constraintsForVisibleTextView will be activated super.layoutSubviews() } var inputItems = [ChatInputItemProtocol]() { didSet { let inputItemViews = self.inputItems.map { (item: ChatInputItemProtocol) -> ChatInputItemView in let inputItemView = ChatInputItemView() inputItemView.inputItem = item inputItemView.delegate = self return inputItemView } self.scrollView.addArrangedViews(inputItemViews) } } open func becomeFirstResponderWithInputView(_ inputView: UIView?) { self.textView.inputView = inputView if self.textView.isFirstResponder { self.textView.reloadInputViews() } else { self.textView.becomeFirstResponder() } } public var inputText: String { get { return self.textView.text } set { self.textView.text = newValue self.updateSendButton() } } public var inputSelectedRange: NSRange { get { return self.textView.selectedRange } set { self.textView.selectedRange = newValue } } public var placeholderText: String { get { return self.textView.placeholderText } set { self.textView.placeholderText = newValue } } fileprivate func updateSendButton() { self.sendButton.isEnabled = self.shouldEnableSendButton(self) } @IBAction func buttonTapped(_ sender: AnyObject) { self.presenter?.onSendButtonPressed() self.delegate?.inputBarSendButtonPressed(self) } public func setTextViewPlaceholderAccessibilityIdentifer(_ accessibilityIdentifer: String) { self.textView.setTextPlaceholderAccessibilityIdentifier(accessibilityIdentifer) } } // MARK: - ChatInputItemViewDelegate extension ChatInputBar: ChatInputItemViewDelegate { func inputItemViewTapped(_ view: ChatInputItemView) { self.focusOnInputItem(view.inputItem) } public func focusOnInputItem(_ inputItem: ChatInputItemProtocol) { let shouldFocus = self.delegate?.inputBar(self, shouldFocusOnItem: inputItem) ?? true guard shouldFocus else { return } let previousFocusedItem = self.presenter?.focusedItem self.presenter?.onDidReceiveFocusOnItem(inputItem) if let previousFocusedItem = previousFocusedItem { self.delegate?.inputBar(self, didLoseFocusOnItem: previousFocusedItem) } self.delegate?.inputBar(self, didReceiveFocusOnItem: inputItem) } } // MARK: - ChatInputBarAppearance extension ChatInputBar { public func setAppearance(_ appearance: ChatInputBarAppearance) { self.textView.font = appearance.textInputAppearance.font self.textView.textColor = appearance.textInputAppearance.textColor self.textView.tintColor = appearance.textInputAppearance.tintColor self.textView.textContainerInset = appearance.textInputAppearance.textInsets self.textView.setTextPlaceholderFont(appearance.textInputAppearance.placeholderFont) self.textView.setTextPlaceholderColor(appearance.textInputAppearance.placeholderColor) self.textView.placeholderText = appearance.textInputAppearance.placeholderText self.textView.layer.borderColor = appearance.textInputAppearance.borderColor.cgColor self.textView.layer.borderWidth = appearance.textInputAppearance.borderWidth self.textView.accessibilityIdentifier = appearance.textInputAppearance.accessibilityIdentifier self.tabBarInterItemSpacing = appearance.tabBarAppearance.interItemSpacing self.tabBarContentInsets = appearance.tabBarAppearance.contentInsets self.sendButton.contentEdgeInsets = appearance.sendButtonAppearance.insets self.sendButton.setTitle(appearance.sendButtonAppearance.title, for: .normal) appearance.sendButtonAppearance.titleColors.forEach { (state, color) in self.sendButton.setTitleColor(color, for: state.controlState) } self.sendButton.titleLabel?.font = appearance.sendButtonAppearance.font self.sendButton.accessibilityIdentifier = appearance.sendButtonAppearance.accessibilityIdentifier self.tabBarContainerHeightConstraint.constant = appearance.tabBarAppearance.height } } extension ChatInputBar { // Tabar public var tabBarInterItemSpacing: CGFloat { get { return self.scrollView.interItemSpacing } set { self.scrollView.interItemSpacing = newValue } } public var tabBarContentInsets: UIEdgeInsets { get { return self.scrollView.contentInset } set { self.scrollView.contentInset = newValue } } } // MARK: UITextViewDelegate extension ChatInputBar: UITextViewDelegate { public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return self.delegate?.inputBarShouldBeginTextEditing(self) ?? true } public func textViewDidEndEditing(_ textView: UITextView) { self.presenter?.onDidEndEditing() self.delegate?.inputBarDidEndEditing(self) } public func textViewDidBeginEditing(_ textView: UITextView) { self.presenter?.onDidBeginEditing() self.delegate?.inputBarDidBeginEditing(self) } public func textViewDidChange(_ textView: UITextView) { self.updateSendButton() self.delegate?.inputBarDidChangeText(self) } open func textView(_ textView: UITextView, shouldChangeTextIn nsRange: NSRange, replacementText text: String) -> Bool { guard let maxCharactersCount = self.maxCharactersCount else { return true } let currentText: NSString = textView.text as NSString let currentCount = currentText.length let rangeLength = nsRange.length let nextCount = currentCount - rangeLength + (text as NSString).length return UInt(nextCount) <= maxCharactersCount } } // MARK: ExpandableTextViewPlaceholderDelegate extension ChatInputBar: ExpandableTextViewPlaceholderDelegate { public func expandableTextViewDidShowPlaceholder(_ textView: ExpandableTextView) { self.delegate?.inputBarDidShowPlaceholder(self) } public func expandableTextViewDidHidePlaceholder(_ textView: ExpandableTextView) { self.delegate?.inputBarDidHidePlaceholder(self) } }
mit
jeremy-w/adian
AdianTests/WryTests.swift
1
1068
/* 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 XCTest @testable import Adian class SpyTask: Task { var command: [String] = [] var input = "" var environment: [String: String] = [:] var completion = {(output: String, ok: Bool) -> Void in } func run(completion: (output: String, ok: Bool) -> Void) { /* pass */ } } class WryTests: XCTestCase { let spyTask = SpyTask() var wry: Wry? override func setUp() { wry = Wry(task: spyTask) } func testPostMessageConfiguresTaskToSend() { wry!.postMessage(AnyMessage) XCTAssertEqual(spyTask.command, "/usr/local/bin/wry post".componentsSeparatedByString(" ")) XCTAssertEqual(spyTask.input, AnyMessage) XCTAssertTrue(spyTask.environment.contains { $0 == "WRY_EDITOR" && $1 == "STDIN" }, "environment missing WRY_EDITOR=STDIN: \(spyTask.environment)") } }
mpl-2.0
modnovolyk/MAVLinkSwift
Sources/TimesyncCommonMsg.swift
1
1024
// // TimesyncCommonMsg.swift // MAVLink Protocol Swift Library // // Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py // https://github.com/modnovolyk/MAVLinkSwift // import Foundation /// Time synchronization message. public struct Timesync { /// Time sync timestamp 1 public let tc1: Int64 /// Time sync timestamp 2 public let ts1: Int64 } extension Timesync: Message { public static let id = UInt8(111) public static var typeName = "TIMESYNC" public static var typeDescription = "Time synchronization message." public static var fieldDefinitions: [FieldDefinition] = [("tc1", 0, "Int64", 0, "Time sync timestamp 1"), ("ts1", 8, "Int64", 0, "Time sync timestamp 2")] public init(data: Data) throws { tc1 = try data.number(at: 0) ts1 = try data.number(at: 8) } public func pack() throws -> Data { var payload = Data(count: 16) try payload.set(tc1, at: 0) try payload.set(ts1, at: 8) return payload } }
mit
brocktonpoint/CawBoxKit
CawBoxKitTests/UserDataTests.swift
1
2715
/* The MIT License (MIT) Copyright (c) 2015 CawBox Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest @testable import CawBoxKit class UserDataTests: XCTestCase { func testUserData () { let stringKey = "string" let stringValue = "Here is some test string." let intKey = "int" let intValue = 12345 let doubleKey = "double" let doubleValue = 0.54321 UserData<AnyObject>.clearAll () XCTAssert (UserData<String>.get (forKey: stringKey) == nil, "String value should be blank. (\(UserData<String>.get (forKey: stringKey)))") XCTAssert (UserData<Int>.get (forKey: intKey) == nil, "Int value should be blank. (\(UserData<Int>.get (forKey: intKey)))") XCTAssert (UserData<Double>.get (forKey: doubleKey) == nil, "Double value should be blank. (\(UserData<Double>.get (forKey: doubleKey)))") UserData<AnyObject>.setDefaults (defaults: [ stringKey: stringValue, intKey: intValue, doubleKey: doubleValue ] ) XCTAssert (UserData<String>.get (forKey: stringKey) == stringValue, "String value incorrect.") XCTAssert (UserData<Int>.get (forKey: intKey) == intValue, "Int value incorrect.") XCTAssert (UserData<Double>.get (forKey: doubleKey) == doubleValue, "Double value incorrect.") UserData<AnyObject>.clear (keys: [stringKey]) XCTAssert (UserData<String>.get (forKey: stringKey) == nil, "String value should be blank.") UserData<AnyObject>.set (forKey: intKey, value: nil) XCTAssert (UserData<Int>.get (forKey: intKey) == nil, "Int value should be blank.") } }
mit
apple/swift
validation-test/compiler_crashers_fixed/00804-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
65
441
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct S<T where g: T>() func g<T> S<f = {
apache-2.0
anto0522/AdMate
AdMate/MainViewController.swift
1
57887
// // MainViewController.swift // AdMate // // Created by Antonin Linossier on 11/5/15. // Copyright © 2015 Antonin Linossier. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Cocoa import NotificationCenter import AdDataKit2 import AdMateOAuth import SQLite // MARK: - NSTableViewDataSource extension MainViewController: NSTableViewDataSource { func tableView(aTableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 63 } func numberOfRowsInTableView(aTableView: NSTableView) -> Int { if TodayDataToDisplay.count > 0 {return 7} else {return 0} } func tableView(aTableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeViewWithIdentifier("AdDataCell", owner: self) as! AdDataCell switch row { case 0: // EARNINGS cell.Caption.stringValue = "Earnings" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].EarningsVarImg!) cell.Value.stringValue = "\(TodayDataToDisplay[0].Earnings!)" + " " + CurrencySymbol cell.PrevValue.stringValue = TodayDataToDisplay[0].EarningsPrev! + " \(CurrencySymbol) Yesterday " + TodayDataToDisplay[0].EarningsVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].EarningsVarImg!) cell.Value.stringValue = "\(ThisWeekDataToDisplay[0].Earnings!)" + " " + CurrencySymbol cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].EarningsPrev! + " \(CurrencySymbol) Last Week " + ThisWeekDataToDisplay[0].EarningsVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].EarningsVarImg!) cell.Value.stringValue = "\(ThisMonthDataToDisplay[0].Earnings!)" + " " + CurrencySymbol cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].EarningsPrev! + " \(CurrencySymbol) Last Month " + ThisMonthDataToDisplay[0].EarningsVar! } case 1: // PAGE VIEWS cell.Caption.stringValue = "Page Views" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].PageViewsVarImg!) cell.Value.stringValue = "\(TodayDataToDisplay[0].PageViews!)" cell.PrevValue.stringValue = TodayDataToDisplay[0].PageViewsPrev! + " Yesterday " + TodayDataToDisplay[0].PageViewsVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].PageViewsVarImg!) cell.Value.stringValue = "\(ThisWeekDataToDisplay[0].PageViews!)" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].PageViewsPrev! + " Last Week " + ThisWeekDataToDisplay[0].PageViewsVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].PageViewsVarImg!) cell.Value.stringValue = "\(ThisMonthDataToDisplay[0].PageViews!)" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].PageViewsPrev! + " Last Month " + ThisMonthDataToDisplay[0].PageViewsVar! } case 2: // CLICKS cell.Caption.stringValue = "Clicks" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].AdClicksVarImg!) cell.Value.stringValue = "\(TodayDataToDisplay[0].AdClicks!)" cell.PrevValue.stringValue = TodayDataToDisplay[0].AdClicksPrev! + " Yesterday " + TodayDataToDisplay[0].AdClicksVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].AdClicksVarImg!) cell.Value.stringValue = "\(ThisWeekDataToDisplay[0].AdClicks!)" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].AdClicksPrev! + " Last Week " + ThisWeekDataToDisplay[0].AdClicksVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].AdClicksVarImg!) cell.Value.stringValue = "\(ThisMonthDataToDisplay[0].AdClicks!)" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].AdClicksPrev! + " Last Month " + ThisMonthDataToDisplay[0].AdClicksVar! } case 3: // PAGE RPM cell.Caption.stringValue = "Page RPM" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].PageViewRPMVarImg!) cell.Value.stringValue = (rounder(TodayDataToDisplay[0].PageViewRPM!) as String) + " \(CurrencySymbol)" cell.PrevValue.stringValue = TodayDataToDisplay[0].PageViewRPMPrev! + " \(CurrencySymbol) Yesterday " + TodayDataToDisplay[0].PageViewRPMVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].PageViewRPMVarImg!) cell.Value.stringValue = rounder(ThisWeekDataToDisplay[0].PageViewRPM!) + " \(CurrencySymbol)" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].PageViewRPMPrev! + " \(CurrencySymbol) Last Week " + ThisWeekDataToDisplay[0].PageViewRPMVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].PageViewRPMVarImg!) cell.Value.stringValue = rounder(ThisMonthDataToDisplay[0].PageViewRPM!) + " \(CurrencySymbol)" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].PageViewRPMPrev! + " \(CurrencySymbol) Last Month " + ThisMonthDataToDisplay[0].PageViewRPMVar! } case 4: // COVERAGE cell.Caption.stringValue = "Coverage" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].AdRequestCoverageVarImg!) cell.Value.stringValue = rounder(TodayDataToDisplay[0].AdRequestCoverage! * 100) + " %" cell.PrevValue.stringValue = TodayDataToDisplay[0].AdRequestCoveragePrev! + "% Yesterday " + TodayDataToDisplay[0].AdRequestCoverageVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].AdRequestCoverageVarImg!) cell.Value.stringValue = rounder(ThisWeekDataToDisplay[0].AdRequestCoverage! * 100) + " %" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].AdRequestCoveragePrev! + "% Last Week " + ThisWeekDataToDisplay[0].AdRequestCoverageVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].AdRequestCoverageVarImg!) cell.Value.stringValue = rounder(ThisMonthDataToDisplay[0].AdRequestCoverage! * 100) + " %" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].AdRequestCoveragePrev! + "% Last Month " + ThisMonthDataToDisplay[0].AdRequestCoverageVar! } // case 5: // PAGE CTR cell.Caption.stringValue = "Page CTR" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].AdRequestCTRVarImg!) cell.Value.stringValue = rounder(TodayDataToDisplay[0].AdRequestCTR! * 100) + " %" cell.PrevValue.stringValue = TodayDataToDisplay[0].AdRequestCTRPrev! + "% Yesterday " + TodayDataToDisplay[0].AdRequestCTRVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].AdRequestCTRVarImg!) cell.Value.stringValue = rounder(ThisWeekDataToDisplay[0].AdRequestCTR! * 100) + " %" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].AdRequestCTRPrev! + "% Last Week " + ThisWeekDataToDisplay[0].AdRequestCTRVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].AdRequestCTRVarImg!) cell.Value.stringValue = rounder(ThisMonthDataToDisplay[0].AdRequestCTR! * 100) + " %" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].AdRequestCTRPrev! + "% Last Month " + ThisMonthDataToDisplay[0].AdRequestCTRVar! } case 6: // COST PER CLICK cell.Caption.stringValue = "Cost per click" switch CurrentSelection { case .Today: cell.Indicator.image = NSImage(named: TodayDataToDisplay[0].AdCostPerClickVarImg!) cell.Value.stringValue = rounder(TodayDataToDisplay[0].AdCostPerClick!) + " \(CurrencySymbol)" cell.PrevValue.stringValue = TodayDataToDisplay[0].AdCostPerClickPrev! + " \(CurrencySymbol) Yesterday " + TodayDataToDisplay[0].AdCostPerClickVar! case .ThisWeek: cell.Indicator.image = NSImage(named: ThisWeekDataToDisplay[0].AdCostPerClickVarImg!) cell.Value.stringValue = rounder(ThisWeekDataToDisplay[0].AdCostPerClick!) + " \(CurrencySymbol)" cell.PrevValue.stringValue = ThisWeekDataToDisplay[0].AdCostPerClickPrev! + " \(CurrencySymbol) Last Week " + ThisWeekDataToDisplay[0].AdCostPerClickVar! case .ThisMonth: cell.Indicator.image = NSImage(named: ThisMonthDataToDisplay[0].AdCostPerClickVarImg!) cell.Value.stringValue = rounder(ThisMonthDataToDisplay[0].AdCostPerClick!) + " \(CurrencySymbol)" cell.PrevValue.stringValue = ThisMonthDataToDisplay[0].AdCostPerClickPrev! + " \(CurrencySymbol) Last Month " + ThisMonthDataToDisplay[0].AdCostPerClickVar! } default: print("Something else") } return cell } func tableViewSelectionDidChange(notification: NSNotification) { let myTableViewFromNotification = notification.object as! NSTableView let index = myTableViewFromNotification.selectedRow as Int switch index { case 0: CurrentRowSelected = .Earnings case 1: CurrentRowSelected = .PageViews case 2: CurrentRowSelected = .Clicks case 3: CurrentRowSelected = .PageRPM case 4: CurrentRowSelected = .Coverage case 5: CurrentRowSelected = .CTR case 6: CurrentRowSelected = .CostPerClick default: print("None Selected") CurrentRowSelected = .Earnings } LayoutSubViews() } func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { let myCustomView = MyRowView() return myCustomView } } // MARK: - NSTableViewDelegate extension MainViewController: NSTableViewDelegate { } class MainViewController: NSViewController { @IBOutlet var LineChartViewLayer: LineChartView! @IBOutlet var MainTitle: NSTextField! @IBOutlet var tableView: NSTableView! @IBOutlet var SegmentedControl: NSSegmentedControl! @IBOutlet var DailyAverageThisMonth: NSTextField! @IBOutlet var DailyAverageLastMonth: NSTextField! @IBOutlet var MaxThisMonth: NSTextField! @IBOutlet var MaxLastMonth: NSTextField! @IBOutlet var MinThisMonth: NSTextField! @IBOutlet var MinLastMonth: NSTextField! enum DataSetToShow { case Today case ThisWeek case ThisMonth } // Default enum values for the data to show the the window is loaded var CurrentSelection = DataSetToShow.Today var CurrentRowSelected = RowSelected.Earnings // Data from DB var DBDataToAnalyse = [AdData]() @IBOutlet var InfoButton: NSButton! let PopoverInfoState = Bool(false) let popover = NSPopover() // Array of structs to display data var TodayDataToDisplay = [ProcessedData]() var ThisWeekDataToDisplay = [ProcessedData]() var ThisMonthDataToDisplay = [ProcessedData]() // The currency symbol to be used var CurrencySymbol = String() @objc func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: NSEdgeInsets) -> NSEdgeInsets { return NSEdgeInsetsZero } override func viewDidLoad() { super.viewDidLoad() // Did load //Register custom cell let nib = NSNib(nibNamed: "AdDataCell", bundle: nil) tableView.registerNib(nib!, forIdentifier: "AdDataCell") self.view.window?.toolbar?.insertItemWithItemIdentifier("RefreshButton", atIndex: 1) self.view.window?.toolbar?.insertItemWithItemIdentifier("LoginButton", atIndex: 2) // self.view.window?.toolbar? NSNotificationCenter.defaultCenter().addObserver(self, selector: "LoadView:", name:"UserDidLogin", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "ReAuthUser:", name:"ReValidateUser", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "LoginButtonPressed:", name:"LoginPressed", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "ExportButtonPressed:", name:"ExportPressed", object: nil) LineChartViewLayer.lineChart.legendEnabled = false if !defaults.boolForKey("FirstTimeOpen"){ copyFile("AdMate.db") } if let UserID = defaults.objectForKey(UserIDDefault) { print("USER IDD VIEW DID LOAD \(UserID)") RefreshTheView() FetchTheData(UserID as! String) NSNotificationCenter.defaultCenter().removeObserver("UserDidLogin") } } func ExportButtonPressed(sender:AnyObject){ let calendar = NSCalendar.autoupdatingCurrentCalendar() let MyFormatter = NSDateFormatter() MyFormatter.dateFormat = "yyyy-MM-dd" let Date = calendar.dateByAddingUnit( [.Day], value: 0, toDate: NSDate(), options: [])! let formatedDate = MyFormatter.stringFromDate(Date) //Pick file location let saveDialog = NSSavePanel(); saveDialog.nameFieldStringValue = "AdMateData-" + formatedDate + ".csv" saveDialog.title = "Export your AdMate data" saveDialog.beginWithCompletionHandler() { (result: Int) -> Void in if result == NSFileHandlingPanelOKButton { GetDataFromDb(){ (result: [AdData]) in dispatch_async(dispatch_get_main_queue()) { // 2 if result.count > 60 { // Validates that we retrieve more than 60 lines let stringofdata = NSMutableString() stringofdata.appendString("AdMate Data exported on " + formatedDate + "\n, \n" ) stringofdata.appendString("Number of requests: The number of ad units that requested ads (for content ads) or search queries (for search ads). An ad request may result in zero or multiple individual ad impressions depending on the size of the ad unit and whether any ads were available. \n" ) stringofdata.appendString("Coverage: The ratio of requested ad units or queries to the number returned to the site. \n" ) stringofdata.appendString("CTR: The ratio of ad requests that resulted in a click. \n" ) stringofdata.appendString("RPM: The revenue per thousand ad requests. This is calculated by dividing estimated revenue by the number of ad requests multiplied by 1000. \n" ) stringofdata.appendString("Clicks: The number of times a user clicked on a standard content ad. \n" ) stringofdata.appendString("Cost per clisk: The amount you earn each time a user clicks on your ad. CPC is calculated by dividing the estimated revenue by the number of clicks received. \n" ) stringofdata.appendString("Earnings: The estimated earnings of the publisher. Note that earnings up to yesterday are accurate. More recent earnings are estimated due to the possibility of spam or exchange rate fluctuations. \n" ) stringofdata.appendString("Page views: The number of page views. \n" ) stringofdata.appendString("Matched ad requests: The number of ad units (for content ads) or search queries (for search ads) that showed ads. A matched ad request is counted for each ad request that returns at least one ad to the site. \n \n \n" ) stringofdata.appendString("Date, Number of requests, Coverage, CTR, RPM, Clicks, Cost per click, Earnings, Page views RPM, Page views, Matched ad requests \n") for i in 0...result.count - 1 { let DateAsString = MyFormatter.stringFromDate((result[i].Date)!) stringofdata.appendString(DateAsString + ", " + (result[i].AdRequest?.description)! + ", " + (result[i].AdRequestCoverage?.description)! + ", " + (result[i].AdRequestCTR?.description)! + ", " + (result[i].AdRequestRPM?.description)! + ", " + (result[i].AdClicks?.description)! + ", " + (result[i].AdCostPerClick?.description)! + ", " + (result[i].Earnings?.description)! + ", " + (result[i].PageViewRPM?.description)! + ", " + (result[i].PageViews?.description)! + ", " + (result[i].MatchedAdRequest?.description)! + "\n") } let data = stringofdata.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) if let content = data { NSFileManager.defaultManager() .createFileAtPath(saveDialog.URL!.path!, contents: content, attributes: nil) } } else { // DATA IS CORRUPTED ALERT MESSAGE print("DATA IS CORRUPTED ALERT MESSAGE") } } } print("File saved at: " + (saveDialog.URL?.absoluteString)!) } } } func LoginButtonPressed(sender: AnyObject){ print("The Login button was pressed") if let UserID = defaults.objectForKey(UserIDDefault) { print("USER IDD VIEW WILL APPEAR \(UserID)") let answer = self.dialogOKCancel("Logout", text: "Do you want to proceed and logout?") if answer { // Perform logout tasks here defaults.setObject(nil, forKey: UserIDDefault) defaults.synchronize() oauth2.forgetTokens() NSNotificationCenter.defaultCenter().postNotificationName("SetLogoutIcon", object: nil) self.performSegueWithIdentifier("GoToTutorial", sender: self) } }else { self.performSegueWithIdentifier("GoToTutorial", sender: self) } } func dialogOKCancel(question: String, text: String) -> Bool { let myPopup: NSAlert = NSAlert() myPopup.messageText = question myPopup.informativeText = text myPopup.alertStyle = NSAlertStyle.WarningAlertStyle myPopup.addButtonWithTitle("OK") myPopup.addButtonWithTitle("Cancel") let res = myPopup.runModal() if res == NSAlertFirstButtonReturn { return true } return false } @IBAction func ShowInfo(sender:AnyObject){ if popover.shown { popover.close() } else { popover.contentViewController = PopOverInfo.init(nibName: nil, bundle: nil) popover.contentViewController!.representedObject = nil popover.contentSize = NSSize(width: 130.0, height: 0.0) popover.showRelativeToRect(InfoButton.bounds, ofView: InfoButton, preferredEdge: NSRectEdge.MaxX) } } func FetchTheData(userID:String){ dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) { // 1 print("Fetching from API") FetchDataFromAPI(userID ){ (UpdateStatus:Bool) in if UpdateStatus { print("Getting data from db") self.RefreshTheView() } } } } func RefreshTheView(){ GetDataFromDb(){ (result: [AdData]) in dispatch_async(dispatch_get_main_queue()) { // 2 if result.count > 60 { // Not Ideal for people whose account is not 60days old yet if defaults.objectForKey("CCYSYMBOL") != nil { self.CurrencySymbol = defaults.objectForKey("CCYSYMBOL") as! String } else { self.CurrencySymbol = "$" } self.DBDataToAnalyse = result self.FormatTodayData(result) self.LayoutSubViews() // Create the chart NSNotificationCenter.defaultCenter().postNotificationName("SetLoginIcon", object: nil) } else { // DATA IS CORRUPTED ALERT MESSAGE print("DATA IS CORRUPTED ALERT MESSAGE") } } } } override func viewWillAppear() { self.view.window?.backgroundColor = NSColor.whiteColor() self.view.window?.titlebarAppearsTransparent = true if let UserID = defaults.objectForKey(UserIDDefault) { print("USER IDD VIEW WILL APPEAR \(UserID)") // For debugging // self.performSegueWithIdentifier("GoToTutorial", sender: self) }else { // The user is not loged in -> go to login screen self.performSegueWithIdentifier("GoToTutorial", sender: self) } } func ReAuthUser(sender:AnyObject) { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("GoToTutorial", sender: self) } } func LayoutSubViews(){ let FrontColor = NSColor(calibratedRed: 102/255, green: 178/255, blue: 255.0/255, alpha: 1.0).CGColor let BackColor = NSColor(calibratedRed: 204.0/255, green: 229.0/255, blue: 255.0/255, alpha: 1.0).CGColor let formatter = NSDateFormatter() formatter.dateFormat = "MMM dd" var DataSetEarningsOne = [CGFloat]() var DataSetEarningsTwo = [CGFloat]() var DataLabelArray = [String]() var DataLabelArrayTwo = [String]() let calendar = NSCalendar.autoupdatingCurrentCalendar() let ThisMonthStartDate = calendar.dateByAddingUnit( [.Day], value: -30, toDate: NSDate(), options: [])! let LastMonthStartDate = calendar.dateByAddingUnit( [.Day], value: -60, toDate: NSDate(), options: [])! var ThisMonth = DBDataToAnalyse.filter({ $0.Date != nil && ThisMonthStartDate.isLessThanDate($0.Date!) }) var LastMonth = DBDataToAnalyse.filter({ $0.Date != nil && ThisMonthStartDate.isGreaterThanDate($0.Date!) && LastMonthStartDate.isLessThanDate($0.Date!) }) ThisMonth = ThisMonth.sort({ $0.Date! < $1.Date! }) LastMonth = LastMonth.sort({ $0.Date! < $1.Date! }) switch CurrentRowSelected { case .Earnings: MainTitle.stringValue = "Earnings" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].Earnings { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].Earnings { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: CurrencySymbol) dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: CurrencySymbol) dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.Earnings!} let l = LastMonth.reduce(0) {$0 + $1.Earnings!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.Earnings < $1.Earnings } )?.Earnings{ MaxThisMonth.stringValue = "\(maxtm)" + " " + CurrencySymbol } if let maxlm = LastMonth.maxElement({ $0.Earnings < $1.Earnings } )?.Earnings{ MaxLastMonth.stringValue = "\(maxlm)" + " " + CurrencySymbol } if let mintm = ThisMonth.minElement({ $0.Earnings < $1.Earnings } )?.Earnings{ MinThisMonth.stringValue = "\(mintm)" + " " + CurrencySymbol } if let minlm = LastMonth.minElement({ $0.Earnings < $1.Earnings } )?.Earnings{ MinLastMonth.stringValue = "\(minlm)" + " " + CurrencySymbol } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(rounder(t / Float(c)) )" + " " + CurrencySymbol DailyAverageLastMonth.stringValue = "\(rounder(l / Float(d)) )" + " " + CurrencySymbol case .PageViews: MainTitle.stringValue = "Page Views" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].PageViews { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].PageViews { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: "") dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: "") dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.PageViews!} let l = LastMonth.reduce(0) {$0 + $1.PageViews!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.PageViews < $1.PageViews } )?.PageViews{ MaxThisMonth.stringValue = "\(maxtm)" } if let maxlm = LastMonth.maxElement({ $0.PageViews < $1.PageViews } )?.PageViews{ MaxLastMonth.stringValue = "\(maxlm)" } if let mintm = ThisMonth.minElement({ $0.PageViews < $1.PageViews } )?.PageViews{ MinThisMonth.stringValue = "\(mintm)" } if let minlm = LastMonth.minElement({ $0.PageViews < $1.PageViews } )?.PageViews{ MinLastMonth.stringValue = "\(minlm)" } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(rounder(Float(t) / Float(c)) )" DailyAverageLastMonth.stringValue = "\(rounder(Float(l) / Float(d)) )" case .Clicks: MainTitle.stringValue = "Clicks" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].AdClicks { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].AdClicks { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: "") dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: "") dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.AdClicks!} let l = LastMonth.reduce(0) {$0 + $1.AdClicks!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.AdClicks < $1.AdClicks } )?.AdClicks{ MaxThisMonth.stringValue = "\(maxtm)" } if let maxlm = LastMonth.maxElement({ $0.AdClicks < $1.AdClicks } )?.AdClicks{ MaxLastMonth.stringValue = "\(maxlm)" } if let mintm = ThisMonth.minElement({ $0.AdClicks < $1.AdClicks } )?.AdClicks{ MinThisMonth.stringValue = "\(mintm)" } if let minlm = LastMonth.minElement({ $0.AdClicks < $1.AdClicks } )?.AdClicks{ MinLastMonth.stringValue = "\(minlm)" } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(rounder(Float(t) / Float(c)) )" DailyAverageLastMonth.stringValue = "\(rounder(Float(l) / Float(d)) )" case .PageRPM: MainTitle.stringValue = "RPM" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].AdRequestRPM { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].AdRequestRPM { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: CurrencySymbol) dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: CurrencySymbol) dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.AdRequestRPM!} let l = LastMonth.reduce(0) {$0 + $1.AdRequestRPM!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.AdRequestRPM < $1.AdRequestRPM } )?.AdRequestRPM{ MaxThisMonth.stringValue = "\(maxtm)" + " " + CurrencySymbol } if let maxlm = LastMonth.maxElement({ $0.AdRequestRPM < $1.AdRequestRPM } )?.AdRequestRPM{ MaxLastMonth.stringValue = "\(maxlm)" + " " + CurrencySymbol } if let mintm = ThisMonth.minElement({ $0.AdRequestRPM < $1.AdRequestRPM } )?.AdRequestRPM{ MinThisMonth.stringValue = "\(mintm)" + " " + CurrencySymbol } if let minlm = LastMonth.minElement({ $0.AdRequestRPM < $1.AdRequestRPM } )?.AdRequestRPM{ MinLastMonth.stringValue = "\(minlm)" + " " + CurrencySymbol } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(rounder(t / Float(c)) )" + " " + CurrencySymbol DailyAverageLastMonth.stringValue = "\(rounder(l / Float(d)) )" + " " + CurrencySymbol case .Coverage: MainTitle.stringValue = "Coverage" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].AdRequestCoverage { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].AdRequestCoverage { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: "%") dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: "%") dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.AdRequestCoverage!} let l = LastMonth.reduce(0) {$0 + $1.AdRequestCoverage!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.AdRequestCoverage < $1.AdRequestCoverage } )?.AdRequestCoverage{ MaxThisMonth.stringValue = "\(ConvertPercentage(maxtm))" + " %" } if let maxlm = LastMonth.maxElement({ $0.AdRequestCoverage < $1.AdRequestCoverage } )?.AdRequestCoverage{ MaxLastMonth.stringValue = "\(ConvertPercentage(maxlm))" + " %" } if let mintm = ThisMonth.minElement({ $0.AdRequestCoverage < $1.AdRequestCoverage } )?.AdRequestCoverage{ MinThisMonth.stringValue = "\(ConvertPercentage(mintm))" + " %" } if let minlm = LastMonth.minElement({ $0.AdRequestCoverage < $1.AdRequestCoverage } )?.AdRequestCoverage{ MinLastMonth.stringValue = "\(ConvertPercentage(minlm))" + " %" } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(ConvertPercentage(Float(t) / Float(c)) )" + " %" DailyAverageLastMonth.stringValue = "\(ConvertPercentage(Float(l) / Float(d)) )" + " %" case .CTR: MainTitle.stringValue = "Click-through rate" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].AdRequestCTR { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].AdRequestCTR { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: "%") dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: "%") dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.AdRequestCTR!} let l = LastMonth.reduce(0) {$0 + $1.AdRequestCTR!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.AdRequestCTR < $1.AdRequestCTR } )?.AdRequestCTR{ MaxThisMonth.stringValue = "\(ConvertPercentage(maxtm))" + " %" } if let maxlm = LastMonth.maxElement({ $0.AdRequestCTR < $1.AdRequestCTR } )?.AdRequestCTR{ MaxLastMonth.stringValue = "\(ConvertPercentage(maxlm))" + " %" } if let mintm = ThisMonth.minElement({ $0.AdRequestCTR < $1.AdRequestCTR } )?.AdRequestCTR{ MinThisMonth.stringValue = "\(ConvertPercentage(mintm))" + " %" } if let minlm = LastMonth.minElement({ $0.AdRequestCTR < $1.AdRequestCTR } )?.AdRequestCTR{ MinLastMonth.stringValue = "\(ConvertPercentage(minlm))" + " %" } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(ConvertPercentage(Float(t) / Float(c)) )" + " %" DailyAverageLastMonth.stringValue = "\(ConvertPercentage(Float(l) / Float(d)) )" + " %" case .CostPerClick: MainTitle.stringValue = "Cost per click" for i in 0...ThisMonth.count - 1 { if let NumberToAppendSerie1 = ThisMonth[i].AdCostPerClick { // Dataset 1 DataSetEarningsOne.append(CGFloat(NumberToAppendSerie1)) DataLabelArray.append(formatter.stringFromDate(ThisMonth[i].Date!)) } if let NumberToAppendSerie2 = LastMonth[i].AdCostPerClick { // Dataset 2 DataSetEarningsTwo.append(CGFloat(NumberToAppendSerie2)) DataLabelArrayTwo.append(formatter.stringFromDate(LastMonth[i].Date!)) } } // Chart Dataset 1 let dataset1 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsOne, poplabelfrominit: DataLabelArray, indice: CurrencySymbol) dataset1.color = FrontColor dataset1.fillColor = nil dataset1.curve = .Bezier(0.3) // Chart Dataset 2 let dataset21 = LineChart.Dataset(label: "Data 1", data: DataSetEarningsTwo, poplabelfrominit: DataLabelArrayTwo, indice: CurrencySymbol) dataset21.color = BackColor dataset21.curve = .Bezier(0.3) dataset21.fillColor = nil // Clearing previous sets and adding new ones LineChartViewLayer.lineChart.datasets = [] LineChartViewLayer.lineChart.datasets += [dataset21, dataset1] // Convenience vars to calculare the average let t = ThisMonth.reduce(0) {$0 + $1.AdCostPerClick!} let l = LastMonth.reduce(0) {$0 + $1.AdCostPerClick!} let c = ThisMonth.count let d = LastMonth.count // Unwrap optionals and display values if let maxtm = ThisMonth.maxElement({ $0.AdCostPerClick < $1.AdCostPerClick } )?.AdCostPerClick{ MaxThisMonth.stringValue = "\(maxtm)" + " " + CurrencySymbol } if let maxlm = LastMonth.maxElement({ $0.AdCostPerClick < $1.AdCostPerClick } )?.AdCostPerClick{ MaxLastMonth.stringValue = "\(maxlm)" + " " + CurrencySymbol } if let mintm = ThisMonth.minElement({ $0.AdCostPerClick < $1.AdCostPerClick } )?.AdCostPerClick{ MinThisMonth.stringValue = "\(mintm)" + " " + CurrencySymbol } if let minlm = LastMonth.minElement({ $0.AdCostPerClick < $1.AdCostPerClick } )?.AdCostPerClick{ MinLastMonth.stringValue = "\(minlm)" + " " + CurrencySymbol } // No need to unwrap optionals here DailyAverageThisMonth.stringValue = "\(rounder(t / Float(c)) )" + " " + CurrencySymbol DailyAverageLastMonth.stringValue = "\(rounder(l / Float(d)) )" + " " + CurrencySymbol } } func FormatTodayData(RawDataFromDb: [AdData]){ // HERE CHANGE TO MAX DATE IN ARRAY - 1 TO FIND YESTERDAY AND TODAY let calendar = NSCalendar.autoupdatingCurrentCalendar() let TodayData = RawDataFromDb.filter({ $0.Date != nil && calendar.isDateInToday($0.Date!) }) print(TodayData) if TodayData.count == 0 { let TodayData = RawDataFromDb.filter({ $0.Date != nil && calendar.isDateInYesterday($0.Date!) }) let TwoDaysAgo = calendar.dateByAddingUnit( [.Day], value: -2, toDate: NSDate(), options: [])! let YesterdayData = RawDataFromDb.filter({ $0.Date != nil && calendar.isDate($0.Date!, inSameDayAsDate: TwoDaysAgo) }) // Here crash array index out of range TodayDataToDisplay.append(ProcessedData(AdRequest: TodayData[0].AdRequest!, AdRequestCoverage: TodayData[0].AdRequestCoverage!, AdRequestCTR: TodayData[0].AdRequestCTR!, AdRequestRPM: TodayData[0].AdRequestRPM!, AdClicks: TodayData[0].AdClicks!, AdCostPerClick: TodayData[0].AdCostPerClick!, Earnings: TodayData[0].Earnings!, PageViews: TodayData[0].PageViews!, PageViewRPM: TodayData[0].PageViewRPM!, MatchedAdRequest: TodayData[0].MatchedAdRequest!, AdRequestPrev: YesterdayData[0].AdRequest!, AdRequestCoveragePrev: YesterdayData[0].AdRequestCoverage!, AdRequestCTRPrev: YesterdayData[0].AdRequestCTR!, AdRequestRPMPrev: YesterdayData[0].AdRequestRPM!, AdClicksPrev: YesterdayData[0].AdClicks!, AdCostPerClickPrev: YesterdayData[0].AdCostPerClick!, EarningsPrev: YesterdayData[0].Earnings!, PageViewsPrev: YesterdayData[0].PageViews!, PageViewRPMPrev: YesterdayData[0].PageViewRPM!, MatchedAdRequestPrev: YesterdayData[0].MatchedAdRequest!)) } else { let YesterdayData = RawDataFromDb.filter({ $0.Date != nil && calendar.isDateInYesterday($0.Date!) }) TodayDataToDisplay.append(ProcessedData(AdRequest: TodayData[0].AdRequest!, AdRequestCoverage: TodayData[0].AdRequestCoverage!, AdRequestCTR: TodayData[0].AdRequestCTR!, AdRequestRPM: TodayData[0].AdRequestRPM!, AdClicks: TodayData[0].AdClicks!, AdCostPerClick: TodayData[0].AdCostPerClick!, Earnings: TodayData[0].Earnings!, PageViews: TodayData[0].PageViews!, PageViewRPM: TodayData[0].PageViewRPM!, MatchedAdRequest: TodayData[0].MatchedAdRequest!, AdRequestPrev: YesterdayData[0].AdRequest!, AdRequestCoveragePrev: YesterdayData[0].AdRequestCoverage!, AdRequestCTRPrev: YesterdayData[0].AdRequestCTR!, AdRequestRPMPrev: YesterdayData[0].AdRequestRPM!, AdClicksPrev: YesterdayData[0].AdClicks!, AdCostPerClickPrev: YesterdayData[0].AdCostPerClick!, EarningsPrev: YesterdayData[0].Earnings!, PageViewsPrev: YesterdayData[0].PageViews!, PageViewRPMPrev: YesterdayData[0].PageViewRPM!, MatchedAdRequestPrev: YesterdayData[0].MatchedAdRequest!)) } let ThisMonthStartDate = calendar.dateByAddingUnit( [.Day], value: -30, toDate: NSDate(), options: [])! let LastMonthStartDate = calendar.dateByAddingUnit( [.Day], value: -60, toDate: NSDate(), options: [])! let ThisWeekStartDate = calendar.dateByAddingUnit( [.Day], value: -7, toDate: NSDate(), options: [])! let LastWeekStartDate = calendar.dateByAddingUnit( [.Day], value: -14, toDate: NSDate(), options: [])! let ThisMonth = RawDataFromDb.filter({ $0.Date != nil && ThisMonthStartDate.isLessThanDate($0.Date!) }) let LastMonth = RawDataFromDb.filter({ $0.Date != nil && ThisMonthStartDate.isGreaterThanDate($0.Date!) && LastMonthStartDate.isLessThanDate($0.Date!) }) let ThisWeek = RawDataFromDb.filter({ $0.Date != nil && ThisWeekStartDate.isLessThanDate($0.Date!) }) let LastWeek = RawDataFromDb.filter({ $0.Date != nil && ThisWeekStartDate.isGreaterThanDate($0.Date!) && LastWeekStartDate.isLessThanDate($0.Date!) }) let Temp1 = MultiplyStruct(ThisWeek, TheStructsTwo: LastWeek) let Temp2 = MultiplyStruct(ThisMonth, TheStructsTwo: LastMonth) ThisWeekDataToDisplay.append(Temp1[0]) ThisMonthDataToDisplay.append(Temp2[0]) self.tableView.reloadData() self.preferredContentSize = CGSizeMake(CGFloat(0), CGFloat((tableView.bounds.height)) + CGFloat(30)) } func MultiplyStruct(TheStructs: [AdData], TheStructsTwo: [AdData])->[ProcessedData]{ var AdRequestADD = Int(0) var AdRequestCoverageADD = Float(0) var AdRequestCTRADD = Float(0) var AdRequestRPMADD = Float(0) var AdClicksADD = Int(0) var AdCostPerClickADD = Float(0) var EarningsADD = Float(0) var PageViewsADD = Int(0) var PageViewRPMADD = Float(0) var MatchedAdRequestADD = Int(0) for i in 0...TheStructs.count - 1 { AdRequestADD = AdRequestADD + TheStructs[i].AdRequest! AdRequestCoverageADD = AdRequestCoverageADD + TheStructs[i].AdRequestCoverage! AdRequestCTRADD = AdRequestCTRADD + TheStructs[i].AdRequestCTR! AdRequestRPMADD = AdRequestRPMADD + TheStructs[i].AdRequestRPM! AdClicksADD = AdClicksADD + TheStructs[i].AdClicks! AdCostPerClickADD = AdCostPerClickADD + TheStructs[i].AdCostPerClick! EarningsADD = EarningsADD + TheStructs[i].Earnings! PageViewsADD = PageViewsADD + TheStructs[i].PageViews! PageViewRPMADD = PageViewRPMADD + TheStructs[i].PageViewRPM! MatchedAdRequestADD = MatchedAdRequestADD + TheStructs[i].MatchedAdRequest! } var AdRequestADDTWO = Int(0) var AdRequestCoverageADDTWO = Float(0) var AdRequestCTRADDTWO = Float(0) var AdRequestRPMADDTWO = Float() var AdClicksADDTWO = Int(0) var AdCostPerClickADDTWO = Float(0) var EarningsADDTWO = Float(0) var PageViewsADDTWO = Int(0) var PageViewRPMADDTWO = Float(0) var MatchedAdRequestADDTWO = Int(0) for i in 0...TheStructsTwo.count - 1 { AdRequestADDTWO = AdRequestADDTWO + TheStructsTwo[i].AdRequest! AdRequestCoverageADDTWO = AdRequestCoverageADDTWO + TheStructsTwo[i].AdRequestCoverage! AdRequestCTRADDTWO = AdRequestCTRADDTWO + TheStructsTwo[i].AdRequestCTR! AdRequestRPMADDTWO = AdRequestRPMADDTWO + TheStructsTwo[i].AdRequestRPM! AdClicksADDTWO = AdClicksADDTWO + TheStructsTwo[i].AdClicks! AdCostPerClickADDTWO = AdCostPerClickADDTWO + TheStructsTwo[i].AdCostPerClick! EarningsADDTWO = EarningsADDTWO + TheStructsTwo[i].Earnings! PageViewsADDTWO = PageViewsADDTWO + TheStructsTwo[i].PageViews! PageViewRPMADDTWO = PageViewRPMADDTWO + TheStructsTwo[i].PageViewRPM! MatchedAdRequestADDTWO = MatchedAdRequestADDTWO + TheStructsTwo[i].MatchedAdRequest! } var ArrayOfStruct = [ProcessedData]() ArrayOfStruct.append(ProcessedData.init(AdRequest: AdRequestADD, AdRequestCoverage: (AdRequestCoverageADD / Float(TheStructs.count)), AdRequestCTR: (AdRequestCTRADD / Float(TheStructs.count)), AdRequestRPM: (AdRequestRPMADD / Float(TheStructs.count)), AdClicks: AdClicksADD, AdCostPerClick: (AdCostPerClickADD / Float(TheStructs.count)), Earnings: EarningsADD, PageViews: PageViewsADD, PageViewRPM: (PageViewRPMADD / Float(TheStructs.count)), MatchedAdRequest: MatchedAdRequestADD, AdRequestPrev: AdRequestADDTWO, AdRequestCoveragePrev: (AdRequestCoverageADDTWO / Float(TheStructsTwo.count)), AdRequestCTRPrev: (AdRequestCTRADDTWO / Float(TheStructsTwo.count)), AdRequestRPMPrev: (AdRequestRPMADDTWO / Float(TheStructsTwo.count)), AdClicksPrev: AdClicksADDTWO, AdCostPerClickPrev: (AdCostPerClickADDTWO / Float(TheStructsTwo.count)), EarningsPrev: EarningsADDTWO, PageViewsPrev: PageViewsADDTWO, PageViewRPMPrev: (PageViewRPMADDTWO / Float(TheStructsTwo.count)), MatchedAdRequestPrev: MatchedAdRequestADDTWO)) return ArrayOfStruct } @IBAction func indexChanged(sender:NSSegmentedControl) { switch SegmentedControl.selectedSegment { case 0: CurrentSelection = DataSetToShow.Today case 1: CurrentSelection = DataSetToShow.ThisWeek case 2: CurrentSelection = DataSetToShow.ThisMonth default: break; } tableView.reloadData() } override func awakeFromNib() { if self.view.layer != nil { let color : CGColorRef = CGColorCreateGenericRGB(250, 250, 250, 250) self.view.layer?.backgroundColor = color } self.view.window?.title = "AdMate" } func LoadView(sender:AnyObject) { print("LoadView") if let UserID = defaults.objectForKey(UserIDDefault) { FetchTheData(UserID as! String) // NSNotificationCenter.defaultCenter().removeObserver("UserDidLogin") } // NSNotificationCenter.defaultCenter().removeObserver("UserDidLogin") } }
mit
tmd2013/iOSDesignPatternSwift
zerenlian/zerenlian/main.swift
1
1147
// // main.swift // zerenlian // // Created by ffwang on 2017/6/9. // Copyright © 2017年 ffwang. All rights reserved. // import Foundation func test1() { let handler1 = FF_ConcreteHandler1() let handler2 = FF_ConcreteHandler2() handler1.nextHandler = handler2 handler1.handleRequest(obj: "FF_ConcreteHandler2") } func test2() { let handler1 = FF_AbsConcreteHandler1() let handler2 = FF_AbsConcreteHandler2() let handler3 = FF_AbsConcreteHandler3() handler1.nextHandler = handler2 handler2.nextHandler = handler3 // let request1 = FF_ConcreteRequest1(obj: "哈哈") let request2 = FF_ConcreteRequest2(obj: "呵呵") // let request3 = FF_ConcreteRequest3(obj: "嘿嘿") handler1.handleRequest(request: request2) } func test3(){ let handler1 = FF_GroupLeader() let handler2 = FF_ManagerLeader() let handler3 = FF_Boss() handler1.nextLeader = handler2 handler2.nextLeader = handler3 let expenseAccount = FF_ExpenseAccount(title: "蛤", money: 99999, body: "车费") handler1.handleExpense(expense: expenseAccount) } test3()
apache-2.0
hooman/swift
test/Concurrency/Inputs/OtherActors.swift
4
162
public class SomeClass { } public actor OtherModuleActor { public let a: Int = 1 public nonisolated let b: Int = 2 public let c: SomeClass = SomeClass() }
apache-2.0
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Errors/Sources/V3Errors/Errors/CPError+CodableError.swift
1
2521
// // Created by Jeffrey Bergier on 2022/08/05. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 Umbrella extension CPError { public var codableValue: CodableError { let data: Data? switch self { case .accountStatus(let status): data = try? PropertyListEncoder().encode(status.rawValue) case .sync(let error): // TODO: Enhance to save suberror kind NSLog(String(describing: error)) data = nil } return CodableError(domain: type(of: self).errorDomain, code: self.errorCode, arbitraryData: data) } public init?(codableError: CodableError) { guard type(of: self).errorDomain == codableError.errorDomain else { return nil } switch codableError.errorCode { case 1001: let status: CPAccountStatus = { guard let data = codableError.arbitraryData, let rawValue = try? PropertyListDecoder().decode(Int.self, from: data), let status = CPAccountStatus(rawValue: rawValue) else { return .couldNotDetermine } return status }() self = .accountStatus(status) case 1002: self = .sync(nil) default: return nil } } }
mit
vector-im/vector-ios
RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationRooms/Coordinator/SpaceCreationRoomsCoordinatorParameters.swift
1
866
// File created from SimpleUserProfileExample // $ createScreen.sh Spaces/SpaceCreation/SpaceCreationRooms SpaceCreationRooms // // Copyright 2021 New Vector Ltd // // 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 struct SpaceCreationRoomsCoordinatorParameters { let session: MXSession let creationParams: SpaceCreationParameters }
apache-2.0
pksprojects/ElasticSwift
Tests/ElasticSwiftCoreTests/ElasticSwiftCoreTests.swift
1
10605
// // ElasticSwiftCoreTests.swift // ElasticSwiftCoreTests // // // Created by Prafull Kumar Soni on 2/11/20. // import Logging import UnitTestSettings import XCTest @testable import ElasticSwiftCore @testable import NIOHTTP1 class ElasticSwiftCoreTests: XCTestCase { let logger = Logger(label: "org.pksprojects.ElasticSwiftCoreTests.ElasticSwiftCoreTests", factory: logFactory) override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. super.setUp() XCTAssert(isLoggingConfigured) logger.info("====================TEST=START===============================") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() logger.info("====================TEST=END===============================") } func test_01_httpRequestBuilder() throws { let e = expectation(description: "execution complete") XCTAssertNoThrow(try HTTPRequestBuilder().set(method: .GET).set(path: "path").build(), "Should not throw") e.fulfill() waitForExpectations(timeout: 10) } func test_02_httpRequestBuilder() throws { let e = expectation(description: "execution complete") XCTAssertNoThrow( try HTTPRequestBuilder() .set(method: .GET) .set(path: "path") .set(body: "Hello Wordl!".data(using: .utf8)!) .set(version: HTTPVersion(major: 2, minor: 0)) .set(headers: ["header1": "headerVal"]) .build(), "Should not throw" ) e.fulfill() waitForExpectations(timeout: 10) } func test_03_httpRequestBuilder_fail() throws { let e = expectation(description: "execution complete") XCTAssertThrowsError(try HTTPRequestBuilder().set(path: "path").build(), "Should not throw") { error in logger.info("Expected Error: \(error)") if let error = error as? HTTPRequestBuilderError { switch error { case let .missingRequiredField(field): XCTAssertEqual("method", field) e.fulfill() default: XCTFail("UnExpectedError: \(error)") } } } waitForExpectations(timeout: 10) } func test_04_httpRequestBuilder_fail_2() throws { let e = expectation(description: "execution complete") XCTAssertThrowsError(try HTTPRequestBuilder().set(method: .GET).build(), "Should not throw") { error in logger.info("Expected Error: \(error)") if let error = error as? HTTPRequestBuilderError { switch error { case let .missingRequiredField(field): XCTAssertEqual("path", field) e.fulfill() default: XCTFail("UnExpectedError: \(error)") } } } waitForExpectations(timeout: 10) } func test_05_httpRequest() throws { let request = try HTTPRequestBuilder() .set(method: .GET) .set(path: "path") .build() XCTAssertEqual(request.path, request.pathWitQuery) } func test_05_httpRequest_queryPath() throws { let request = try HTTPRequestBuilder() .set(method: .GET) .set(path: "path") .set(queryParams: [.init(name: "test", value: "testVal")]) .build() XCTAssertEqual("path", request.path) XCTAssertEqual("?test=testVal", request.query) XCTAssertNotEqual(request.path, request.pathWitQuery) XCTAssertEqual("path?test=testVal", request.pathWitQuery) } func test_06_httpResponseBuilder_fail() throws { let e = expectation(description: "execution complete") let request = HTTPRequest(path: "path", method: .GET) XCTAssertThrowsError(try HTTPResponseBuilder().set(request: request).set(status: .accepted).build(), "Should not throw") { error in logger.info("Expected Error: \(error)") if let error = error as? HTTPResponseBuilderError { switch error { case let .missingRequiredField(field): XCTAssertEqual("headers", field) e.fulfill() default: XCTFail("UnExpectedError: \(error)") } } } waitForExpectations(timeout: 10) } func test_07_httpResponseBuilder_fail_2() throws { let e = expectation(description: "execution complete") let request = HTTPRequest(path: "path", method: .GET) XCTAssertThrowsError(try HTTPResponseBuilder().set(request: request).set(headers: .init()).build(), "Should not throw") { error in logger.info("Expected Error: \(error)") if let error = error as? HTTPResponseBuilderError { switch error { case let .missingRequiredField(field): XCTAssertEqual("status", field) e.fulfill() default: XCTFail("UnExpectedError: \(error)") } } } waitForExpectations(timeout: 10) } func test_08_httpResponseBuilder_fail_3() throws { let e = expectation(description: "execution complete") XCTAssertThrowsError(try HTTPResponseBuilder().set(headers: .init()).set(status: .accepted).build(), "Should not throw") { error in logger.info("Expected Error: \(error)") if let error = error as? HTTPResponseBuilderError { switch error { case let .missingRequiredField(field): XCTAssertEqual("request", field) e.fulfill() default: XCTFail("UnExpectedError: \(error)") } } } waitForExpectations(timeout: 10) } func test_09_httpResponseBuilder() throws { let e = expectation(description: "execution complete") let request = HTTPRequest(path: "path", method: .GET) XCTAssertNoThrow(try HTTPResponseBuilder() .set(request: request) .set(status: .ok) .set(headers: ["Content-Type": "text/plain"]) .set(body: "Hello World!".data(using: .utf8)!) .build(), "Should not throw") e.fulfill() waitForExpectations(timeout: 10) } func test_10_HTTPResponseStatus_extension_test() throws { XCTAssertTrue(HTTPResponseStatus.ok.is2xxSuccessful()) XCTAssertTrue(HTTPResponseStatus.processing.is1xxInformational()) XCTAssertTrue(HTTPResponseStatus.seeOther.is3xxRedirection()) XCTAssertTrue(HTTPResponseStatus.unauthorized.is4xxClientError()) XCTAssertTrue(HTTPResponseStatus.internalServerError.is5xxServerError()) XCTAssertTrue(HTTPResponseStatus.badGateway.isError()) XCTAssertTrue(HTTPResponseStatus.badRequest.isError()) } func test_11_dynamic_coding_keys() throws { let data = "{ \"1\": \"Test\"}".data(using: .utf8)! let test = try JSONDecoder().decode(Test.self, from: data) XCTAssertTrue(test.str == "Test") } func test_12_dynamic_coding_keys() throws { let key = DynamicCodingKeys(stringValue: "test") XCTAssertNotNil(key) XCTAssertNil(key?.intValue) XCTAssertEqual("test", key?.stringValue) } func test_13_query_type() throws { let queryType1 = MyQueryType.query1 let queryType2 = MyTestQueryType.random1 XCTAssertFalse(queryType1.isEqualTo(queryType2)) XCTAssertTrue(queryType2.isEqualTo(MyTestQueryType.random1)) XCTAssertNil(MyTestQueryType("NOT VALUE")) } func test_14_query() throws { let query1 = MyTestQuery() let query2 = MyTestQuery2() XCTAssertFalse(query1.isEqualTo(query2)) XCTAssertTrue(query2.isEqualTo(query2)) } } struct Test { let str: String } extension Test: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) str = try container.decode(String.self, forKey: .key(indexed: 1)) } } enum MyQueryType: String, QueryType { case query1 case query2 var metaType: Query.Type { return MyTestQuery.self } } enum MyTestQueryType: String, QueryType { case random1 case random2 var metaType: Query.Type { return MyTestQuery.self } } struct MyTestQuery: Query, Equatable { static func == (lhs: MyTestQuery, rhs: MyTestQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.boost == rhs.boost && lhs.name == rhs.name } var queryType: QueryType = MyTestQueryType.random1 var boost: Decimal? var name: String? func toDic() -> [String: Any] { return [:] } init() {} func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(queryType.name, forKey: .queryType) } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(String.self, forKey: .queryType) queryType = MyTestQueryType(type)! } enum CodingKeys: String, CodingKey { case queryType } } struct MyTestQuery2: Query, Equatable { static func == (lhs: MyTestQuery2, rhs: MyTestQuery2) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.boost == rhs.boost && lhs.name == rhs.name } var queryType: QueryType = MyQueryType.query2 var boost: Decimal? var name: String? init() {} func toDic() -> [String: Any] { return [:] } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(queryType.name, forKey: .queryType) } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(String.self, forKey: .queryType) queryType = MyQueryType(type)! } enum CodingKeys: String, CodingKey { case queryType } }
mit
vector-im/vector-ios
Riot/Modules/KeyVerification/Device/SelfVerifyStart/KeyVerificationSelfVerifyStartViewModelType.swift
1
1741
// File created from ScreenTemplate // $ createScreen.sh KeyVerification KeyVerificationSelfVerifyStart /* Copyright 2020 New Vector Ltd 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 protocol KeyVerificationSelfVerifyStartViewModelViewDelegate: AnyObject { func keyVerificationSelfVerifyStartViewModel(_ viewModel: KeyVerificationSelfVerifyStartViewModelType, didUpdateViewState viewSate: KeyVerificationSelfVerifyStartViewState) } protocol KeyVerificationSelfVerifyStartViewModelCoordinatorDelegate: AnyObject { func keyVerificationSelfVerifyStartViewModel(_ viewModel: KeyVerificationSelfVerifyStartViewModelType, otherDidAcceptRequest request: MXKeyVerificationRequest) func keyVerificationSelfVerifyStartViewModelDidCancel(_ viewModel: KeyVerificationSelfVerifyStartViewModelType) } /// Protocol describing the view model used by `KeyVerificationSelfVerifyStartViewController` protocol KeyVerificationSelfVerifyStartViewModelType { var viewDelegate: KeyVerificationSelfVerifyStartViewModelViewDelegate? { get set } var coordinatorDelegate: KeyVerificationSelfVerifyStartViewModelCoordinatorDelegate? { get set } func process(viewAction: KeyVerificationSelfVerifyStartViewAction) }
apache-2.0
LawrenceHan/iOS-project-playground
Swift_A_Big_Nerd_Ranch_Guide/MonsterTown/MonsterTown/Monster.swift
2
424
// // Monster.swift // MonsterTown // // Created by Hanguang on 3/1/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation class Monster { var town: Town? var name = "Monster" func terrorizeTown() { if town != nil { print("\(name) is terrorizing a town!") } else { print("\(name) hasn't found a town to terrorize yet...") } } }
mit
dongjiahao/Gomoku
五子棋UITests/___UITests.swift
1
1239
// // ___UITests.swift // 五子棋UITests // // Created by 董嘉豪 on 2017/2/12. // Copyright © 2017年 董嘉豪. All rights reserved. // import XCTest class ___UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
dvor/Antidote
Antidote/NotificationCoordinator.swift
1
14199
// 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 private enum NotificationType { case newMessage(OCTMessageAbstract) case friendRequest(OCTFriendRequest) } private struct Constants { static let NotificationVisibleDuration = 3.0 } protocol NotificationCoordinatorDelegate: class { func notificationCoordinator(_ coordinator: NotificationCoordinator, showChat chat: OCTChat) func notificationCoordinatorShowFriendRequest(_ coordinator: NotificationCoordinator, showRequest request: OCTFriendRequest) func notificationCoordinatorAnswerIncomingCall(_ coordinator: NotificationCoordinator, userInfo: String) func notificationCoordinator(_ coordinator: NotificationCoordinator, updateFriendsBadge badge: Int) func notificationCoordinator(_ coordinator: NotificationCoordinator, updateChatsBadge badge: Int) } class NotificationCoordinator: NSObject { weak var delegate: NotificationCoordinatorDelegate? fileprivate let theme: Theme fileprivate let userDefaults = UserDefaultsManager() fileprivate let notificationWindow: NotificationWindow fileprivate weak var submanagerObjects: OCTSubmanagerObjects! fileprivate var messagesToken: RLMNotificationToken? fileprivate var chats: Results<OCTChat> fileprivate var chatsToken: RLMNotificationToken? fileprivate var requests: Results<OCTFriendRequest> fileprivate var requestsToken: RLMNotificationToken? fileprivate let avatarManager: AvatarManager fileprivate let audioPlayer = AlertAudioPlayer() fileprivate var notificationQueue = [NotificationType]() fileprivate var inAppNotificationAppIdsRegistered = [String: Bool]() fileprivate var bannedChatIdentifiers = Set<String>() init(theme: Theme, submanagerObjects: OCTSubmanagerObjects) { self.theme = theme self.notificationWindow = NotificationWindow(theme: theme) self.submanagerObjects = submanagerObjects self.avatarManager = AvatarManager(theme: theme) let predicate = NSPredicate(format: "lastMessage.dateInterval > lastReadDateInterval") self.chats = submanagerObjects.chats(predicate: predicate) self.requests = submanagerObjects.friendRequests() super.init() addNotificationBlocks() NotificationCenter.default.addObserver(self, selector: #selector(NotificationCoordinator.applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } deinit { NotificationCenter.default.removeObserver(self) messagesToken?.stop() chatsToken?.stop() requestsToken?.stop() } /** Show or hide connnecting view. */ func toggleConnectingView(show: Bool, animated: Bool) { notificationWindow.showConnectingView(show, animated: animated) } /** Stops showing notifications for given chat. Also removes all related to that chat notifications from queue. */ func banNotificationsForChat(_ chat: OCTChat) { bannedChatIdentifiers.insert(chat.uniqueIdentifier) notificationQueue = notificationQueue.filter { switch $0 { case .newMessage(let messageAbstract): return messageAbstract.chatUniqueIdentifier != chat.uniqueIdentifier case .friendRequest: return true } } LNNotificationCenter.default().clearPendingNotifications(forApplicationIdentifier: chat.uniqueIdentifier); } /** Unban notifications for given chat (if they were banned before). */ func unbanNotificationsForChat(_ chat: OCTChat) { bannedChatIdentifiers.remove(chat.uniqueIdentifier) } func handleLocalNotification(_ notification: UILocalNotification) { guard let userInfo = notification.userInfo as? [String: String] else { return } guard let action = NotificationAction(dictionary: userInfo) else { return } performAction(action) } func showCallNotificationWithCaller(_ caller: String, userInfo: String) { let object = NotificationObject( title: caller, body: String(localized: "notification_is_calling"), action: .answerIncomingCall(userInfo: userInfo), soundName: "isotoxin_Ringtone.aac") showLocalNotificationObject(object) } func registerInAppNotificationAppId(_ appId: String) { if inAppNotificationAppIdsRegistered[appId] == nil { LNNotificationCenter.default().registerApplication(withIdentifier: appId, name: Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String, icon: UIImage(named: "notification-app-icon"), defaultSettings: LNNotificationAppSettings.default()) inAppNotificationAppIdsRegistered[appId] = true } } } extension NotificationCoordinator: CoordinatorProtocol { func startWithOptions(_ options: CoordinatorOptions?) { let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) let application = UIApplication.shared application.registerUserNotificationSettings(settings) application.cancelAllLocalNotifications() updateBadges() } } // MARK: Notifications extension NotificationCoordinator { func applicationDidBecomeActive() { UIApplication.shared.cancelAllLocalNotifications() } } private extension NotificationCoordinator { func addNotificationBlocks() { let messages = submanagerObjects.messages().sortedResultsUsingProperty("dateInterval", ascending: false) messagesToken = messages.addNotificationBlock { [unowned self] change in switch change { case .initial: break case .update(let messages, _, let insertions, _): guard let messages = messages else { break } if insertions.contains(0) { let message = messages[0] self.playSoundForMessageIfNeeded(message) if self.shouldEnqueueMessage(message) { self.enqueueNotification(.newMessage(message)) } } case .error(let error): fatalError("\(error)") } } chatsToken = chats.addNotificationBlock { [unowned self] change in switch change { case .initial: break case .update: self.updateBadges() case .error(let error): fatalError("\(error)") } } requestsToken = requests.addNotificationBlock { [unowned self] change in switch change { case .initial: break case .update(let requests, _, let insertions, _): guard let requests = requests else { break } for index in insertions { let request = requests[index] self.audioPlayer.playSound(.NewMessage) self.enqueueNotification(.friendRequest(request)) } self.updateBadges() case .error(let error): fatalError("\(error)") } } } func playSoundForMessageIfNeeded(_ message: OCTMessageAbstract) { if message.isOutgoing() { return } if message.messageText != nil || message.messageFile != nil { audioPlayer.playSound(.NewMessage) } } func shouldEnqueueMessage(_ message: OCTMessageAbstract) -> Bool { if message.isOutgoing() { return false } if UIApplication.isActive && bannedChatIdentifiers.contains(message.chatUniqueIdentifier) { return false } if message.messageText != nil || message.messageFile != nil { return true } return false } func enqueueNotification(_ notification: NotificationType) { notificationQueue.append(notification) showNextNotification() } func showNextNotification() { if notificationQueue.isEmpty { return } let notification = notificationQueue.removeFirst() let object = notificationObjectFromNotification(notification) if UIApplication.isActive { switch notification { case .newMessage(let messageAbstract): showInAppNotificationObject(object, chatUniqueIdentifier: messageAbstract.chatUniqueIdentifier) default: showInAppNotificationObject(object, chatUniqueIdentifier: nil) } } else { showLocalNotificationObject(object) } } func showInAppNotificationObject(_ object: NotificationObject, chatUniqueIdentifier: String?) { var appId:String if chatUniqueIdentifier != nil { appId = chatUniqueIdentifier! } else { appId = Bundle.main.bundleIdentifier! } registerInAppNotificationAppId(appId); let notification = LNNotification.init(message: object.body, title: object.title) notification?.defaultAction = LNNotificationAction.init(title: nil, handler: { [weak self] _ in self?.performAction(object.action) }) LNNotificationCenter.default().present(notification, forApplicationIdentifier: appId) showNextNotification() } func showLocalNotificationObject(_ object: NotificationObject) { let local = UILocalNotification() local.alertBody = "\(object.title): \(object.body)" local.userInfo = object.action.archive() local.soundName = object.soundName UIApplication.shared.presentLocalNotificationNow(local) showNextNotification() } func notificationObjectFromNotification(_ notification: NotificationType) -> NotificationObject { switch notification { case .friendRequest(let request): return notificationObjectFromRequest(request) case .newMessage(let message): return notificationObjectFromMessage(message) } } func notificationObjectFromRequest(_ request: OCTFriendRequest) -> NotificationObject { let title = String(localized: "notification_incoming_contact_request") let body = request.message ?? "" let action = NotificationAction.openRequest(requestUniqueIdentifier: request.uniqueIdentifier) return NotificationObject(title: title, body: body, action: action, soundName: "isotoxin_NewMessage.aac") } func notificationObjectFromMessage(_ message: OCTMessageAbstract) -> NotificationObject { let title: String if let friend = submanagerObjects.object(withUniqueIdentifier: message.senderUniqueIdentifier, for: .friend) as? OCTFriend { title = friend.nickname } else { title = "" } var body: String = "" let action = NotificationAction.openChat(chatUniqueIdentifier: message.chatUniqueIdentifier) if let messageText = message.messageText { let defaultString = String(localized: "notification_new_message") if userDefaults.showNotificationPreview { body = messageText.text ?? defaultString } else { body = defaultString } } else if let messageFile = message.messageFile { let defaultString = String(localized: "notification_incoming_file") if userDefaults.showNotificationPreview { body = messageFile.fileName ?? defaultString } else { body = defaultString } } return NotificationObject(title: title, body: body, action: action, soundName: "isotoxin_NewMessage.aac") } func performAction(_ action: NotificationAction) { switch action { case .openChat(let identifier): guard let chat = submanagerObjects.object(withUniqueIdentifier: identifier, for: .chat) as? OCTChat else { return } delegate?.notificationCoordinator(self, showChat: chat) banNotificationsForChat(chat) case .openRequest(let identifier): guard let request = submanagerObjects.object(withUniqueIdentifier: identifier, for: .friendRequest) as? OCTFriendRequest else { return } delegate?.notificationCoordinatorShowFriendRequest(self, showRequest: request) case .answerIncomingCall(let userInfo): delegate?.notificationCoordinatorAnswerIncomingCall(self, userInfo: userInfo) } } func updateBadges() { let chatsCount = chats.count let requestsCount = requests.count delegate?.notificationCoordinator(self, updateChatsBadge: chatsCount) delegate?.notificationCoordinator(self, updateFriendsBadge: requestsCount) UIApplication.shared.applicationIconBadgeNumber = chatsCount + requestsCount } // func chatsBadge() -> Int { // // TODO update to new Realm and filter unread chats with predicate "lastMessage.dateInterval > lastReadDateInterval" // var badge = 0 // for index in 0..<chats.count { // guard let chat = chats[index] as? OCTChat else { // continue // } // if chat.hasUnreadMessages() { // badge += 1 // } // } // return badge // } }
mit
MiezelKat/AWSense
AWSenseWatchTest/AWSenseWatchTest WatchKit Extension/ConfigurationInterfaceController.swift
1
2465
// // ConfigurationInterfaceController.swift // AWSenseWatchTest // // Created by Katrin Hansel on 18/02/2017. // Copyright © 2017 QMUL. All rights reserved. // import WatchKit import Foundation import AWSenseWatch import AWSenseShared class ConfigurationInterfaceController: WKInterfaceController { @IBOutlet var accelerometerSwitch: WKInterfaceSwitch! @IBOutlet var deviceMotionSwitch: WKInterfaceSwitch! @IBOutlet var heartRateSwitch: WKInterfaceSwitch! var accelerometerSensingOn = false var deviceMotionSensingOn = false var heartRateSensingOn = false @IBOutlet var startSensingButton: WKInterfaceButton! override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. let manager = AWSSensorManager.sharedInstance accelerometerSwitch.setEnabled(manager.isSensorAvailable(sensor: .accelerometer)) deviceMotionSwitch.setEnabled(manager.isSensorAvailable(sensor: .device_motion)) heartRateSwitch.setEnabled(manager.isSensorAvailable(sensor: .heart_rate)) startSensingButton.setEnabled(false) } @IBAction func accelerometerStateChanged(_ value: Bool) { accelerometerSensingOn = value evaluateStartButtonState() } @IBAction func deviceMotionStateChanged(_ value: Bool) { deviceMotionSensingOn = value evaluateStartButtonState() } @IBAction func heartRateStateChanged(_ value: Bool) { heartRateSensingOn = value evaluateStartButtonState() } func evaluateStartButtonState(){ startSensingButton.setEnabled(accelerometerSensingOn || deviceMotionSensingOn || heartRateSensingOn) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func startSensingButtonAction() { self.pushController(withName: "sensingIC", context: [AWSSensorType.accelerometer: accelerometerSensingOn, AWSSensorType.heart_rate: heartRateSensingOn, AWSSensorType.device_motion: deviceMotionSensingOn ] ) } }
mit
joeytat/Eww
Eww/Classes/Extensions/Constraint+Extension.swift
1
448
// // Constraint+Extension.swift // Tea // // Created by Max on 01/05/2017. // Copyright © 2017 Miaomi. All rights reserved. // import Foundation import UIKit public extension NSLayoutConstraint { @IBInspectable public var usePixels: Bool { get { return false // default Value } set { if newValue { constant = constant / UIScreen.main.scale } } } }
mit
jbennett/Bugology
SRCoreTests/SRCoreTests.swift
1
963
// // SRCoreTests.swift // SRCoreTests // // Created by Jonathan Bennett on 2016-01-30. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import XCTest @testable import SRCore class SRCoreTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
JohnSansoucie/MyProject2
BlueCap/Beacon/BeaconsViewController.swift
1
3850
// // BeaconsViewController.swift // BlueCap // // Created by Troy Stribling on 9/13/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import BlueCapKit class BeaconsViewController: UITableViewController { var beaconRegion : BeaconRegion? struct MainStoryBoard { static let beaconCell = "BeaconCell" } required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let beaconRegion = self.beaconRegion { self.navigationItem.title = beaconRegion.identifier NSNotificationCenter.defaultCenter().addObserver(self, selector:"updateBeacons", name:BlueCapNotification.didUpdateBeacon, object:beaconRegion) } else { self.navigationItem.title = "Beacons" } NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender: AnyObject!) { } func updateBeacons() { Logger.debug("BeaconRegionsViewController#updateBeacons") self.tableView.reloadData() } func sortBeacons(b1:Beacon, b2:Beacon) -> Bool { if b1.major > b2.major { return true } else if b1.major == b2.major && b1.minor > b2.minor { return true } else { return false } } func didResignActive() { Logger.debug("BeaconRegionsViewController#didResignActive") self.navigationController?.popToRootViewControllerAnimated(false) } func didBecomeActive() { Logger.debug("BeaconRegionsViewController#didBecomeActive") } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let beaconRegion = self.beaconRegion { return beaconRegion.beacons.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryBoard.beaconCell, forIndexPath: indexPath) as BeaconCell if let beaconRegion = self.beaconRegion { let beacon = sorted(beaconRegion.beacons, self.sortBeacons)[indexPath.row] if let uuid = beacon.proximityUUID { cell.proximityUUIDLabel.text = uuid.UUIDString } else { cell.proximityUUIDLabel.text = "Unknown" } if let major = beacon.major { cell.majorLabel.text = "\(major)" } else { cell.majorLabel.text = "Unknown" } if let minor = beacon.minor { cell.minorLabel.text = "\(minor)" } else { cell.minorLabel.text = "Unknown" } cell.proximityLabel.text = beacon.proximity.stringValue cell.rssiLabel.text = "\(beacon.rssi)" let accuracy = NSString(format:"%.4f", beacon.accuracy) cell.accuracyLabel.text = "\(accuracy)m" } return cell } }
mit
crazypoo/PTools
Pods/PermissionsKit/Sources/LocationAlwaysPermission/LocationAlwaysHandler.swift
1
2565
// The MIT License (MIT) // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if PERMISSIONSKIT_SPM import PermissionsKit import LocationExtension #endif #if os(iOS) && PERMISSIONSKIT_LOCATION_ALWAYS import Foundation import MapKit class LocationAlwaysHandler: NSObject, CLLocationManagerDelegate { // MARK: - Location Manager lazy var locationManager = CLLocationManager() func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .notDetermined { return } completionHandler() } // MARK: - Process var completionHandler: () -> Void = {} func requestPermission(_ completionHandler: @escaping () -> Void) { self.completionHandler = completionHandler let status = CLLocationManager.authorizationStatus() switch status { case .notDetermined: locationManager.delegate = self locationManager.requestAlwaysAuthorization() case .authorizedWhenInUse: locationManager.delegate = self locationManager.requestAlwaysAuthorization() default: self.completionHandler() } } // MARK: - Init static var shared: LocationAlwaysHandler? override init() { super.init() } deinit { locationManager.delegate = nil } } #endif
mit
material-motion/motion-transitioning-objc
examples/supplemental/Layout.swift
4
1025
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit func center(_ view: UIView, within containerView: UIView) -> UIView { let x = (containerView.bounds.width - view.bounds.width) / 2 let y = (containerView.bounds.height - view.bounds.height) / 2 view.frame = .init(origin: .init(x: x, y: y), size: view.bounds.size) view.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleLeftMargin] return view }
apache-2.0
wei18810109052/CWWeChat
CWWeChat/ChatModule/CWChatKit/Message/Layout/CWMessageViewLayout.swift
2
9756
// // CWMessageViewLayout.swift // CWWeChat // // Created by chenwei on 2017/7/14. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import YYText protocol CWMessageViewLayoutDelegate: NSObjectProtocol { func collectionView(_ collectionView: UICollectionView, itemAt indexPath: IndexPath) -> CWMessageModel } /** 使用collectionView 不太熟悉 待完善 */ class CWMessageViewLayout: UICollectionViewFlowLayout { weak var delegate: CWMessageViewLayoutDelegate? var setting = CWMessageLayoutSettings.share var needLayout: Bool = true var contentHeight = CGFloat() var cache = [IndexPath: CWMessageLayoutAttributes]() var visibleLayoutAttributes = [CWMessageLayoutAttributes]() override public class var layoutAttributesClass: AnyClass { return CWMessageLayoutAttributes.self } override public var collectionViewContentSize: CGSize { return CGSize(width: collectionViewWidth, height: contentHeight) } fileprivate var collectionViewHeight: CGFloat { return collectionView!.frame.height } fileprivate var collectionViewWidth: CGFloat { return collectionView!.frame.width } private var contentOffset: CGPoint { return collectionView!.contentOffset } } extension CWMessageViewLayout { func prepareCache() { cache.removeAll(keepingCapacity: true) } override func prepare() { guard let collectionView = collectionView, let delegate = self.delegate, needLayout == true else { return } prepareCache() needLayout = false contentHeight = 0 // 计算布局 let section = 0 for item in 0 ..< collectionView.numberOfItems(inSection: section) { let cellIndexPath = IndexPath(item: item, section: section) let attributes = CWMessageLayoutAttributes(forCellWith: cellIndexPath) configure(attributes: attributes) // cell 高度 let heightOfCell = attributes.messageContainerFrame.height + kMessageCellBottomMargin + kMessageCellTopMargin attributes.frame = CGRect(x: 0, y: contentHeight, width: kScreenWidth, height: heightOfCell) contentHeight = attributes.frame.maxY cache[cellIndexPath] = attributes } } private func configure(attributes: CWMessageLayoutAttributes) { guard let collectionView = collectionView, let message = delegate?.collectionView(collectionView, itemAt: attributes.indexPath) else { return } attributes.avaterFrame = avatarFrame(with: message) setupUsernameFrame(with: attributes, message: message) setupContainerFrame(with: attributes, message: message) setupStateFrame(with: attributes, message: message) } // 头像 func avatarFrame(with message: CWMessageModel) -> CGRect { let size: CGSize = setting.kAvaterSize let origin: CGPoint if message.isSend { origin = CGPoint(x: collectionViewWidth - setting.kMessageToLeftPadding - size.width, y: setting.kMessageToTopPadding) } else { origin = CGPoint(x: setting.kMessageToLeftPadding, y: setting.kMessageToTopPadding) } return CGRect(origin: origin, size: size) } // 昵称(如果有昵称,则昵称和头像y一样) func setupUsernameFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) { var size: CGSize = setting.kUsernameSize let origin: CGPoint if message.showUsername == false { size = CGSize.zero } if message.isSend { origin = CGPoint(x: attributes.avaterFrame.minX - setting.kUsernameLeftPadding - size.width, y: attributes.avaterFrame.minY) } else { origin = CGPoint(x: attributes.avaterFrame.maxX + setting.kUsernameLeftPadding, y: attributes.avaterFrame.minY) } attributes.usernameFrame = CGRect(origin: origin, size: size) } func setupContainerFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) { // 如果是文字 var contentSize: CGSize = CGSize.zero switch message.messageType { case .text: let content = (message.messageBody as! CWTextMessageBody).text let size = CGSize(width: kChatTextMaxWidth, height: CGFloat.greatestFiniteMagnitude) var edge: UIEdgeInsets if message.isSend { edge = ChatCellUI.right_edge_insets } else { edge = ChatCellUI.left_edge_insets } let modifier = CWTextLinePositionModifier(font: setting.contentTextFont) // YYTextContainer let textContainer = YYTextContainer(size: size) textContainer.linePositionModifier = modifier textContainer.maximumNumberOfRows = 0 let textFont = setting.contentTextFont let textAttributes = [NSAttributedStringKey.font: textFont, NSAttributedStringKey.foregroundColor: UIColor.black] let textAttri = CWChatTextParser.parseText(content, attributes: textAttributes)! let textLayout = YYTextLayout(container: textContainer, text: textAttri)! contentSize = CGSize(width: textLayout.textBoundingSize.width+edge.left+edge.right, height: textLayout.textBoundingSize.height+edge.top+edge.bottom) message.textLayout = textLayout case .image: let imageSize = (message.messageBody as! CWImageMessageBody).size //根据图片的比例大小计算图片的frame if imageSize.width > imageSize.height { var height = kChatImageMaxWidth * imageSize.height / imageSize.width height = max(kChatImageMinWidth, height) contentSize = CGSize(width: ceil(kChatImageMaxWidth), height: ceil(height)) } else { var width = kChatImageMaxWidth * imageSize.width / imageSize.height width = max(kChatImageMinWidth, width) contentSize = CGSize(width: ceil(width), height: ceil(kChatImageMaxWidth)) } let edge = UIEdgeInsets.zero contentSize = CGSize(width: contentSize.width+edge.left+edge.right, height: contentSize.height+edge.top+edge.bottom) case .voice: let voiceMessage = message.messageBody as! CWVoiceMessageBody var scale: CGFloat = CGFloat(voiceMessage.voiceLength)/60.0 if scale > 1 { scale = 1 } contentSize = CGSize(width: ceil(scale*kChatVoiceMaxWidth)+70, height: setting.kAvaterSize.height+13) case .emoticon: contentSize = CGSize(width: 120, height: 120) case .location: contentSize = CGSize(width: 250, height: 150) default: break } let origin: CGPoint if message.isSend { origin = CGPoint(x: attributes.avaterFrame.minX - setting.kUsernameLeftPadding - contentSize.width, y: attributes.usernameFrame.minY) } else { origin = CGPoint(x: attributes.avaterFrame.maxX + setting.kUsernameLeftPadding, y: attributes.usernameFrame.minY) } attributes.messageContainerFrame = CGRect(origin: origin, size: contentSize) } func setupStateFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) { let containerFrame = attributes.messageContainerFrame let origin: CGPoint if message.isSend { origin = CGPoint(x: containerFrame.minX - 2 - setting.errorSize.width, y: containerFrame.midY - 10) } else { origin = CGPoint(x: containerFrame.minX + 2 + setting.errorSize.width, y: containerFrame.midY - 10) } attributes.errorFrame = CGRect(origin: origin, size: setting.errorSize) attributes.activityFrame = CGRect(origin: origin, size: setting.errorSize) } // 所有cell 布局 override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cache[indexPath] } //3 override public func layoutAttributesForElements( in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { visibleLayoutAttributes.removeAll(keepingCapacity: true) for (_, attributes) in cache where attributes.frame.intersects(rect) { visibleLayoutAttributes.append(attributes) } return visibleLayoutAttributes } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) if context.invalidateDataSourceCounts { needLayout = true } } }
mit
warnerbros/cpe-manifest-ios-data
Source/TheTake/TheTakeAPIUtil.swift
1
6278
// // TheTakeAPIUtil.swift // import Foundation public class TheTakeAPIUtil: APIUtil, ProductAPIUtil { public static var APIDomain = "https://thetake.p.mashape.com" public static var APINamespace = "thetake.com" private struct Headers { static let APIKey = "X-Mashape-Key" static let Accept = "Accept" static let AcceptValue = "application/json" } public var featureAPIID: String? public var productCategories: [ProductCategory]? private var frameTimes = [Double: NSDictionary]() private var _frameTimeKeys = [Double]() open var frameTimeKeys: [Double] { if _frameTimeKeys.count == 0 { _frameTimeKeys = frameTimes.keys.sorted() } return _frameTimeKeys } public convenience init(apiKey: String, featureAPIID: String? = nil) { self.init(apiDomain: TheTakeAPIUtil.APIDomain) self.featureAPIID = featureAPIID self.customHeaders[Headers.APIKey] = apiKey self.customHeaders[Headers.Accept] = Headers.AcceptValue } open func closestFrameTime(_ timeInSeconds: Double) -> Double { let timeInMilliseconds = timeInSeconds * 1000 var closestFrameTime = -1.0 if frameTimes.count > 0 && frameTimes[timeInMilliseconds] == nil { if let frameIndex = frameTimeKeys.index(where: { $0 > timeInMilliseconds }) { closestFrameTime = frameTimeKeys[max(frameIndex - 1, 0)] } } else { closestFrameTime = timeInMilliseconds } return closestFrameTime } open func getProductFrameTimes(completion: @escaping (_ frameTimes: [Double]?) -> Void) -> URLSessionDataTask? { if let apiID = featureAPIID { return getJSONWithPath("/frames/listFrames", parameters: ["media": apiID, "start": "0", "limit": "10000"], successBlock: { (result) -> Void in if let frames = result["result"] as? [NSDictionary] { completion(frames.flatMap({ $0["frameTime"] as? Double })) } else { completion(nil) } }, errorBlock: { (error) in print("Error fetching product frame times: \(error?.localizedDescription ?? "Unknown error")") completion(nil) }) } return nil } open func getProductCategories(completion: ((_ productCategories: [ProductCategory]?) -> Void)?) -> URLSessionDataTask? { if productCategories != nil { completion?(productCategories) return nil } if let apiID = featureAPIID { productCategories = [TheTakeProductCategory]() return getJSONWithPath("/categories/listProductCategories", parameters: ["media": apiID], successBlock: { [weak self] (result) in if let categories = result["result"] as? [NSDictionary] { self?.productCategories = categories.flatMap({ TheTakeProductCategory(data: $0) }) } completion?(self?.productCategories) }, errorBlock: { [weak self] (error) in print("Error fetching product categories: \(error?.localizedDescription ?? "Unknown error")") completion?(self?.productCategories) }) } return nil } open func getFrameProducts(_ frameTime: Double, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask? { if let apiID = featureAPIID, frameTime >= 0 && frameTimes[frameTime] != nil { return getJSONWithPath("/frameProducts/listFrameProducts", parameters: ["media": apiID, "time": String(frameTime)], successBlock: { (result) -> Void in if let productList = result["result"] as? NSArray { var products = [TheTakeProduct]() for productInfo in productList { if let productData = productInfo as? NSDictionary, let product = TheTakeProduct(data: productData) { products.append(product) } } completion(products) } }) { (error) -> Void in print("Error fetching products for frame \(frameTime): \(error?.localizedDescription ?? "Unknown error")") completion(nil) } } else { completion(nil) } return nil } open func getCategoryProducts(_ categoryID: String?, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask? { if let apiID = featureAPIID { var parameters: [String: String] = ["media": apiID, "limit": "100"] if let categoryID = categoryID { parameters["category"] = categoryID } return getJSONWithPath("/products/listProducts", parameters: parameters, successBlock: { (result) -> Void in if let productList = result["result"] as? NSArray { var products = [TheTakeProduct]() for productInfo in productList { if let productData = productInfo as? NSDictionary, let product = TheTakeProduct(data: productData) { products.append(product) } } completion(products) } }) { (error) -> Void in print("Error fetching products for category ID \(categoryID ?? "NONE"): \(error?.localizedDescription ?? "Unknown error")") completion(nil) } } else { completion(nil) } return nil } open func getProductDetails(_ productID: String, completion: @escaping (_ product: ProductItem?) -> Void) -> URLSessionDataTask { return getJSONWithPath("/products/productDetails", parameters: ["product": productID], successBlock: { (result) -> Void in completion(TheTakeProduct(data: result)) }) { (error) -> Void in print("Error fetching product details for product ID \(productID): \(error?.localizedDescription ?? "Unknown error")") completion(nil) } } }
apache-2.0
ixonelaguardia/miDiccionario
DiccionarioAPP/DiccionarioAPP/ListadoIdiomasViewController.swift
1
2965
// // ListadoIdiomasViewController.swift // DiccionarioAPP // // Created by on 12/1/16. // Copyright © 2016 Egibide. All rights reserved. // import UIKit class ListadoIdiomasViewController: UIViewController { var idiomas=["","","",""] @IBOutlet weak var boton1: UIButton! @IBOutlet weak var boton2: UIButton! @IBOutlet weak var boton3: UIButton! @IBOutlet weak var boton4: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func carcelar(segue:UIStoryboardSegue) { } @IBAction func hecho(segue:UIStoryboardSegue) { let nuevoIdiomaVC = segue.sourceViewController as! NuevoIdiomaViewController for i in 0...3{ if idiomas[i]==""{ idiomas[i] = nuevoIdiomaVC.nombreIdioma break } } if boton1.titleLabel!.text==nil{ boton1.setTitle(idiomas[0], forState: .Normal) boton1.enabled=true }else{ if boton2.titleLabel!.text==nil{ boton2.setTitle(idiomas[1], forState: .Normal) boton2.enabled=true }else{ if boton3.titleLabel!.text==nil{ boton3.setTitle(idiomas[2], forState: .Normal) boton3.enabled=true }else { if boton4.titleLabel!.text==nil{ boton4.setTitle(idiomas[3], forState: .Normal) boton4.enabled=true } } } } } var idioma=5; // 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?) { if let destino = segue.destinationViewController as? Listado { if segue.identifier=="segueIdioma1"{ destino.indiceIdioma=0 destino.titulo=boton1.titleLabel!.text! } else if segue.identifier=="segueIdioma2"{ destino.indiceIdioma=1 destino.titulo=boton2.titleLabel!.text! } else if segue.identifier=="segueIdioma3"{ destino.indiceIdioma=2 destino.titulo=boton3.titleLabel!.text! } else if segue.identifier=="segueIdioma4"{ destino.indiceIdioma=3 destino.titulo=boton4.titleLabel!.text! } } } }
apache-2.0
mykoma/NetworkingLib
Networking/Sources/HttpTransaction/HttpTransaction+Operation.swift
1
2033
// // HttpTransaction+RequestOperation.swift // Networking // // Created by Apple on 2016/11/4. // Copyright © 2016年 goluk. All rights reserved. // import Foundation // MARK: - Operations extension HttpTransaction { public func cancel() { self.currentRequest?.request?.cancel() self.currentRequest?.isCancelled = true } public func suspend() { self.currentRequest?.request?.suspend() } public func resume() { self.currentRequest?.request?.resume() } } // MARK: - Download var HttpTransaction_Download_ResumeData: UInt8 = 0 extension HttpTransaction { var resumeData: Data? { get { return objc_getAssociatedObject(self, &HttpTransaction_Download_ResumeData) as? Data } set { objc_setAssociatedObject(self, &HttpTransaction_Download_ResumeData, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func suspendDownload() { self.cancel() } public func resumeDownload() { let _ = HttpNetworking.sharedInstance .sendingDownloadResume(transaction: self) .subscribe(onNext: { [weak self](resp) in guard let strongSelf = self else { return } strongSelf.rxObserver?.onNext(resp) }, onError: { [weak self](error) in guard let strongSelf = self else { return } strongSelf.rxObserver?.onError(error) }, onCompleted: { [weak self] in guard let strongSelf = self else { return } strongSelf.rxObserver?.onCompleted() }) { // Dispose } } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/01294-getselftypeforcontainer.swift
11
548
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse var m: Int -> Int = { n $0 o: Int = { d, l f }(k, m) protocol j { typealias l = d} class g<q : l, m : l p q.g == m> : j { class k { protocol c : b { func b
apache-2.0
kstaring/swift
test/Constraints/diag_ambiguities_module.swift
4
521
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/has_ambiguities.swift // RUN: not %target-swift-frontend -parse %s -I %t 2>&1 | %FileCheck %s import has_ambiguities maybeTrans(0) // expected-error{{ambiguous use of 'maybeTrans'}} // CHECK: ambiguous use of 'maybeTrans' // CHECK: maybeTrans(0) // CHECK: found this candidate // CHECK-NOT: transparent // CHECK: maybeTrans(_ i: Int16) // CHECK: found this candidate // CHECK-NOT: transparent // CHECK: maybeTrans(_ i: Int32)
apache-2.0
kstaring/swift
test/Constraints/dictionary_literal.swift
4
4154
// RUN: %target-parse-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class Dictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: Dictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} useDictStringInt([4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}} useDictStringInt([nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}} useDictStringInt([7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' cannot be used with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}} var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type 'Dictionary<AnyHashable, Any>'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}} }
apache-2.0
telldus/telldus-live-mobile-v3
ios/DeviceActionShortcutExtension/IntentHandler.swift
1
493
// // IntentHandler.swift // DeviceActionShortcutExtension // // Created by Rimnesh Fernandez on 15/02/21. // Copyright © 2021 Telldus Technologies AB. All rights reserved. // import Intents import DeviceActionShortcut class IntentHandler: INExtension { override func handler(for intent: INIntent) -> Any { guard intent is DeviceActionShortcutIntent else { fatalError("Unhandled intent type: \(intent)") } return DeviceActionShortcutIntentHandler() } }
gpl-3.0
JGiola/swift-package-manager
Tests/PackageDescription4Tests/XCTestManifests.swift
1
404
#if !canImport(ObjectiveC) import XCTest extension VersionTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__VersionTests = [ ("testBasics", testBasics), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(VersionTests.__allTests__VersionTests), ] } #endif
apache-2.0
MukeshKumarS/Swift
validation-test/compiler_crashers/26298-llvm-densemapbase.swift
1
221
// RUN: not --crash %target-swift-frontend %s -emit-silgen // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/airspeedswift (airspeedswift) ["1"].map { String($0) }
apache-2.0
matrix-org/matrix-ios-sdk
MatrixSDKTests/Utils/TestObserver.swift
1
1700
// // Copyright 2021 The Matrix.org Foundation C.I.C // // 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 XCTest /// TestObserver offers additional checks on tests @objcMembers class TestObserver: NSObject { static let shared = TestObserver() var mxSessionTracker: MXSessionTracker { get { MXSessionTracker.shared } } /// Launch the tracking on open MXSessions /// There will be `fatalError()` if there are still open MXSession at the end of a test func trackMXSessions() { mxSessionTracker.trackMXSessions() XCTestObservationCenter.shared.addTestObserver(self) } } extension TestObserver: XCTestObservation { func testCaseDidFinish(_ testCase: XCTestCase) { let count = mxSessionTracker.openMXSessionsCount if count > 0 { mxSessionTracker.printOpenMXSessions() // All MXSessions must be closed at the end of the test // Else, they will continue to run in background and affect tests execution performance fatalError("Test \(testCase.name) did not close \(count) MXSession instances") } } }
apache-2.0
varunoberoi/Howzatt
HowzattTests/HowzattTests.swift
1
920
// // Cricket_ScoreboardTests.swift // Cricket ScoreboardTests // // Created by Varun Oberoi on 10/01/15. // Copyright (c) 2015 Varun Oberoi. All rights reserved. // import Cocoa import XCTest class HowzattTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
maxbritto/cours-ios11-swift4
Apprendre/Objectif 3/Objectif3_UIKit/Objectif3_UIKit/ViewController.swift
1
2987
// // ViewController.swift // Objectif3_UIKit // // Created by Maxime Britto on 28/07/2017. // Copyright © 2017 Purple Giraffe. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var ui_tableView: UITableView! var _70sShowList:[String] = [] var _friendsList:[String] = [] @IBOutlet weak var ui_demoTextField: UITextField! @IBAction func dissmissKeyboard() { ui_demoTextField.resignFirstResponder() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. ui_demoTextField.becomeFirstResponder() ui_tableView.dataSource = self _70sShowList.append("Donna") _70sShowList.append("Eric") _70sShowList.append("Kelso") _70sShowList.append("Jackie") _70sShowList.append("Fez") _70sShowList.append("Hide") _70sShowList.append("Bob") _70sShowList.append("Midge") _friendsList.append("Monica") _friendsList.append("Rachel") _friendsList.append("Phoebe") _friendsList.append("Chandler") _friendsList.append("Joey") _friendsList.append("Ross") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let title:String if section == 0 { title = "That 70's Show" } else { title = "Friends" } return title } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rowCount:Int if section == 0 { rowCount = _70sShowList.count } else { rowCount = _friendsList.count } return rowCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "number-cell", for: indexPath) if let titleLabel = cell.textLabel { if indexPath.section == 0 { titleLabel.text = _70sShowList[indexPath.row] } else { titleLabel.text = _friendsList[indexPath.row] } } return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if indexPath.section == 0 { _70sShowList.remove(at: indexPath.row) } else { _friendsList.remove(at: indexPath.row) } tableView.deleteRows(at: [indexPath], with: .automatic) } }
apache-2.0
AssistoLab/FloatingLabel
FloatingLabel/src/fields/EmailFloatingField.swift
2
443
// // EmailFloatingField.swift // FloatingLabel // // Created by Kevin Hirsch on 23/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit public class EmailFloatingField: FloatingTextField { override public func setup() { super.setup() keyboardType = .EmailAddress autocapitalizationType = .None autocorrectionType = .No spellCheckingType = .No validation = Validation(.EmailAddress) } }
mit
marselan/patient-records
Patient-Records/Patient-Records/StudyTypes.swift
1
508
// // StudyTypes.swift // Patient-Records // // Created by Mariano Arselan on 4/10/18. // Copyright © 2018 Mariano Arselan. All rights reserved. // import Foundation class StudyTypes { var types = [Int: String]() func populate(_ studyTypes : [StudyType]) { for st in studyTypes { self.types[st.id] = st.description } } static let shared : StudyTypes = StudyTypes() subscript(_ id : Int) -> String? { return types[id] } }
gpl-3.0
benlangmuir/swift
test/SILOptimizer/devirt_outer_requirements.swift
7
1450
// RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s public protocol P {} public class C1<U> { // CHECK-LABEL: sil @$s25devirt_outer_requirements2C1C3fooyyqd__AA1PRzlF : $@convention(method) <U where U : P><V> (@in_guaranteed V, @guaranteed C1<U>) -> () { // CHECK: function_ref @$s25devirt_outer_requirements2C1C3baryyqd__AA1PRzlF : $@convention(method) <τ_0_0 where τ_0_0 : P><τ_1_0> (@in_guaranteed τ_1_0, @guaranteed C1<τ_0_0>) -> () // CHECK: return public func foo<V>(_ z: V) where U : P { bar(z) } @_optimize(none) public func bar<V>(_ z: V) where U : P {} } public class Base<T> { public func foo<V>(_: V) where T : P {} } public protocol Q {} public struct Foo<T> {} extension Foo : P where T : Q {} public class Derived<T> : Base<Foo<T>> { public override func foo<V>(_: V) where T : Q {} } @_transparent public func takesBase<T, V>(_ b: Base<T>, _ v: V) where T : P { b.foo(v) } // CHECK-LABEL: sil {{.*}}@$s25devirt_outer_requirements12takesDerivedyyAA0E0CyxG_q_tAA1QRzr0_lF : $@convention(thin) <T, V where T : Q> (@guaranteed Derived<T>, @in_guaranteed V) -> () { public func takesDerived<T, V>(_ d: Derived<T>, _ v: V) where T : Q { // CHECK: function_ref @$s25devirt_outer_requirements12takesDerivedyyAA0E0CyxG_q_tAA1QRzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Q> (@guaranteed Derived<τ_0_0>, @in_guaranteed τ_0_1) -> () takesDerived(d, v) // CHECK: return }
apache-2.0
lukesutton/olpej
Olpej/Olpej/Properties-Label.swift
1
1959
extension Property { public static func text<T: UILabel>(value: String) -> Property<T> { return Property<T>("label.text", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.text = nil case .update: view.text = value } } } public static func attributedText<T: UILabel>(value: NSAttributedString) -> Property<T> { return Property<T>("label.attributedText", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.attributedText = nil case .update: view.attributedText = value } } } public static func font<T: UILabel>(value: UIFont) -> Property<T> { return Property<T>("label.font", value.hashValue) { _, mode, view in switch(mode) { case .remove: view.font = nil case .update: view.font = value } } } public static func textColor<T: UILabel>(color: UIColor) -> Property<T> { return Property<T>("label.font", color.hashValue) { _, mode, view in switch(mode) { case .remove: view.textColor = nil case .update: view.textColor = color } } } public static func textAlignment<T: UILabel>(alignment: NSTextAlignment) -> Property<T> { return Property<T>("label.font", alignment.hashValue) { _, mode, view in switch(mode) { case .remove: view.textAlignment = .Left case .update: view.textAlignment = alignment } } } public static func lineBreakMode<T: UILabel>(breakMode: NSLineBreakMode) -> Property<T> { return Property<T>("label.font", breakMode.hashValue) { _, mode, view in switch(mode) { case .remove: view.lineBreakMode = .ByTruncatingTail case .update: view.lineBreakMode = breakMode } } } }
mit
wordpress-mobile/WordPress-Aztec-iOS
AztecTests/NSAttributedString/Conversions/AttributedStringSerializerTests.swift
2
8686
import XCTest @testable import Aztec class AttributedStringSerializerTests: XCTestCase { /// Verifies that <span> Nodes are preserved into the NSAttributedString instance, by means of the UnsupportedHTML /// attribute. /// func testMultipleSpanNodesAreProperlyPreservedWithinUnsupportedHtmlAttribute() { let textNode = TextNode(text: "Ehlo World!") // <span class="aztec"></span> let spanAttribute2 = Attribute(type: .class, value: .string("aztec")) let spanNode2 = ElementNode(type: .span, attributes: [spanAttribute2], children: [textNode]) // <span class="first"><span class="aztec"></span> let spanAttribute1 = Attribute(type: .class, value: .string("first")) let spanNode1 = ElementNode(type: .span, attributes: [spanAttribute1], children: [spanNode2]) // <h1><span class="first"><span class="aztec"></span></span></h1> let headerNode = ElementNode(type: .h1, attributes: [], children: [spanNode1]) let rootNode = RootNode(children: [headerNode]) // Convert let output = attributedString(from: rootNode) // Test var range = NSRange() guard let unsupportedHTML = output.attribute(.unsupportedHtml, at: 0, effectiveRange: &range) as? UnsupportedHTML else { XCTFail() return } let representations = unsupportedHTML.representations XCTAssert(range.length == textNode.length()) XCTAssert(representations.count == 2) let restoredSpanElement2 = representations.last XCTAssertEqual(restoredSpanElement2?.name, "span") let restoredSpanAttribute2 = restoredSpanElement2?.attributes.first XCTAssertEqual(restoredSpanAttribute2?.name, "class") XCTAssertEqual(restoredSpanAttribute2?.value.toString(), "aztec") let restoredSpanElement1 = representations.first XCTAssertEqual(restoredSpanElement1?.name, "span") let restoredSpanAttribute1 = restoredSpanElement1?.attributes.first XCTAssertEqual(restoredSpanAttribute1?.type, .class) XCTAssertEqual(restoredSpanAttribute1?.value.toString(), "first") } /// Verifies that the DivFormatter effectively appends the DIV Element Representation, to the properties collection. /// func testHtmlDivFormatterEffectivelyAppendsNewDivProperty() { let textNode = TextNode(text: "Ehlo World!") let divAttr3 = Attribute(type: .class, value: .string("third")) let divNode3 = ElementNode(type: .div, attributes: [divAttr3], children: [textNode]) let divAttr2 = Attribute(type: .class, value: .string("second")) let divNode2 = ElementNode(type: .div, attributes: [divAttr2], children: [divNode3]) let divAttr1 = Attribute(type: .class, value: .string("first")) let divNode1 = ElementNode(type: .div, attributes: [divAttr1], children: [divNode2]) // Convert let output = attributedString(from: divNode1) // Test! var range = NSRange() guard let paragraphStyle = output.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? ParagraphStyle else { XCTFail() return } XCTAssert(range.length == textNode.length()) XCTAssert(paragraphStyle.htmlDiv.count == 3) guard case let .element(restoredDiv1) = paragraphStyle.htmlDiv[0].representation!.kind, case let .element(restoredDiv2) = paragraphStyle.htmlDiv[1].representation!.kind, case let .element(restoredDiv3) = paragraphStyle.htmlDiv[2].representation!.kind else { XCTFail() return } XCTAssert(restoredDiv1.name == divNode1.name) XCTAssert(restoredDiv1.attributes == [divAttr1]) XCTAssert(restoredDiv2.name == divNode2.name) XCTAssert(restoredDiv2.attributes == [divAttr2]) XCTAssert(restoredDiv3.name == divNode3.name) XCTAssert(restoredDiv3.attributes == [divAttr3]) } /// Verifies that BR elements contained within div tags do not cause any side effect. /// Ref. #658 /// func testLineBreakTagWithinHTMLDivGetsProperlyEncodedAndDecoded() { let inHtml = "<div><br>Aztec, don't forget me!</div>" let inNode = HTMLParser().parse(inHtml) let attrString = attributedString(from: inNode) let outNode = AttributedStringParser().parse(attrString) let outHtml = HTMLSerializer().serialize(outNode) XCTAssertEqual(outHtml, inHtml) } /// Verifies that BR elements contained within span tags do not cause Data Loss. /// Ref. #658 /// func testLineBreakTagWithinUnsupportedHTMLDoesNotCauseDataLoss() { let inHtml = "<span><br>Aztec, don't forget me!</span>" let expectedHtml = "<p><span><br>Aztec, don't forget me!</span></p>" let inNode = HTMLParser().parse(inHtml) let attrString = attributedString(from: inNode) let outNode = AttributedStringParser().parse(attrString) let outHtml = HTMLSerializer().serialize(outNode) XCTAssertEqual(outHtml, expectedHtml) } /// Verifies that nested Unsupported HTML snippets get applied to *their own* UnsupportedHTML container. /// Ref. #658 /// func testMultipleUnrelatedUnsupportedHTMLSnippetsDoNotGetAppliedToTheEntireStringRange() { let inHtml = "<div>" + "<p><span>One</span></p>" + "<p><span><br></span></p>" + "<p><span>Two</span></p>" + "<p><br></p>" + "<p><span>Three</span><span>Four</span><span>Five</span></p>" + "</div>" let inNode = HTMLParser().parse(inHtml) let attrString = attributedString(from: inNode) let outNode = AttributedStringParser().parse(attrString) let outHtml = HTMLSerializer().serialize(outNode) XCTAssertEqual(outHtml, inHtml) } /// Verifies that a linked image is properly converted from HTML to attributed string and back to HTML. /// func testLinkedImageGetsProperlyEncodedAndDecoded() { let inHtml = "<p><a href=\"https://wordpress.com\" class=\"alignnone\"><img src=\"https://s.w.org/about/images/wordpress-logo-notext-bg.png\" class=\"alignnone\"></a></p>" let inNode = HTMLParser().parse(inHtml) let attrString = attributedString(from: inNode) let outNode = AttributedStringParser().parse(attrString) let outHtml = HTMLSerializer().serialize(outNode) XCTAssertEqual(outHtml, inHtml) } /// Verifies that Figure + Figcaption entities are properly mapped within an Image's caption field. /// /// - Input: <figure><img src="."><figcaption><h1>I'm a caption!</h1></figcaption></figure> /// /// - Output: Expected to he a single ImageAttachment, with it's `.caption` field properly set (and it's contents in h1 format). /// func testFigcaptionElementGetsProperlySerializedIntoImageAttachmentCaptionField() { // <figcaption><h1>I'm a caption!</h1></figcaption> let figcaptionTextNode = TextNode(text: "I'm a caption!") let figcaptionH1Node = ElementNode(type: .h1, attributes: [], children: [figcaptionTextNode]) let figcaptionMainNode = ElementNode(type: .figcaption, attributes: [], children: [figcaptionH1Node]) // <figure><img/><figcaption/></figure> let imageNode = ElementNode(type: .img, attributes: [], children: []) let figureNode = ElementNode(type: .figure, attributes: [], children: [imageNode, figcaptionMainNode]) // Convert let rootNode = RootNode(children: [figureNode]) let output = attributedString(from: rootNode) guard let imageAttachment = output.attribute(.attachment, at: 0, effectiveRange: nil) as? ImageAttachment else { XCTFail() return } guard let caption = output.caption(for: imageAttachment) else { XCTFail() return } let formatter = HeaderFormatter(headerLevel: .h1) XCTAssertTrue(formatter.present(in: caption, at: 0)) } } // MARK: - Helpers // extension AttributedStringSerializerTests { func attributedString(from node: Node) -> NSAttributedString { let defaultAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14), .paragraphStyle: ParagraphStyle.default] let serializer = AttributedStringSerializer() return serializer.serialize(node, defaultAttributes: defaultAttributes) } }
gpl-2.0
rechsteiner/Parchment
Parchment/Classes/PagingOptions.swift
1
6733
import UIKit public struct PagingOptions { /// The size for each of the menu items. _Default: /// .sizeToFit(minWidth: 150, height: 40)_ public var menuItemSize: PagingMenuItemSize /// Determine the spacing between the menu items. _Default: 0_ public var menuItemSpacing: CGFloat /// Determine the horizontal constraints of menu item label. _Default: 20_ public var menuItemLabelSpacing: CGFloat /// Determine the insets at around all the menu items. _Default: /// UIEdgeInsets.zero_ public var menuInsets: UIEdgeInsets /// Determine whether the menu items should be centered when all the /// items can fit within the bounds of the view. _Default: .left_ public var menuHorizontalAlignment: PagingMenuHorizontalAlignment /// Determine the position of the menu relative to the content. /// _Default: .top_ public var menuPosition: PagingMenuPosition /// Determine the transition behaviour of menu items while scrolling /// the content. _Default: .scrollAlongside_ public var menuTransition: PagingMenuTransition /// Determine how users can interact with the menu items. /// _Default: .scrolling_ public var menuInteraction: PagingMenuInteraction /// Determine how users can interact with the contents /// _Default: .scrolling_ public var contentInteraction: PagingContentInteraction /// The class type for collection view layout. Override this if you /// want to use your own subclass of the layout. Setting this /// property will initialize the new layout type and update the /// collection view. /// _Default: PagingCollectionViewLayout.self_ public var menuLayoutClass: PagingCollectionViewLayout.Type /// Determine how the selected menu item should be aligned when it /// is selected. Effectivly the same as the /// `UICollectionViewScrollPosition`. _Default: .preferCentered_ public var selectedScrollPosition: PagingSelectedScrollPosition /// Add an indicator view to the selected menu item. The indicator /// width will be equal to the selected menu items width. Insets /// only apply horizontally. _Default: .visible_ public var indicatorOptions: PagingIndicatorOptions /// The class type for the indicator view. Override this if you want /// your use your own subclass of PagingIndicatorView. _Default: /// PagingIndicatorView.self_ public var indicatorClass: PagingIndicatorView.Type /// Determine the color of the indicator view. public var indicatorColor: UIColor /// Add a border at the bottom of the menu items. The border will be /// as wide as all the menu items. Insets only apply horizontally. /// _Default: .visible_ public var borderOptions: PagingBorderOptions /// The class type for the border view. Override this if you want /// your use your own subclass of PagingBorderView. _Default: /// PagingBorderView.self_ public var borderClass: PagingBorderView.Type /// Determine the color of the border view. public var borderColor: UIColor /// Updates the content inset for the menu items based on the /// .safeAreaInsets property. _Default: true_ public var includeSafeAreaInsets: Bool /// The font used for title label on the menu items. public var font: UIFont /// The font used for the currently selected menu item. public var selectedFont: UIFont /// The color of the title label on the menu items. public var textColor: UIColor /// The text color for the currently selected menu item. public var selectedTextColor: UIColor /// The background color for the menu items. public var backgroundColor: UIColor /// The background color for the selected menu item. public var selectedBackgroundColor: UIColor /// The background color for the view behind the menu items. public var menuBackgroundColor: UIColor /// The background color for the paging contents /// _Default: .white public var pagingContentBackgroundColor: UIColor /// The scroll navigation orientation of the content in the page /// view controller. _Default: .horizontal_ public var contentNavigationOrientation: PagingNavigationOrientation public var scrollPosition: UICollectionView.ScrollPosition { switch selectedScrollPosition { case .left: return UICollectionView.ScrollPosition.left case .right: return UICollectionView.ScrollPosition.right case .preferCentered, .center: return UICollectionView.ScrollPosition.centeredHorizontally } } public var menuHeight: CGFloat { return menuItemSize.height + menuInsets.top + menuInsets.bottom } public var estimatedItemWidth: CGFloat { switch menuItemSize { case let .fixed(width, _): return width case let .sizeToFit(minWidth, _): return minWidth case let .selfSizing(estimatedItemWidth, _): return estimatedItemWidth } } public init() { selectedScrollPosition = .preferCentered menuItemSize = .sizeToFit(minWidth: 150, height: 40) menuPosition = .top menuTransition = .scrollAlongside menuInteraction = .scrolling menuInsets = UIEdgeInsets.zero menuItemSpacing = 0 menuItemLabelSpacing = 20 menuHorizontalAlignment = .left includeSafeAreaInsets = true indicatorClass = PagingIndicatorView.self borderClass = PagingBorderView.self menuLayoutClass = PagingCollectionViewLayout.self indicatorOptions = .visible( height: 4, zIndex: Int.max, spacing: UIEdgeInsets.zero, insets: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) ) borderOptions = .visible( height: 1, zIndex: Int.max - 1, insets: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) ) font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium) selectedFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium) textColor = UIColor.black selectedTextColor = UIColor(red: 3 / 255, green: 125 / 255, blue: 233 / 255, alpha: 1) backgroundColor = .clear selectedBackgroundColor = .clear pagingContentBackgroundColor = .white menuBackgroundColor = UIColor.white borderColor = UIColor(white: 0.9, alpha: 1) indicatorColor = UIColor(red: 3 / 255, green: 125 / 255, blue: 233 / 255, alpha: 1) contentNavigationOrientation = .horizontal contentInteraction = .scrolling } }
mit
likojack/wedrive_event_management
weDrive/DatePickerDialog.swift
2
12497
import UIKit import QuartzCore class DatePickerDialog: UIView { /* Consts */ private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50 private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1 private let kDatePickerDialogCornerRadius: CGFloat = 7 private let kDatePickerDialogCancelButtonTag: Int = 1 private let kDatePickerDialogDoneButtonTag: Int = 2 /* Views */ private var dialogView: UIView! private var titleLabel: UILabel! private var datePicker: UIDatePicker! private var cancelButton: UIButton! private var doneButton: UIButton! /* Vars */ private var title: String! private var doneButtonTitle: String! private var cancelButtonTitle: String! private var defaultDate: NSDate! private var datePickerMode: UIDatePickerMode! private var callback: ((date: NSDate) -> Void)! /* Overrides */ init () { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* Handle device orientation changes */ func deviceOrientationDidChange(notification: NSNotification) { /* TODO */ } /* Create the dialog view, and animate opening the dialog */ func show(#title: String, datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { show(title: title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback) } func show(#title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { self.title = title self.doneButtonTitle = doneButtonTitle self.cancelButtonTitle = cancelButtonTitle self.datePickerMode = datePickerMode self.callback = callback self.defaultDate = defaultDate self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(self.dialogView!) /* Attached to the top most window (make sure we are using the right orientation) */ let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation switch(interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: let t: Double = M_PI * 270 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.LandscapeRight: let t: Double = M_PI * 90 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.PortraitUpsideDown: let t: Double = M_PI * 180 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break default: break } self.frame = CGRectMake(0, 0, self.frame.width, self.frame.size.height) UIApplication.sharedApplication().windows.first!.addSubview(self) /* Anim */ UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } /* Dialog close animation then cleaning and removing the view from the parent */ private func close() { let currentTransform = self.dialogView.layer.transform let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ private func createContainerView() -> UIView { let screenSize = countScreenSize() let dialogSize = CGSizeMake( 300, 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) // For the black background self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor] let cornerRadius = kDatePickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, atIndex: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath // There is a line above the button let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30)) self.titleLabel.textAlignment = NSTextAlignment.Center self.titleLabel.font = UIFont.boldSystemFontOfSize(17) self.titleLabel.text = self.title dialogContainer.addSubview(self.titleLabel) self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0)) self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin self.datePicker.frame.size.width = 300 self.datePicker.datePickerMode = self.datePickerMode self.datePicker.date = self.defaultDate dialogContainer.addSubview(self.datePicker) // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ private func addButtonsToView(container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton self.cancelButton.frame = CGRectMake( 0, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.cancelButton.tag = kDatePickerDialogCancelButtonTag self.cancelButton.setTitle(self.cancelButtonTitle, forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.cancelButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton self.doneButton.frame = CGRectMake( buttonWidth, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.doneButton.tag = kDatePickerDialogDoneButtonTag self.doneButton.setTitle(self.doneButtonTitle, forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.doneButton) } func buttonTapped(sender: UIButton!) { if sender.tag == kDatePickerDialogDoneButtonTag { self.callback(date: self.datePicker.date) } else if sender.tag == kDatePickerDialogCancelButtonTag { //There's nothing do to here \o\ } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { var screenWidth = UIScreen.mainScreen().bounds.size.width var screenHeight = UIScreen.mainScreen().bounds.size.height let interfaceOrientaion = UIApplication.sharedApplication().statusBarOrientation if UIInterfaceOrientationIsLandscape(interfaceOrientaion) { let tmp = screenWidth screenWidth = screenHeight screenHeight = tmp } return CGSizeMake(screenWidth, screenHeight) } }
apache-2.0
firebase/quickstart-ios
authentication/AuthenticationExample/SceneDelegate.swift
1
3193
// Copyright 2020 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 UIKit import FirebaseDynamicLinks import FirebaseAuth class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? lazy var authNavController: UINavigationController = { let navController = UINavigationController(rootViewController: AuthViewController()) navController.view.backgroundColor = .systemBackground return navController }() lazy var userNavController: UINavigationController = { let navController = UINavigationController(rootViewController: UserViewController()) navController.view.backgroundColor = .systemBackground return navController }() lazy var tabBarController: UITabBarController = { let tabBarController = UITabBarController() tabBarController.delegate = tabBarController tabBarController.view.backgroundColor = .systemBackground return tabBarController }() func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } configureControllers() window = UIWindow(windowScene: windowScene) window?.rootViewController = tabBarController window?.makeKeyAndVisible() } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { if let incomingURL = userActivity.webpageURL { handleIncomingDynamicLink(incomingURL) } } // MARK: - Firebase 🔥 private func handleIncomingDynamicLink(_ incomingURL: URL) { DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { dynamicLink, error in guard error == nil else { return print("ⓧ Error in \(#function): \(error!.localizedDescription)") } guard let link = dynamicLink?.url?.absoluteString else { return } if Auth.auth().isSignIn(withEmailLink: link) { // Save the link as it will be used in the next step to complete login UserDefaults.standard.set(link, forKey: "Link") // Post a notification to the PasswordlessViewController to resume authentication NotificationCenter.default .post(Notification(name: Notification.Name("PasswordlessEmailNotificationSuccess"))) } } } // MARK: - Private Helpers private func configureControllers() { authNavController.configureTabBar( title: "Authentication", systemImageName: "person.crop.circle.fill.badge.plus" ) userNavController.configureTabBar(title: "Current User", systemImageName: "person.fill") tabBarController.viewControllers = [authNavController, userNavController] } }
apache-2.0
iHunterX/SocketIODemo
DemoSocketIO/Classes/RequiredViewController.swift
1
3584
// // RequiredViewController.swift // DemoSocketIO // // Created by Đinh Xuân Lộc on 10/28/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import UIKit class RequiredViewController: PAPermissionsViewController,PAPermissionsViewControllerDelegate { let cameraCheck = PACameraPermissionsCheck() let locationCheck = PALocationPermissionsCheck() let microphoneCheck = PAMicrophonePermissionsCheck() let photoLibraryCheck = PAPhotoLibraryPermissionsCheck() lazy var notificationsCheck : PAPermissionsCheck = { if #available(iOS 10.0, *) { return PAUNNotificationPermissionsCheck() } else { return PANotificationsPermissionsCheck() } }() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = true self.delegate = self let permissions = [ PAPermissionsItem.itemForType(.location, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.microphone, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.photoLibrary, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.notifications, reason: "Required to send you great updates")!, PAPermissionsItem.itemForType(.camera, reason: PAPermissionDefaultReason)!] let handlers = [ PAPermissionsType.location.rawValue: self.locationCheck, PAPermissionsType.microphone.rawValue :self.microphoneCheck, PAPermissionsType.photoLibrary.rawValue: self.photoLibraryCheck, PAPermissionsType.camera.rawValue: self.cameraCheck, PAPermissionsType.notifications.rawValue: self.notificationsCheck ] self.setupData(permissions, handlers: handlers) // Do any additional setup after loading the view. self.tintColor = UIColor.white self.backgroundImage = #imageLiteral(resourceName: "background") self.useBlurBackground = false self.titleText = "iSpam" self.detailsText = "Please enable the following" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func permissionsViewControllerDidContinue(_ viewController: PAPermissionsViewController) { if let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "MainController") as? UINavigationController { // let appDelegate = UIApplication.shared.delegate as! AppDelegate // let presentingViewController: UIViewController! = self.presentingViewController // // self.dismiss(animated: false) { // // go back to MainMenuView as the eyes of the user // presentingViewController.dismiss(animated: false, completion: { //// self.present(loginVC, animated: true, completion: nil) // }) // } loginVC.modalTransitionStyle = .crossDissolve self.present(loginVC, animated: true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
RajatDhasmana/rajat_appinventiv
constraints/constraints/ViewController.swift
1
509
// // ViewController.swift // constraints // // Created by Mohd Sultan on 15/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
rtsbtx/IQKeyboardManager
IQKeybordManagerSwift/IQToolbar/IQToolbar.swift
3
3368
// // IQToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-15 Iftekhar Qurashi. // // 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 /** @abstract IQToolbar for IQKeyboardManager. */ class IQToolbar: UIToolbar , UIInputViewAudioFeedback { override class func initialize() { superclass()?.initialize() self.appearance().barTintColor = nil self.appearance().backgroundColor = nil } var titleFont : UIFont? { didSet { if items != nil { for item in items as! [UIBarButtonItem] { if item is IQTitleBarButtonItem == true { (item as! IQTitleBarButtonItem).font = titleFont } } } } } var title : String? { didSet { if items != nil { for item in items as! [UIBarButtonItem] { if item is IQTitleBarButtonItem == true { (item as! IQTitleBarButtonItem).title = title } } } } } override init(frame: CGRect) { super.init(frame: frame) sizeToFit() autoresizingMask = UIViewAutoresizing.FlexibleWidth tintColor = UIColor .blackColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sizeToFit() autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight tintColor = UIColor .blackColor() } override func sizeThatFits(size: CGSize) -> CGSize { var sizeThatFit = super.sizeThatFits(size) sizeThatFit.height = 44 return sizeThatFit } override var tintColor: UIColor! { didSet { if let unwrappedItems = items { for item in unwrappedItems as! [UIBarButtonItem] { if item is IQTitleBarButtonItem { item.tintColor = tintColor } } } } } var enableInputClicksWhenVisible: Bool { return true } }
mit
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Groups/Search/GroupsModel.swift
1
5980
// // GenericModel.swift // GetSocialDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import Foundation class GroupsModel { var onInitialDataLoaded: (() -> Void)? var onDidOlderLoad: ((Bool) -> Void)? var onError: ((String) -> Void)? var groupFollowed: ((Int) -> Void)? var groupUnfollowed: ((Int) -> Void)? var onGroupDeleted: ((Int) -> Void)? var onGroupJoined: ((GroupMember, Int) -> Void)? var onGroupLeft: ((Int) -> Void)? var onInviteAccepted: ((Int) -> Void)? var pagingQuery: GroupsPagingQuery? var query: GroupsQuery? var groups: [Group] = [] var nextCursor: String = "" func loadEntries(query: GroupsQuery) { self.query = query self.pagingQuery = GroupsPagingQuery.init(query) self.groups.removeAll() executeQuery(success: { self.onInitialDataLoaded?() }, failure: onError) } func loadNewer() { self.pagingQuery?.nextCursor = "" self.groups.removeAll() executeQuery(success: { self.onInitialDataLoaded?() }, failure: onError) } func loadOlder() { if self.nextCursor.count == 0 { onDidOlderLoad?(false) return } self.pagingQuery?.nextCursor = self.nextCursor executeQuery(success: { self.onDidOlderLoad?(true) }, failure: onError) } func numberOfEntries() -> Int { return self.groups.count } func entry(at: Int) -> Group { return self.groups[at] } func findGroup(_ groupId: String) -> Group? { return self.groups.filter { return $0.id == groupId }.first } func joinGroup(_ groupId: String) { let query = JoinGroupQuery.init(groupId: groupId) if let oldGroup = findGroup(groupId), let groupIndex = self.groups.firstIndex(of: oldGroup) { Communities.joinGroup(query, success: { [weak self] member in Communities.group(groupId, success: { group in self?.groups[groupIndex] = group self?.onGroupJoined?(member, groupIndex) }, failure: { error in self?.onError?(error.localizedDescription) }) }, failure: { [weak self] error in self?.onError?(error.localizedDescription) }) } } func acceptInvite(_ groupId: String, membership: Membership) { var groupIndex: Int? for (index, group) in self.groups.enumerated() { if group.id == groupId { groupIndex = index } } let query = JoinGroupQuery.init(groupId: groupId).withInvitationToken(membership.invitationToken!) Communities.joinGroup(query, success: { [weak self] members in Communities.group(groupId, success: { group in self?.groups[groupIndex!] = group self?.onInviteAccepted?(groupIndex!) }, failure: { error in self?.onError?(error.localizedDescription) }) }, failure: { [weak self] error in self?.onError?(error.localizedDescription) }) } func followGroup(_ groupId: String) { if let group = findGroup(groupId), let groupIndex = self.groups.firstIndex(of: group) { let query = FollowQuery.groups([groupId]) if group.isFollowedByMe { Communities.unfollow(query, success: { _ in PrivateGroupBuilder.updateGroup(group: group, isFollowed: false) self.groupUnfollowed?(groupIndex) }) { error in self.onError?(error.localizedDescription) } } else { Communities.follow(query, success: { _ in PrivateGroupBuilder.updateGroup(group: group, isFollowed: true) self.groupFollowed?(groupIndex) }) { error in self.onError?(error.localizedDescription) } } } } func deleteGroup(_ groupId: String) { var groupIndex: Int? for (index, group) in self.groups.enumerated() { if group.id == groupId { groupIndex = index } } Communities.removeGroups([groupId], success: { [weak self] in self?.groups.remove(at: groupIndex!) self?.onGroupDeleted?(groupIndex!) }, failure: { [weak self] error in self?.onError?(error.localizedDescription) }) } func leaveGroup(_ groupId: String) { guard let currentUserId = GetSocial.currentUser()?.userId else { self.onError?("Could not get current user") return } var groupIndex: Int? for (index, group) in self.groups.enumerated() { if group.id == groupId { groupIndex = index } } let query = RemoveGroupMembersQuery.users(UserIdList.create([currentUserId]), from: groupId) Communities.removeGroupMembers(query, success: { [weak self] in Communities.group(groupId, success: { group in self?.groups[groupIndex!] = group self?.onGroupLeft?(groupIndex!) }, failure: { error in self?.onError?(error.localizedDescription) }) }, failure: { [weak self] error in self?.onError?(error.localizedDescription) }) } private func executeQuery(success: (() -> Void)?, failure: ((String) -> Void)?) { Communities.groups(self.pagingQuery!, success: { result in self.nextCursor = result.nextCursor self.groups.append(contentsOf: result.groups) success?() }) { error in failure?(error.localizedDescription) } } }
apache-2.0
Kruks/FindViewControl
FindViewControl/FindViewControl/Constants.swift
1
1070
// // Constants.swift // MyCity311 // // Created by Piyush on 6/2/16. // Copyright © 2016 Kahuna Systems. All rights reserved. // import Foundation import UIKit struct Constants { enum TimeOutIntervals { static let kSRRetryCount = 3 static let kMaxRetryCount = 3 static let kSRTimeoutInterval = 60 static let kMaxTimeoutInterval = 240 static let cacheImageTimeOut = 30.0 static let kMaxLocationWaitTime = 10 static let kMinHorizontalAccuracy = 100 static let horizontalLocationAccuracy = 70 static let maximumWaitTimeForLocation = 10 static let defaultImageCompressionValue = 0.7 static let queryPageSize = 10 } enum UnidentifiedError: Error { case emptyHTTPResponse } enum ServerResponseCodes { static let successCode: Int = 200 static let unknownErrorCode: Int = 1000 static let generalErrorCode = 201 static let sessionExpireErrorCode = 234 static let duplicateEntryCode = 203 } }
mit
muukii/NextGrowingTextView
NextGrowingTextView-Demo/Book.swift
1
1466
import StorybookKit import NextGrowingTextView import UIKit import MondrianLayout let book = Book(title: "NextGrowingTextView") { BookPush(title: "Flexible Width") { FlexibleWidthCenteringViewController() } BookPush(title: "Fixed Width") { FixedWidthViewController() } } func makeControlPanel(for growingTextView: NextGrowingTextView) -> UIView { let view = UIView() Mondrian.buildSubviews(on: view) { VGridBlock(columns: [ .init(.flexible(), spacing: 10), .init(.flexible(), spacing: 10), ]) { UIButton.make(title: "Set text") { growingTextView.textView.text = BookGenerator.loremIpsum(length: 300) } UIButton.make(title: "Clear text") { growingTextView.textView.text = "" } UIButton.make(title: "Max = 3") { growingTextView.configuration.maxLines = 3 } UIButton.make(title: "Max = 10") { growingTextView.configuration.maxLines = 10 } UIButton.make(title: "Min = 1") { growingTextView.configuration.minLines = 1 } UIButton.make(title: "Min = 5") { growingTextView.configuration.minLines = 5 } UIButton.make(title: "Long placeholder") { growingTextView.placeholderLabel.text = "Placeholder, Placeholder, Placeholder, " growingTextView.placeholderLabel.numberOfLines = 0 } } } return view }
mit
universeiscool/MediaPickerController
MediaPickerController/MediaPickerController.swift
1
11038
// // MediaPickerController.swift // MediaPickerController // // Created by Malte Schonvogel on 22.11.15. // Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved. // import UIKit import Photos public enum MediaPickerOption { case ViewBackgroundColor(UIColor) case NavigationBarTitleAttributes([String:AnyObject]) } public enum MediaPickerAlbumType { case Moments case Selected case AllAssets case UserAlbum case Panorama case Screenshots case Favorites case RecentlyAdded case SelfPortraits static func convertFromAssetTypes(assetCollectionSubtype: PHAssetCollectionSubtype) -> MediaPickerAlbumType? { var type:MediaPickerAlbumType? = nil switch assetCollectionSubtype { case .SmartAlbumPanoramas: type = .Panorama case .SmartAlbumRecentlyAdded: type = .RecentlyAdded case .SmartAlbumScreenshots: type = .Screenshots case .SmartAlbumSelfPortraits: type = .SelfPortraits case .SmartAlbumFavorites: type = .Favorites case .SmartAlbumUserLibrary: type = .AllAssets case .AlbumRegular: type = .UserAlbum default: type = nil } return type } } public class MediaPickerAlbum { var title: String? var cover: UIImage? var collection: PHAssetCollection? var fetchResult: PHFetchResult? // For Moments var assetCount: Int var type: MediaPickerAlbumType init(title:String?, collection:PHAssetCollection?, assetCount:Int, type: MediaPickerAlbumType) { self.title = title self.collection = collection self.assetCount = assetCount self.type = type } } public struct MediaPickerMoment { let title:String let date:String let assets:PHFetchResult } public class MediaPickerController: UINavigationController { public var selectedAssets = [PHAsset]() { didSet { doneButtonView.enabled = selectedAssets.count > 0 } } public var prevSelectedAssetIdentifiers:[String]? lazy var doneButtonView:UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(didClickDoneButton(_:))) button.enabled = false return button }() lazy var cancelButtonView:UIBarButtonItem = { return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(didClickCancelButton(_:))) }() lazy var selectAlbumButtonView: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(didClickSelectAlbumButton(_:)), forControlEvents: UIControlEvents.TouchUpInside) button.enabled = false return button }() var selectAlbumButtonTitle:String { set { let attributedTitle = NSAttributedString(string: newValue.uppercaseString, attributes: navigationBarTitleAttributes) selectAlbumButtonView.setAttributedTitle(attributedTitle, forState: .Normal) selectAlbumButtonView.sizeToFit() } get { return selectAlbumButtonView.titleLabel?.text ?? "" } } lazy public var photosViewController: PhotosViewController = { let vc = PhotosViewController() return vc }() lazy public var momentsViewController: MomentsViewController = { let vc = MomentsViewController() return vc }() lazy public var albumsViewController: AlbumsViewController = { let vc = AlbumsViewController(albums: self.albums) vc.preferredContentSize = self.view.bounds.size vc.delegate = self return vc }() var albums: [[MediaPickerAlbum]]? public var doneClosure:((assets: [PHAsset], momentTitle:String?, mediaPickerController:MediaPickerController) -> Void)? public var cancelClosure:((mediaPickerController:MediaPickerController) -> Void)? public var maximumSelect = Int(50) { didSet { allowsMultipleSelection = maximumSelect > 1 } } public var allowsMultipleSelection = true public var viewBackgroundColor = UIColor.blackColor() public var navigationBarTitleAttributes:[String:AnyObject] = [ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 16.0)!, NSKernAttributeName: 1.5 ] public var hintText:String? public convenience init(mediaPickerOptions:[MediaPickerOption]?) { self.init(nibName: nil, bundle: nil) if let options = mediaPickerOptions { optionsToInstanceVariables(options) } } override private init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func viewDidLoad() { super.viewDidLoad() selectAlbumButtonTitle = "Loading ..." let fetcher = AlbumFetcher.shared fetcher.fetchAlbums{ (albums) in self.selectAlbumButtonView.enabled = true self.albums = albums if let album = self.albums?.flatten().filter({ $0.type == .Moments }).first { self.momentsViewController.album = album } else if let album = self.albums?.flatten().first { self.setViewControllers([self.photosViewController], animated: false) self.photosViewController.album = album } } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) // Make sure MomentsViewController won't be displayed, if allowsMultipleSelection is not allowed if albums?.count > 0 && !allowsMultipleSelection { if getActiveViewController() is MomentsViewController { setViewControllers([photosViewController], animated: false) if let album = self.albums?.flatten().filter({ $0.type == .AllAssets }).first where photosViewController.album == nil { self.photosViewController.album = album } } } } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) selectedAssets.removeAll() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public override func loadView() { super.loadView() navigationBar.translucent = false setViewControllers([momentsViewController], animated: false) } func didClickSelectAlbumButton(sender: UIButton) { guard let popover = albumsViewController.popoverPresentationController else { return } popover.permittedArrowDirections = .Up popover.sourceView = sender let senderRect = sender.convertRect(sender.frame, fromView: sender.superview) let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + 4.0, width: senderRect.size.width, height: senderRect.size.height) popover.sourceRect = sourceRect popover.delegate = self albumsViewController.hideMoments = !allowsMultipleSelection presentViewController(albumsViewController, animated: true, completion: nil) } func didClickDoneButton(sender: UIBarButtonItem) { if let vc = viewControllers.first as? MomentsViewController { if let moment = vc.selectedMoment { var assets = [PHAsset]() for i in 0..<moment.assets.count { assets.append(moment.assets[i] as! PHAsset) } doneClosure?(assets:assets, momentTitle:moment.title, mediaPickerController:self) } } else if let _ = viewControllers.first as? PhotosViewController { doneClosure?(assets:selectedAssets, momentTitle:nil, mediaPickerController:self) } } func didClickCancelButton(sender: UIBarButtonItem) { cancelClosure?(mediaPickerController:self) } // MARK: Helper Functions private func optionsToInstanceVariables(options:[MediaPickerOption]) { for option in options { switch option { case let .ViewBackgroundColor(value): viewBackgroundColor = value case let .NavigationBarTitleAttributes(value): navigationBarTitleAttributes = value } } } private func getActiveViewController() -> MediaPickerCollectionViewController? { if let vc = viewControllers.first as? MomentsViewController { return vc } else if let vc = viewControllers.first as? PhotosViewController { return vc } return nil } } extension MediaPickerController: PHPhotoLibraryChangeObserver { public func photoLibraryDidChange(changeInstance: PHChange) { } } // MARK: UIPopoverPresentationControllerDelegate extension MediaPickerController: UIPopoverPresentationControllerDelegate { public func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } public func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool { return true } } // MARK: UINavigationControllerDelegate //extension PhotosViewController: UINavigationControllerDelegate { // public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { // if operation == .Push { // return expandAnimator // } else { // return shrinkAnimator // } // } //} extension MediaPickerController: AlbumsViewControllerDelegate { func didSelectAlbum(album:MediaPickerAlbum) { self.albumsViewController.dismissViewControllerAnimated(true, completion: nil) if album.type == .Moments { self.setViewControllers([self.momentsViewController], animated: false) self.momentsViewController.album = album } else { self.setViewControllers([self.photosViewController], animated: false) self.photosViewController.album = album } } }
mit
nguyenantinhbk77/practice-swift
HealthKit/HealthKit Authorization/HealthKit AuthorizationTests/HealthKit_AuthorizationTests.swift
2
943
// // HealthKit_AuthorizationTests.swift // HealthKit AuthorizationTests // // Created by Domenico on 08/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit import XCTest class HealthKit_AuthorizationTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit