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
tiagobsbraga/HotmartTest
HotmartTest/MainViewController.swift
1
751
// // MainViewController.swift // HotmartTest // // Created by Tiago Braga on 05/02/17. // Copyright © 2017 Tiago Braga. All rights reserved. // import UIKit import SlideMenuControllerSwift class MainViewController: SlideMenuController { override func awakeFromNib() { self.mainViewController = AppStoryboard.Dashboard.instance.instantiateViewController(withIdentifier: "Main") self.leftViewController = AppStoryboard.Main.instance.instantiateViewController(withIdentifier: "Menu") SlideMenuOptions.contentViewScale = 1 SlideMenuOptions.contentViewOpacity = 0.3 SlideMenuOptions.opacityViewBackgroundColor = Style.Color.black super.awakeFromNib() } }
mit
overtake/TelegramSwift
Telegram-Mac/PIPVideoWindow.swift
1
12164
// // PIPVideoWindow.swift // Telegram // // Created by keepcoder on 26/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import AVKit import SwiftSignalKit private let pipFrameKey: String = "kPipFrameKey3" enum PictureInPictureControlMode { case normal case pip } protocol PictureInPictureControl { func pause() func play() func didEnter() func didExit() var view: NSView { get } var isPictureInPicture: Bool { get } func setMode(_ mode: PictureInPictureControlMode, animated: Bool) } private class PictureInpictureView : Control { private let _window: Window init(frame: NSRect, window: Window) { _window = window super.init(frame: frame) autoresizesSubviews = true } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) } override func mouseExited(with event: NSEvent) { super.mouseEntered(with: event) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override var window: NSWindow? { set { } get { return _window } } } fileprivate class ModernPictureInPictureVideoWindow: NSPanel { private let saver: WindowSaver fileprivate let _window: Window fileprivate let control: PictureInPictureControl private let rect:NSRect private let restoreRect: NSRect fileprivate var forcePaused: Bool = false fileprivate let item: MGalleryItem fileprivate weak var _delegate: InteractionContentViewProtocol? fileprivate let _contentInteractions:ChatMediaLayoutParameters? fileprivate let _type: GalleryAppearType fileprivate let viewer: GalleryViewer fileprivate var eventLocalMonitor: Any? fileprivate var eventGlobalMonitor: Any? private var hideAnimated: Bool = true private let lookAtMessageDisposable = MetaDisposable() init(_ control: PictureInPictureControl, item: MGalleryItem, viewer: GalleryViewer, origin:NSPoint, delegate:InteractionContentViewProtocol? = nil, contentInteractions:ChatMediaLayoutParameters? = nil, type: GalleryAppearType) { self.viewer = viewer self._delegate = delegate self._contentInteractions = contentInteractions self._type = type self.control = control let minSize = control.view.frame.size.aspectFilled(NSMakeSize(120, 120)) let size = item.notFittedSize.aspectFilled(NSMakeSize(250, 250)).aspectFilled(minSize) let newRect = NSMakeRect(origin.x, origin.y, size.width, size.height) self.rect = newRect self.restoreRect = NSMakeRect(origin.x, origin.y, control.view.frame.width, control.view.frame.height) self.item = item _window = Window(contentRect: newRect, styleMask: [.resizable], backing: .buffered, defer: true) _window.name = "pip" self.saver = .find(for: _window) _window.setFrame(NSMakeRect(3000, 3000, saver.rect.width, saver.rect.height), display: true) super.init(contentRect: newRect, styleMask: [.resizable, .nonactivatingPanel], backing: .buffered, defer: true) //self.isOpaque = false self.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]; let view = PictureInpictureView(frame: bounds, window: _window) self.contentView = view view.forceMouseDownCanMoveWindow = true // self.contentView?.wantsLayer = true; self.contentView?.layer?.cornerRadius = 4; self.backgroundColor = .clear; control.view.frame = NSMakeRect(0, 0, newRect.width, newRect.height) // control.view.autoresizingMask = [.width, .height]; control.view.setFrameOrigin(0, 0) // contentView?.autoresizingMask = [.width, .height] contentView?.addSubview(control.view) _window.set(mouseHandler: { event -> KeyHandlerResult in NSCursor.arrow.set() return .invoked }, with: self, for: .mouseMoved, priority: .low) _window.set(mouseHandler: { event -> KeyHandlerResult in NSCursor.arrow.set() return .invoked }, with: self, for: .mouseEntered, priority: .low) _window.set(mouseHandler: { event -> KeyHandlerResult in return .invoked }, with: self, for: .mouseExited, priority: .low) _window.set(mouseHandler: { [weak self] event -> KeyHandlerResult in if event.clickCount == 2, let strongSelf = self { let inner = strongSelf.control.view.convert(event.locationInWindow, from: nil) if NSWindow.windowNumber(at: NSEvent.mouseLocation, belowWindowWithWindowNumber: 0) == strongSelf.windowNumber, strongSelf.control.view.hitTest(inner) is MediaPlayerView { strongSelf.hide() } } return .invoked }, with: self, for: .leftMouseDown, priority: .low) _window.set(mouseHandler: { [weak self] event -> KeyHandlerResult in self?.findAndMoveToCorner() return .rejected }, with: self, for: .leftMouseUp, priority: .low) self.level = .modalPanel self.isMovableByWindowBackground = true NotificationCenter.default.addObserver(self, selector: #selector(windowDidResized(_:)), name: NSWindow.didResizeNotification, object: self) eventLocalMonitor = NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in guard let `self` = self else {return event} self._window.sendEvent(event) return event }) eventGlobalMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in guard let `self` = self else {return} self._window.sendEvent(event) }) if let message = item.entry.message { let messageView = item.context.account.postbox.messageView(message.id) |> deliverOnMainQueue lookAtMessageDisposable.set(messageView.start(next: { [weak self] view in if view.message == nil { self?.hideAnimated = true self?.hide() } })) } self.control.setMode(.pip, animated: true) } func hide() { if hideAnimated { contentView?._change(opacity: 0, animated: true, duration: 0.1, timingFunction: .linear) setFrame(NSMakeRect(frame.minX + (frame.width - 0) / 2, frame.minY + (frame.height - 0) / 2, 0, 0), display: true, animate: true) } orderOut(nil) window = nil _window.removeAllHandlers(for: self) if let monitor = eventLocalMonitor { NSEvent.removeMonitor(monitor) } if let monitor = eventGlobalMonitor { NSEvent.removeMonitor(monitor) } } override func orderOut(_ sender: Any?) { super.orderOut(sender) window = nil if control.isPictureInPicture { control.pause() } } func openGallery() { setFrame(restoreRect, display: true, animate: true) hideAnimated = false hide() showGalleryFromPip(item: item, gallery: self.viewer, delegate: _delegate, contentInteractions: _contentInteractions, type: _type) } deinit { if control.isPictureInPicture { control.pause() } self.control.setMode(.normal, animated: true) NotificationCenter.default.removeObserver(self) lookAtMessageDisposable.dispose() } override func animationResizeTime(_ newFrame: NSRect) -> TimeInterval { return 0.2 } @objc func windowDidResized(_ notification: Notification) { } private func findAndMoveToCorner() { if let screen = self.screen { let rect = screen.frame.offsetBy(dx: -screen.visibleFrame.minX, dy: -screen.visibleFrame.minY) let point = self.frame.offsetBy(dx: -screen.visibleFrame.minX, dy: -screen.visibleFrame.minY) var options:BorderType = [] if point.maxX > rect.width && point.minX < rect.width { options.insert(.Right) } if point.minX < 0 { options.insert(.Left) } if point.minY < 0 { options.insert(.Bottom) } var newFrame = self.frame if options.contains(.Right) { newFrame.origin.x = screen.visibleFrame.maxX - newFrame.width - 30 } if options.contains(.Bottom) { newFrame.origin.y = screen.visibleFrame.minY + 30 } if options.contains(.Left) { newFrame.origin.x = screen.visibleFrame.minX + 30 } setFrame(newFrame, display: true, animate: true) } } override var isResizable: Bool { return true } override func setFrame(_ frameRect: NSRect, display flag: Bool, animate animateFlag: Bool) { super.setFrame(frameRect, display: flag, animate: animateFlag) saver.rect = frameRect saver.save() } override func makeKeyAndOrderFront(_ sender: Any?) { super.makeKeyAndOrderFront(sender) if let screen = NSScreen.main { let savedRect: NSRect = NSMakeRect(0, 0, screen.frame.width * 0.3, screen.frame.width * 0.3) let convert_s = self.rect.size.aspectFilled(NSMakeSize(min(savedRect.width, 250), min(savedRect.height, 250))) self.aspectRatio = self.rect.size.fitted(NSMakeSize(savedRect.width, savedRect.height)) self.minSize = self.rect.size.aspectFitted(NSMakeSize(savedRect.width, savedRect.height)).aspectFilled(NSMakeSize(120, 120)) let frame = NSScreen.main?.frame ?? NSMakeRect(0, 0, 1920, 1080) self.maxSize = self.rect.size.aspectFitted(frame.size) var rect = saver.rect.size.bounds rect.origin = NSMakePoint(screen.frame.width - convert_s.width - 30, screen.frame.height - convert_s.height - 50) self.setFrame(NSMakeRect(saver.rect.minX, saver.rect.minY, convert_s.width, convert_s.height), display: true, animate: true) } } } private var window: NSWindow? var hasPictureInPicture: Bool { return window != nil } func showPipVideo(control: PictureInPictureControl, viewer: GalleryViewer, item: MGalleryItem, origin: NSPoint, delegate:InteractionContentViewProtocol? = nil, contentInteractions:ChatMediaLayoutParameters? = nil, type: GalleryAppearType) { closePipVideo() window = ModernPictureInPictureVideoWindow(control, item: item, viewer: viewer, origin: origin, delegate: delegate, contentInteractions: contentInteractions, type: type) window?.makeKeyAndOrderFront(nil) } func exitPictureInPicture() { if let window = window as? ModernPictureInPictureVideoWindow { window.openGallery() } } func pausepip() { if let window = window as? ModernPictureInPictureVideoWindow { window.control.pause() window.forcePaused = true } } func playPipIfNeeded() { if let window = window as? ModernPictureInPictureVideoWindow, window.forcePaused { window.control.play() } } func closePipVideo() { if let window = window as? ModernPictureInPictureVideoWindow { window.hide() window.control.pause() } window = nil }
gpl-2.0
nalck/Barliman
cocoa/BarlimanTests/BarlimanTests.swift
1
973
// // BarlimanTests.swift // Barliman // // Created by William Byrd on 5/14/16. // Copyright © 2016 William E. Byrd. // Released under MIT License (see LICENSE file) import XCTest class BarlimanTests: 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.measure { // Put the code you want to measure the time of here. } } }
mit
zhangao0086/DKPhotoGallery
DKPhotoGallery/Transition/DKPhotoGalleryTransitionController.swift
2
2079
// // DKPhotoGalleryTransitionController.swift // DKPhotoGallery // // Created by ZhangAo on 09/09/2017. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit open class DKPhotoGalleryTransitionController: UIPresentationController, UIViewControllerTransitioningDelegate { open var gallery: DKPhotoGallery! internal var interactiveController: DKPhotoGalleryInteractiveTransition? init(gallery: DKPhotoGallery, presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) self.gallery = gallery } internal func prepareInteractiveGesture() { self.interactiveController = DKPhotoGalleryInteractiveTransition(gallery: self.gallery) } // MARK: - UIViewControllerTransitioningDelegate public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let presentAnimator = DKPhotoGalleryTransitionPresent() presentAnimator.gallery = self.gallery return presentAnimator } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let dismissAnimator = DKPhotoGalleryTransitionDismiss() dismissAnimator.gallery = self.gallery return dismissAnimator } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if let interactiveController = self.interactiveController, interactiveController.isInteracting { return interactiveController } else { return nil } } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return nil } }
mit
crspybits/SyncServerII
Sources/Server/Configuration/Configuration.swift
1
2211
// // Configuration.swift // Server // // Created by Christopher G Prince on 9/10/19. // // Server startup configuration info. import LoggerAPI import Foundation import PerfectLib class Configuration { let deployedGitTag:String // The following file is assumed to be at the root of the running, deployed server-- e.g., I'm putting it there when I build the Docker image. File is assumed to contain one line of text. private let deployedGitTagFilename = "VERSION" static private(set) var server: ServerConfiguration! static private(set) var misc:Configuration! #if DEBUG static private(set) var test:TestConfiguration? #endif /// testConfigFileFullPath is only for testing, with the DEBUG compilation flag on. static func setup(configFileFullPath:String, testConfigFileFullPath:String? = nil) throws { misc = try Configuration(configFileFullPath:configFileFullPath, testConfigFileFullPath: testConfigFileFullPath) } private init(configFileFullPath:String, testConfigFileFullPath:String? = nil) throws { Log.info("Loading config file: \(configFileFullPath)") let decoder = JSONDecoder() let url = URL(fileURLWithPath: configFileFullPath) let data = try Data(contentsOf: url) Configuration.server = try decoder.decode(ServerConfiguration.self, from: data) #if DEBUG if let testConfigFileFullPath = testConfigFileFullPath { let testConfigUrl = URL(fileURLWithPath: testConfigFileFullPath) let testConfigData = try Data(contentsOf: testConfigUrl) Configuration.test = try decoder.decode(TestConfiguration.self, from: testConfigData) } #endif let file = File(deployedGitTagFilename) try file.open(.read, permissions: .readUser) defer { file.close() } let tag = try file.readString() // In case the line in the file had trailing white space (e.g., a new line) self.deployedGitTag = tag.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } #if DEBUG static func setupLoadTestingCloudStorage() { server.setupLoadTestingCloudStorage() } #endif }
mit
kpiteira/MobileAzureDevDays
Swift/MobileAzureDevDays/MobileAzureDevDays/SentimentClient.swift
1
3299
// // SentimentClient.swift // MobileAzureDevDays // // Created by Colby Williams on 9/22/17. // Copyright © 2017 Colby Williams. All rights reserved. // import Foundation import UIKit class SentimentClient { static let shared: SentimentClient = { let instance = SentimentClient() return instance }() let textId = "sentimentText" let contentType = "application/json" let endpoint = "https://%@.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment" let apiKeyPreference = "\(Bundle.main.bundleIdentifier ?? "cognitive.text").apiKey" let regionPreference = "\(Bundle.main.bundleIdentifier ?? "cognitive.text").region" var apiKey: String? { get { return UserDefaults.standard.string(forKey: apiKeyPreference) } set(val) { UserDefaults.standard.set(val, forKey: apiKeyPreference) } } var region: String? { get { return UserDefaults.standard.string(forKey: regionPreference)! } set(val) { UserDefaults.standard.set(val, forKey: regionPreference) } } init(){ region = "eastus2" } func obtainKey(callback: @escaping (SentimentApiKeyDocument?) -> ()) { let url = URL(string: "https://vsmcsentimentdemo.azurewebsites.net/api/GetSentimentKey") var request = URLRequest(url: url!) request.httpMethod = "GET" request.addValue(contentType, forHTTPHeaderField: "Content-Type") UIApplication.shared.isNetworkActivityIndicatorVisible = true URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { print(error.localizedDescription) } if let data=data, let keyData = try? JSONSerialization.jsonObject(with: data) as? [String:Any], let keyJson = keyData { DispatchQueue.main.async { callback(SentimentApiKeyDocument(fromJson: keyJson)) } } else { DispatchQueue.main.async { callback(nil) } } }.resume() } func determineSentiment(_ text:String, callback: @escaping (SentimentResponse?) -> ()) { if let apiKey = apiKey, let region = region, let data = try? JSONSerialization.data(withJSONObject: [ "documents" : [ [ "language" : Locale.current.languageCode ?? "en", "id" : textId, "text" : text ] ] ], options: []) { let url = URL(string: String(format: endpoint, region)) var request = URLRequest(url: url!) request.httpMethod = "POST" request.addValue(contentType, forHTTPHeaderField: "Content-Type") request.addValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key") request.httpBody = data UIApplication.shared.isNetworkActivityIndicatorVisible = true URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } if let error = error { print(error.localizedDescription) } if let data = data, let sentimentData = try? JSONSerialization.jsonObject(with: data) as? [String:Any], let sentimentJson = sentimentData { DispatchQueue.main.async { callback(SentimentResponse(fromJson: sentimentJson)) } } else { DispatchQueue.main.async { callback(nil) } } }.resume() } } }
mit
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/Samples/MenuId.swift
1
1029
// // MenuId.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import UIKit import Result import ReactiveSwift import FontAwesome enum MenuId: Int { case friends = 0 case chats = 1 case home = 2 case settings = 3 case profile = 10 case help = 11 static let allMenuIds = [0...3, 10...11].flatMap { $0.flatMap { MenuId(rawValue: $0) } } var fontAwesome: FontAwesome { switch self { case .friends: return .users case .chats: return .comment case .home: return .home case .settings: return .gear case .profile: return .user case .help: return .question } } var tabImage: UIImage { return UIImage.fontAwesomeIcon( name: self.fontAwesome, textColor: UIColor.black, size: CGSize(width: 40, height: 40) ) } }
mit
GitNK/NCGraph
Graph/DFS.swift
1
6141
// // DFS.swift // NCGraph // // Created by Nikita Gromadskyi on 10/21/16. // Copyright © 2016 Nikita Gromadskyi. All rights reserved. // import Foundation extension NCGraph { /// A Boolean value indicating if `self` is directed acyclic graph public var isDAG :Bool { if edgeCount < 1 || !isDirected { return false } /// Set of deleted sink nodes var deleted = Set<Name>() /// Set of explored nodes var explored = Set<Name>() var hasCycle = false for node in nodes() { if !explored.contains(node.name){ dfsCycleFinder(sourceNode: node, explored: &explored, deleted: &deleted, hasCycle: &hasCycle) } if hasCycle {return false} /// Early exit } return !hasCycle } /// Checks if `self` is directed strongly connected graph public var isStronglyConnected: Bool { return scc()?.count == 1 } /// returns topologicaly sorted nodes for directed acyclic graph, nil if topological in not possible public func topSort() -> [NodeType]? { if !isDirected || !isDAG {return nil} var sortedNodes = [NodeType]() sortedNodes.reserveCapacity(nodeCount) var explored = Set<Name>() for node in nodes() { if !explored.contains(node.name) { dfs(sourceNode: node, explored: &explored, sortedNodes: &sortedNodes) } } return sortedNodes.reversed() } /// Method for finding strongly connected components /// of directed graph. /// - returns: 2d array representing strongly connected components, /// nil if none exist for `self` public func scc() -> [[NodeType]]? { if !isDirected || isEmpty {return nil} var _scc = [[NodeType]]() /// explored nodes var explored = Set<Name>() var newOrder = [NodeType]() /// first loop for node in nodes() { if !explored.contains(node.name) { dfsRev(sourceNode: node, explored: &explored, sortedNodes: &newOrder) } } /// reset explored nodes explored = Set<Name>() /// i-th strong component var strongComponent: [NodeType] /// second loop for node in newOrder.reversed() { if !explored.contains(node.name) { strongComponent = [NodeType]() dfs(sourceNode: node, explored: &explored, sortedNodes: &strongComponent) _scc.append(strongComponent) } } return _scc } //# MARK: - Private section private func dfs(sourceNode: NodeType, explored: inout Set<Name>, sortedNodes: inout [NodeType]) { /// stack of nodes var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let outEdges = self.outDegreeEdgesFor(node: current) else {fatalError()} for edge in outEdges { if !explored.contains(edge.head.name) { explored.insert(edge.head.name) nodesToProcess.append(edge.head) inserted = true break } } if !inserted { nodesToProcess.removeLast() sortedNodes.append(current) } } } /// DFS with reversed direction edges private func dfsRev(sourceNode: NodeType, explored: inout Set<Name>, sortedNodes: inout [NodeType]) { /// nodes stack var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let inEdges = self.inDegreeEdgesFor(node: current) else {fatalError()} for edge in inEdges { if !explored.contains(edge.tail.name) { explored.insert(edge.tail.name) nodesToProcess.append(edge.tail) inserted = true break } } if !inserted { nodesToProcess.removeLast() sortedNodes.append(current) } } } /// DFS Hepler for finding cycles in `self` private func dfsCycleFinder(sourceNode: NodeType, explored: inout Set<Name>, deleted: inout Set<Name>, hasCycle: inout Bool) { /// nodes stack var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let outEdges = self.outDegreeEdgesFor(node: current) else {fatalError()} for edge in outEdges { if !explored.contains(edge.head.name) { explored.insert(edge.head.name) nodesToProcess.append(edge.head) inserted = true break } else { /// check if head node has been marked as deleted if !deleted.contains(edge.head.name) { hasCycle = true } } } if !inserted { nodesToProcess.removeLast() deleted.insert(current.name) } } } }
mit
worthbak/crux-climber
CruxClimbing/AppDelegate.swift
1
2085
// // AppDelegate.swift // CruxClimbing // // Created by Worth Baker on 8/28/15. // Copyright © 2015 Worth Baker. 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
Xinext/RemainderCalc
src/RemainderCalc/PreferenceTableViewController.swift
1
2110
// // PreferenceTableViewController.swift // RemainderCalc // import UIKit class PreferenceTableViewController: UITableViewController { // MARK: - IBOutlet // Sound section @IBOutlet weak var outletTapButtonSoundLabel: UILabel! @IBOutlet weak var outletTapButtonSoundSwich: UISwitch! // MARK: - Private vriable // Each section title text var sectionTitleArray: Array<String> = Array() // MARK: - ViewController Override /** View生成時に呼び出されるイベントハンドラー */ override func viewDidLoad() { super.viewDidLoad() // 各アイテムの初期化 localizeEachItem() // ローカライズ } /** Viewが表示される直前に呼び出されるイベントハンドラー */ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Reflected the latest setting to ViewItem outletTapButtonSoundSwich.isOn = AppPreference.GetButtonPushedSound() } /** メモリー警告 */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** localize each item */ private func localizeEachItem() { outletTapButtonSoundLabel.text = NSLocalizedString("STR_PREF_TAP_BUTTON_LABEL", comment: "Tap the button.") sectionTitleArray.removeAll() sectionTitleArray += [NSLocalizedString("STR_PREF_SUBTITLE_SOUND", comment: "Sound")] } // MARK: - IBAction /** [action]ボタンタップ音スイッチの切り替え */ @IBAction func actionTapButtonSoundSwich_ValueChange(_ sender: Any) { AppPreference.SetButtonPushedSound(value: outletTapButtonSoundSwich.isOn) } // MARK: - Table view data source // Sectioのタイトル設定 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitleArray[section] } }
mit
SvenTiigi/PerfectAPIClient
Sources/PerfectAPIClient/Models/APIClientError.swift
1
2572
// // APIClientError.swift // PerfectAPIClient // // Created by Sven Tiigi on 09.01.18. // /// APIClientError /// /// - mappingFailed: The mapping failed /// - badResponseStatus: Retrieved bad response status /// - connectionFailed: The connection failed public enum APIClientError { /// APIClient failed on mapping case mappingFailed( reason: String, response: APIClientResponse ) /// APIClient did retrieved bad response status case badResponseStatus( response: APIClientResponse ) /// The connection failed case connectionFailed( error: Error, request: APIClientRequest ) } // MARK: Error Extension extension APIClientError: Error { /// The localized APIClientError Description public var localizedDescription: String { switch self { case .mappingFailed(reason: let reason, response: let response): return "\(reason) | Response: \(response)" case .badResponseStatus(response: let response): return "Retrieved bad response code: \(response.status.code) | Response: \(response)" case .connectionFailed(error: let error, request: let request): return "\(error.localizedDescription) | Request: \(request)" } } } // MARK: Analysis Extension public extension APIClientError { /// Perform APIClientError Analysis /// /// - Parameters: /// - mappingFailed: Invoked when error is mappingFailed /// - badResponseStatus: Invoked when error is badResponseStatus /// - connectionFailed: Invoked when error is connectionFailed func analysis(mappingFailed: ((String, APIClientResponse) -> Void)?, badResponseStatus: ((APIClientResponse) -> Void)?, connectionFailed: ((Error, APIClientRequest) -> Void)?) { // Switch on self switch self { case .mappingFailed(reason: let reason, response: let response): guard let mappingFailed = mappingFailed else { return } mappingFailed(reason, response) case .badResponseStatus(response: let response): guard let badResponseStatus = badResponseStatus else { return } badResponseStatus(response) case .connectionFailed(error: let error, request: let request): guard let connectionFailed = connectionFailed else { return } connectionFailed(error, request) } } }
mit
sarvex/SwiftRecepies
Motion/Retrieving Pedometer Data/Retrieving Pedometer Data/AppDelegate.swift
1
3612
// // AppDelegate.swift // Retrieving Pedometer Data // // Created by vandad on 177//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // /* 1 */ //import UIKit //import CoreMotion // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // lazy var pedometer = CMPedometer() // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: // [NSObject : AnyObject]?) -> Bool { // return true // } // // func applicationDidBecomeActive(application: UIApplication) { // if CMPedometer.isStepCountingAvailable(){ // // pedometer.startPedometerUpdatesFromDate(NSDate(), withHandler: { // (data: CMPedometerData!, error: NSError!) in // // println("Number of steps = \(data.numberOfSteps)") // // }) // // } else { // println("Step counting is not available") // } // } // // func applicationWillResignActive(application: UIApplication) { // pedometer.stopPedometerUpdates() // } // //} /* 2 */ //import UIKit //import CoreMotion // ///* A really simple extension on NSDate that gives us convenience methods //for "now" and "yesterday" */ //extension NSDate{ // class func now() -> NSDate{ // return NSDate() // } // class func yesterday() -> NSDate{ // return NSDate(timeIntervalSinceNow: -(24 * 60 * 60)) // } //} // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // lazy var pedometer = CMPedometer() // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: // [NSObject : AnyObject]?) -> Bool { // return true // } // // func applicationDidBecomeActive(application: UIApplication) { // // /* Can we ask for distance updates? */ // if CMPedometer.isDistanceAvailable(){ // // pedometer.queryPedometerDataFromDate(NSDate.yesterday(), // toDate: NSDate.now(), // withHandler: {(data: CMPedometerData!, error: NSError!) in // // println("Distance travelled from yesterday to now " + // "= \(data.distance) meters") // // }) // // } else { // println("Distance counting is not available") // } // } // // func applicationWillResignActive(application: UIApplication) { // pedometer.stopPedometerUpdates() // } // //} /* 3 */ import UIKit import CoreMotion extension NSDate{ class func now() -> NSDate{ return NSDate() } class func tenMinutesAgo() -> NSDate{ return NSDate(timeIntervalSinceNow: -(10 * 60)) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var pedometer = CMPedometer() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { return true } func applicationDidBecomeActive(application: UIApplication) { /* Can we ask for floor climb/descending updates? */ if CMPedometer.isFloorCountingAvailable(){ pedometer.queryPedometerDataFromDate(NSDate.tenMinutesAgo(), toDate: NSDate.now(), withHandler: {(data: CMPedometerData!, error: NSError!) in println("Floors ascended = \(data.floorsAscended)") println("Floors descended = \(data.floorsAscended)") }) } else { println("Floor counting is not available") } } func applicationWillResignActive(application: UIApplication) { pedometer.stopPedometerUpdates() } }
isc
IvanVorobei/Sparrow
sparrow/modules/rate-app/types/dialog/banner-with-indicator/data-source/SPRateAppBannerWithIndicatorDataSource.swift
2
2135
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // 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 open class SPRateAppBannerWithIndicatorDataSource: NSObject, SPRateAppBannerWithIndicatorDataSourceInterface { public func titleFirstStageOnAlert() -> String { return "You are enjoy with app?" } public func titleButtonFirstStage() -> String { return "Enjoy" } public func titleFirstStageOnList() -> String { return "You are enjoy with app" } public func titleSecondStageOnAlert() -> String { return "Rate App in AppStore?" } public func titleButtonSecondStage() -> String { return "Rate" } public func titleSecondStageOnList() -> String { return "You want rate app in AppStore" } public func bottomAdviceTitle() -> String { return "Swipe to hide" } public func mainColor() -> UIColor { return SPStyleKit.baseColor() } public func secondColor() -> UIColor { return UIColor.white } }
mit
64characters/Telephone
UseCases/SoundEventTarget.swift
1
721
// // SoundEventTarget.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public protocol SoundEventTarget { func didFinishPlaying(_ sound: Sound) }
gpl-3.0
yannickl/AwaitKit
Example/Example/AppDelegate.swift
1
2122
// // AppDelegate.swift // AwaitKitExample // // Created by Yannick LORIOT on 18/05/16. // Copyright © 2016 Yannick Loriot. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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
ryansong/cameraPhotoDemo
cameraPhotoDemo/SYBCollectionViewCell.swift
1
808
// // SYBCollectionViewCell.swift // cameraPhotoDemo // // Created by Ryan on 5/2/17. // Copyright © 2017 Song Xiaoming. All rights reserved. // import UIKit class SYBCollectionViewCell: UICollectionViewCell { let imageView:UIImageView = UIImageView() override func layoutSubviews() { super.layoutSubviews() self.imageView.frame = self.bounds } func setupCell(model:SYBImageAssetModel) -> Void { self.imageView.image = model.image if (model.image == nil && model.imageAsset != nil) { model.image = model.imageAsset?.image(with: self.traitCollection) self.imageView.image = model.image } } override func prepareForReuse() { self.imageView.image = nil; } }
mit
gregomni/swift
test/Constraints/diagnostics.swift
2
71113
// RUN: %target-typecheck-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: @escaping (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } // expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}} // expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}} // expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}} // expected-note@-4 {{where 'T' = 'Int'}} func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}} i) // expected-error{{extra argument in call}} // Cannot conform to protocols. f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}} func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}} return (c: 0, i: g(())) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}} return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} // expected-note@-1 {{required by global function 'f8' where 'T' = '(Int, Double)'}} f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{type '(Int, Double)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } precedencegroup Starry { associativity: left higherThan: MultiplicationPrecedence } infix operator **** : Starry func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ : Starry func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}} _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> func rdar20142523() { _ = myMap(0..<10, { x in // expected-error {{'myMap' is unavailable: call the 'map()' method on the sequence}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral func rdar21080030() { var s = "Hello" // SR-7599: This should be `cannot_call_non_function_value` if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} expected-note {{did you mean to add a return type?}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}} // expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}} _ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'any r21553065Protocol' be a class type}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{cannot find type 'Nail' in scope}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer type of a closure parameter '$0' in the current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // Diagnose passing an array in lieu of variadic parameters func variadic(_ x: Int...) {} func variadicArrays(_ x: [Int]...) {} func variadicAny(_ x: Any...) {} struct HasVariadicSubscript { subscript(_ x: Int...) -> Int { get { 0 } } } let foo = HasVariadicSubscript() let array = [1,2,3] let arrayWithOtherEltType = ["hello", "world"] variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}} variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic(0, [1,2,3], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} variadic(0, [1,2,3,], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} {{20-21=}} variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} // FIXME: SR-11104 variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}} // expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-2 {{remove brackets to pass array elements directly}} variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}} foo[0, [1,2,3], 4] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{8-9=}} {{14-15=}} variadicAny(array) variadicAny([1,2,3]) variadicArrays(array) variadicArrays([1,2,3]) variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}} protocol Proto {} func f<T: Proto>(x: [T]) {} func f(x: Int...) {} f(x: [1,2,3]) // TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads. // expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-3 {{remove brackets to pass array elements directly}} // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // rdar://19804707 - trailing closures for contextual member references. knownOps = .BinaryOperator(){$1 - $0} knownOps = .BinaryOperator{$1 - $0} _ = knownOps } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func frob(_ a : Int, b : inout Int) -> Color {} static var svar: Color { return .Red } } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error@-1 {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}} // expected-error@-2 {{cannot infer contextual base in reference to member 'Unknown'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}} let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}} // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}} let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function that produces expected type 'Color'; did you mean to call it?}} {{25-25=()}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}} let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}} someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{use of extraneous '&'}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type '(any r22020088P)?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } class GenClass<T> {} struct GenStruct<T> {} enum GenEnum<T> {} func test(_ a : B) { B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, nil) // expected-error {{missing argument label 'a:' in call}} // expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}} a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} func foo1(_ arg: Bool) -> Int {return nil} func foo2<T>(_ arg: T) -> GenClass<T> {return nil} func foo3<T>(_ arg: T) -> GenStruct<T> {return nil} func foo4<T>(_ arg: T) -> GenEnum<T> {return nil} // expected-error@-4 {{'nil' is incompatible with return type 'Int'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}} let clsr1: () -> Int = {return nil} let clsr2: () -> GenClass<Bool> = {return nil} let clsr3: () -> GenStruct<String> = {return nil} let clsr4: () -> GenEnum<Double?> = {return nil} // expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}} var number = 0 var genClassBool = GenClass<Bool>() var funcFoo1 = foo1 number = nil genClassBool = nil funcFoo1 = nil // expected-error@-3 {{'nil' cannot be assigned to type 'Int'}} // expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}} // expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) // TODO(diagnostics): This is a regression from diagnosing missing optional unwrap for `a`, we have to // re-think the way errors in tuple elements are detected because it's currently impossible to detect // exactly what went wrong here and aggregate fixes for different elements at the same time. _ = MyTuple(42, a) // expected-error {{tuple type '(_const Int, String?)' is not convertible to tuple type 'MyTuple' (aka '(Int, String)')}} } // rdar://71829040 - "ambiguous without more context" error for tuple type mismatch. func r71829040() { func object(forKey: String) -> Any? { nil } let flags: [String: String] // expected-error@+1 {{tuple type '(String, Bool)' is not convertible to tuple type '(String, String)'}} flags = Dictionary(uniqueKeysWithValues: ["keyA", "keyB"].map { ($0, object(forKey: $0) as? Bool ?? false) }) } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String where T.Iterator.Element == String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-1{{chain the optional }} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}} // expected-note@-1{{chain the optional }} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}} _ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } // FIXME(rdar://problem/65688291) - on iOS simulator this diagnostic is flaky, // either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires` if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{requires that 'AssocTest' conform to 'Equatable'}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 _ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}} a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } postfix operator +++ postfix func +++ <T>(_: inout T) -> T { fatalError() } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} _ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}} } // SR-1594: Wrong error description when using === on non-class types class SR1594 { func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) { _ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}} _ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}} _ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } } func nilComparison(i: Int, o: AnyObject) { _ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} _ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} // FIXME(integers): uncomment these tests once the < is no longer ambiguous // _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} _ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } // <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion func testImplConversion(a : Float?) -> Bool {} func testImplConversion(a : Int?) -> Bool { let someInt = 42 let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }} // expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}} } // <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands class Foo23752537 { var title: String? var message: String? } extension Foo23752537 { func isEquivalent(other: Foo23752537) { // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" // expected-error@+1 {{unexpected non-void return value in void function}} return (self.title != other.title && self.message != other.message) // expected-note {{did you mean to add a return type?}} } } // <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" func rdar27391581(_ a : Int, b : Int) -> Int { return a == b && b != 0 // expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read<T : BinaryInteger>() -> T? { var buffer : T let n = withUnsafeMutablePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}} } // <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context func rdar24202058(a : Int) { return a <= 480 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // SR-1752: Warning about unused result with ternary operator struct SR1752 { func foo() {} } let sr1752: SR1752? true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void // Make sure RawRepresentable fix-its don't crash in the presence of type variables class NSCache<K, V> { func object(forKey: K) -> V? {} } class CacheValue { func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}} func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{no exact matches in reference to instance method 'value'}} } // SR-1255 func foo1255_1() { return true || false // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } func foo1255_2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // Diagnostic message for initialization with binary operations as right side let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}} let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}} let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} // SR-2208 struct Foo2208 { func bar(value: UInt) {} } func test2208() { let foo = Foo2208() let a: Int = 1 let b: Int = 2 let result = a / b foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: UInt(result)) // Ok } // SR-2164: Erroneous diagnostic when unable to infer generic type struct SR_2164<A, B> { // expected-note 4 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}} init(a: A) {} init(b: B) {} init(c: Int) {} init(_ d: A) {} init(e: A?) {} } struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}} init(_ a: [A]) {} } struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}} init(a: [A: Double]) {} } SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(c: 2) // expected-error@-1 {{generic parameter 'A' could not be inferred}} // expected-error@-2 {{generic parameter 'B' could not be inferred}} // expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<Any, Any>}} SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} let _ = SR_2164<Int, Bool>(a: 0) // Ok let _ = SR_2164<Int, Bool>(b: true) // Ok SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} // <rdar://problem/29850459> Swift compiler misreports type error in ternary expression let r29850459_flag = true let r29850459_a: Int = 0 let r29850459_b: Int = 1 func r29850459() -> Bool { return false } let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} // SR-6272: Tailored diagnostics with fixits for numerical conversions func SR_6272_a() { enum Foo: Int { case bar } // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}} let _: Int = Foo.bar.rawValue * Float(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}} let _: Float = Foo.bar.rawValue * Float(0) // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} Foo.bar.rawValue * Float(0) } func SR_6272_b() { let lhs = Float(3) let rhs = Int(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}} let _: Float = lhs * rhs // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}} let _: Int = lhs * rhs // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} lhs * rhs } func SR_6272_c() { // expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}} Int(3) * "0" struct S {} // expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}} Int(10) * S() } struct SR_6272_D: ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral: Int) {} static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } } func SR_6272_d() { let x: Float = 1.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x // expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{50-50=Int(}} {{54-54=)}} let _: Float = SR_6272_D(integerLiteral: 42) + 42.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0 } // Ambiguous overload inside a trailing closure func ambiguousCall() -> Int {} // expected-note {{found this candidate}} func ambiguousCall() -> Float {} // expected-note {{found this candidate}} func takesClosure(fn: () -> ()) {} takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}} // SR-4692: Useless diagnostics calling non-static method class SR_4692_a { private static func foo(x: Int, y: Bool) { self.bar(x: x) // expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}} } private func bar(x: Int) { } } class SR_4692_b { static func a() { self.f(x: 3, y: true) // expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}} } private func f(a: Int, b: Bool, c: String) { self.f(x: a, y: b) } private func f(x: Int, y: Bool) { } } // rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful struct R32101765 { let prop32101765 = 0 } let _: KeyPath<R32101765, Float> = \.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} // rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}} _ = i + 1 } // SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error func sr5045() { let doubles: [Double] = [1, 2, 3] return doubles.reduce(0, +) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // rdar://problem/32934129 - QoI: misleading diagnostic class L_32934129<T : Comparable> { init(_ value: T) { self.value = value } init(_ value: T, _ next: L_32934129<T>?) { self.value = value self.next = next } var value: T var next: L_32934129<T>? = nil func length() -> Int { func inner(_ list: L_32934129<T>?, _ count: Int) { guard let list = list else { return count } // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} return inner(list.next, count + 1) } return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}} } } // rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type class C_31671195 { var name: Int { fatalError() } func name(_: Int) { fatalError() } } C_31671195().name(UInt(0)) // expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}} // rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type class AST_28456467 { var hasStateDef: Bool { return false } } protocol Expr_28456467 {} class ListExpr_28456467 : AST_28456467, Expr_28456467 { let elems: [Expr_28456467] init(_ elems:[Expr_28456467] ) { self.elems = elems } override var hasStateDef: Bool { return elems.first(where: { $0.hasStateDef }) != nil // expected-error@-1 {{value of type 'any Expr_28456467' has no member 'hasStateDef'}} } } func sr5081() { var a = ["1", "2", "3", "4", "5"] var b = [String]() b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}} } // TODO(diagnostics):Figure out what to do when expressions are complex and completely broken func rdar17170728() { var i: Int? = 1 var j: Int? var k: Int? = 2 let _ = [i, j, k].reduce(0 as Int?) { $0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil)) // expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} } let _ = [i, j, k].reduce(0 as Int?) { // expected-error {{missing argument label 'into:' in call}} // expected-error@-1 {{cannot convert value of type 'Int?' to expected argument type '(inout @escaping (Bool, Bool) -> Bool?, Int?) throws -> ()'}} $0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil)) // expected-error@-1 {{binary operator '+' cannot be applied to two 'Bool' operands}} } } // https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad // generic constraints func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}} func platypus<T>(a: [T]) { _ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}} } // Another case of the above. func badTypes() { let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }} // Notes, attached to declarations, explain that there is a difference between Array.init(_:) and // RangeReplaceableCollection.init(_:) which are both applicable in this case. let array = [Int](sequence) // expected-error@-1 {{no exact matches in call to initializer}} } // rdar://34357545 func unresolvedTypeExistential() -> Bool { return (Int.self==_{}) // expected-error@-1 {{type of expression is ambiguous without more context}} // expected-error@-2 {{type placeholder not allowed here}} } do { struct Array {} let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}} // expected-error@-1 {{generic parameter 'Element' could not be inferred}} struct Error {} let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} } // SyntaxSugarTypes with unresolved types func takesGenericArray<T>(_ x: [T]) {} takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}} func takesNestedGenericArray<T>(_ x: [[T]]) {} takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}} func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {} takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}} func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {} takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}} func takesArrayOfGenericOptionals<T>(_ x: [T?]) {} takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}} func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}} takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // expected-error@-2 {{generic parameter 'U' could not be inferred}} typealias Z = Int func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}} takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}} takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}} takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // Void function returns non-void result fix-it func voidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{16-16= -> <#Return Type#>}} } func voidFuncWithArgs(arg1: Int) { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{33-33= -> <#Return Type#>}} } func voidFuncWithCondFlow() { if Bool.random() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } else { return 2 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } } func voidFuncWithNestedVoidFunc() { func nestedVoidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{24-24= -> <#Return Type#>}} } } func voidFuncWithEffects1() throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{35-35= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects2() async throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) // expected-error@+1 {{'async' must precede 'throws'}} func voidFuncWithEffects3() throws async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects4() async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{34-34= -> <#Return Type#>}} } func voidFuncWithEffects5(_ closure: () throws -> Void) rethrows { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{65-65= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidGenericFuncWithEffects<T>(arg: T) async where T: CustomStringConvertible { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{49-49= -> <#Return Type#>}} } // Special cases: These should not offer a note + fix-it func voidFuncExplicitType() -> Void { return 1 // expected-error {{unexpected non-void return value in void function}} } class ClassWithDeinit { deinit { return 0 // expected-error {{unexpected non-void return value in void function}} } } class ClassWithVoidProp { var propertyWithVoidType: () { return 5 } // expected-error {{unexpected non-void return value in void function}} } class ClassWithPropContainingSetter { var propWithSetter: Int { get { return 0 } set { return 1 } // expected-error {{unexpected non-void return value in void function}} } } // https://bugs.swift.org/browse/SR-11964 struct Rect { let width: Int let height: Int } struct Frame { func rect(width: Int, height: Int) -> Rect { Rect(width: width, height: height) } let rect: Rect } func foo(frame: Frame) { frame.rect.width + 10.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} } // Make sure we prefer the conformance failure. func f11(_ n: Int) {} func f11<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} f11(3, f4) // expected-error {{global function 'f11' requires that 'Int' conform to 'P2'}} let f12: (Int) -> Void = { _ in } // expected-note {{candidate '(Int) -> Void' requires 1 argument, but 2 were provided}} func f12<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{candidate requires that 'Int' conform to 'P2' (requirement specified as 'T' : 'P2')}} f12(3, f4)// expected-error {{no exact matches in call to global function 'f12'}} // SR-12242 struct SR_12242_R<Value> {} struct SR_12242_T {} protocol SR_12242_P {} func fSR_12242() -> SR_12242_R<[SR_12242_T]> {} func genericFunc<SR_12242_T: SR_12242_P>(_ completion: @escaping (SR_12242_R<[SR_12242_T]>) -> Void) { let t = fSR_12242() completion(t) // expected-error {{cannot convert value of type 'diagnostics.SR_12242_R<[diagnostics.SR_12242_T]>' to expected argument type 'diagnostics.SR_12242_R<[SR_12242_T]>'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('diagnostics.SR_12242_T' and 'SR_12242_T') are expected to be equal}} } func assignGenericMismatch() { var a: [Int]? var b: [String] a = b // expected-error {{cannot assign value of type '[String]' to type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} b = a // expected-error {{cannot assign value of type '[Int]' to type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{value of optional type '[Int]?' must be unwrapped to a value of type '[Int]'}} // expected-note@-3 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-4 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } // [Int] to [String]? argument to param conversion let value: [Int] = [] func gericArgToParamOptional(_ param: [String]?) {} gericArgToParamOptional(value) // expected-error {{convert value of type '[Int]' to expected argument type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // Inout Expr conversions func gericArgToParamInout1(_ x: inout [[Int]]) {} func gericArgToParamInout2(_ x: inout [[String]]) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} } func gericArgToParamInoutOptional(_ x: inout [[String]]?) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]?' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} // expected-error@-2 {{value of optional type '[[String]]?' must be unwrapped to a value of type '[[String]]'}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func gericArgToParamInout(_ x: inout [[Int]]) { // expected-note {{change variable type to '[[String]]?' if it doesn't need to be declared as '[[Int]]'}} gericArgToParamInoutOptional(&x) // expected-error {{cannot convert value of type '[[Int]]' to expected argument type '[[String]]?'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{inout argument could be set to a value with a type other than '[[Int]]'; use a value declared as type '[[String]]?' instead}} } // SR-12725 struct SR12725<E> {} // expected-note {{arguments to generic parameter 'E' ('Int' and 'Double') are expected to be equal}} func generic<T>(_ value: inout T, _ closure: (SR12725<T>) -> Void) {} let arg: Int generic(&arg) { (g: SR12725<Double>) -> Void in } // expected-error {{cannot convert value of type '(SR12725<Double>) -> Void' to expected argument type '(SR12725<Int>) -> Void'}} // rdar://problem/62428353 - bad error message for passing `T` where `inout T` was expected func rdar62428353<T>(_ t: inout T) { let v = t // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} rdar62428353(v) // expected-error {{cannot pass immutable value as inout argument: 'v' is a 'let' constant}} } func rdar62989214() { struct Flag { var isTrue: Bool } @propertyWrapper @dynamicMemberLookup struct Wrapper<Value> { var wrappedValue: Value subscript<Subject>( dynamicMember keyPath: WritableKeyPath<Value, Subject> ) -> Wrapper<Subject> { get { fatalError() } } } func test(arr: Wrapper<[Flag]>, flag: Flag) { arr[flag].isTrue // expected-error {{cannot convert value of type 'Flag' to expected argument type 'Int'}} } } // SR-5688 func SR5688_1() -> String? { "" } SR5688_1!.count // expected-error {{function 'SR5688_1' was used as a property; add () to call it}} {{9-9=()}} func SR5688_2() -> Int? { 0 } let _: Int = SR5688_2! // expected-error {{function 'SR5688_2' was used as a property; add () to call it}} {{22-22=()}} // rdar://74696023 - Fallback error when passing incorrect optional type to `==` operator func rdar74696023() { struct MyError { var code: Int = 0 } func test(error: MyError?, code: Int32) { guard error?.code == code else { fatalError() } // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } } extension Int { static var optionalIntMember: Int? { 0 } static var optionalThrowsMember: Int? { get throws { 0 } } } func testUnwrapFixIts(x: Int?) throws { let _ = x + 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11=(}} {{12-12= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = (x ?? 0) + 2 let _ = 2 + x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{16-16= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 + (x ?? 0) func foo(y: Int) {} foo(y: x) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=!}} foo(y: x ?? 0) let _ = x < 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{12-12= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = x ?? 0 < 2 let _ = 2 < x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{16-16= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 < x ?? 0 let _: Int = (.optionalIntMember) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{35-35= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{35-35=!}} let _: Int = (.optionalIntMember ?? 0) let _ = 1 + .optionalIntMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{33-33= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{33-33=!}} let _ = 1 + (.optionalIntMember ?? 0) let _ = try .optionalThrowsMember + 1 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{36-36= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{36-36=!}} let _ = try (.optionalThrowsMember ?? 0) + 1 let _ = .optionalIntMember?.bitWidth > 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{39-39= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=(}} {{39-39=)!}} let _ = (.optionalIntMember?.bitWidth)! > 0 let _ = .optionalIntMember?.bitWidth ?? 0 > 0 let _ = .random() ? .optionalIntMember : 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{41-41= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{41-41=!}} let _ = .random() ? .optionalIntMember ?? 0 : 0 let _: Int = try try try .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{49-49= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{49-49=!}} let _: Int = try try try .optionalThrowsMember ?? 0 let _: Int = try! .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}} let _: Int = try! .optionalThrowsMember ?? 0 } func rdar86611718(list: [Int]) { String(list.count()) // expected-error@-1 {{cannot call value of non-function type 'Int'}} }
apache-2.0
ronlisle/XcodeViperTemplate
viperTests.xctemplate/Mock___FILEBASENAME___Interactor.swift
1
313
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import XCTest class MockInteractor : ___FILEBASENAME___InteractorInput { var was<methodname>Called = false internal func <methodName>() { was<methodName>Called = true } }
mit
Zewo/Zewo
Sources/Core/String/String.swift
1
3047
import Foundation extension Character { public var isASCII: Bool { return unicodeScalars.reduce(true, { $0 && $1.isASCII }) } public var isAlphabetic: Bool { return isLowercase || isUppercase } public var isDigit: Bool { return ("0" ... "9").contains(self) } } extension String { public func uppercasedFirstCharacter() -> String { let first = prefix(1).capitalized let other = dropFirst() return first + other } } extension CharacterSet { public static var urlAllowed: CharacterSet { let uppercaseAlpha = CharacterSet(charactersIn: "A" ... "Z") let lowercaseAlpha = CharacterSet(charactersIn: "a" ... "z") let numeric = CharacterSet(charactersIn: "0" ... "9") let symbols: CharacterSet = ["_", "-", "~", "."] return uppercaseAlpha .union(lowercaseAlpha) .union(numeric) .union(symbols) } } extension String { public func trimmed() -> String { let regex = try! NSRegularExpression(pattern: " +", options: .caseInsensitive) return regex.stringByReplacingMatches( in: self, options: [], range: NSRange(location: 0, length: utf8.count), withTemplate: " " ).trimmingCharacters(in: .whitespaces) } public func camelCaseSplit() -> [String] { var entries: [String] = [] var runes: [[Character]] = [] var lastClass = 0 var currentClass = 0 for character in self { switch true { case character.isLowercase: currentClass = 1 case character.isUppercase: currentClass = 2 case character.isDigit: currentClass = 3 default: currentClass = 4 } if currentClass == lastClass { var rune = runes[runes.count - 1] rune.append(character) runes[runes.count - 1] = rune } else { runes.append([character]) } lastClass = currentClass } // handle upper case -> lower case sequences, e.g. // "PDFL", "oader" -> "PDF", "Loader" if runes.count >= 2 { for i in 0 ..< runes.count - 1 { if runes[i][0].isUppercase && runes[i + 1][0].isLowercase { runes[i + 1] = [runes[i][runes[i].count - 1]] + runes[i + 1] runes[i] = Array(runes[i][..<(runes[i].count - 1)]) } } } for rune in runes where rune.count > 0 { entries.append(String(rune)) } return entries } } extension UUID : LosslessStringConvertible { public init?(_ string: String) { guard let uuid = UUID(uuidString: string) else { return nil } self = uuid } }
mit
taggon/highlight
Highlight/BaseWindow.swift
1
193
// // BaseWindow.swift // Highlight // // Created by Taegon Kim on 2017. 12. 23.. // Copyright © 2017년 Taegon Kim. All rights reserved. // import Cocoa class BaseWindow: NSWindow { }
mit
justinlevi/asymptotik-rnd-scenekit-kaleidoscope
Atk_Rnd_VisualToys/KaleidoscopeViewController.swift
1
25047
// // KaleidoscopeViewController.swift // Atk_Rnd_VisualToys // // Created by Rick Boykin on 8/4/14. // Copyright (c) 2014 Asymptotik Limited. All rights reserved. // import Foundation import UIKit import QuartzCore import SceneKit import Darwin import GLKit import OpenGLES import AVFoundation import CoreVideo import CoreMedia enum MirrorTextureSoure { case Image, Color, Video } enum RecordingStatus { case Stopped, Finishing, FinishRequested, Recording } class KaleidoscopeViewController: UIViewController, SCNSceneRendererDelegate, SCNProgramDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var settingsOffsetConstraint: NSLayoutConstraint! @IBOutlet weak var settingsWidthConstraint: NSLayoutConstraint! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var settingsContainerView: UIView! @IBOutlet weak var videoButton: UIButton! @IBOutlet weak var imageRecording: UIImageView! var textureSource = MirrorTextureSoure.Video var hasMirror = false var videoCapture = VideoCaptureBuffer() var videoRecorder:FrameBufferVideoRecorder? var videoRecordingTmpUrl: NSURL!; var recordingStatus = RecordingStatus.Stopped; var defaultFBO:GLint = 0 var snapshotRequested = false; private weak var settingsViewController:KaleidoscopeSettingsViewController? = nil var textureRotation:GLfloat = 0.0 var textureRotationSpeed:GLfloat = 0.1 var rotateTexture = false var screenTexture:ScreenTextureQuad? override func viewDidLoad() { super.viewDidLoad() // create a new scene let scene = SCNScene() // retrieve the SCNView let scnView = self.view as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = false // configure the view scnView.backgroundColor = UIColor.blackColor() // Anti alias scnView.antialiasingMode = SCNAntialiasingMode.Multisampling4X // delegate to self scnView.delegate = self scene.rootNode.runAction(SCNAction.customActionWithDuration(5, actionBlock:{ (triNode:SCNNode, elapsedTime:CGFloat) -> Void in })) // create and add a camera to the scene let cameraNode = SCNNode() let camera = SCNCamera() //camera.usesOrthographicProjection = true cameraNode.camera = camera scene.rootNode.addChildNode(cameraNode) scnView.pointOfView = cameraNode; // place the camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 15) cameraNode.pivot = SCNMatrix4MakeTranslation(0, 0, 0) // add a tap gesture recognizer //let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") //let pinchGesture = UIPinchGestureRecognizer(target: self, action: "handlePinch:") //let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:") //var gestureRecognizers:[AnyObject] = [tapGesture, pinchGesture, panGesture] //if let recognizers = scnView.gestureRecognizers { // gestureRecognizers += recognizers //} //scnView.gestureRecognizers = gestureRecognizers for controller in self.childViewControllers { if controller.isKindOfClass(KaleidoscopeSettingsViewController) { let settingsViewController = controller as! KaleidoscopeSettingsViewController settingsViewController.kaleidoscopeViewController = self self.settingsViewController = settingsViewController } } self.videoRecordingTmpUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("video.mov") self.screenTexture = ScreenTextureQuad() self.screenTexture!.initialize() OpenGlUtils.checkError("init") } override func viewWillLayoutSubviews() { let viewFrame = self.view.frame if(self.settingsViewController?.view.frame.width > viewFrame.width) { var frame = self.settingsViewController!.view.frame frame.size.width = viewFrame.width self.settingsOffsetConstraint.constant = -frame.size.width self.settingsWidthConstraint.constant = frame.size.width } } func createSphereNode(color:UIColor) -> SCNNode { let sphere = SCNSphere() let material = SCNMaterial() material.diffuse.contents = color sphere.materials = [material]; let sphereNode = SCNNode() sphereNode.geometry = sphere sphereNode.scale = SCNVector3Make(0.25, 0.25, 0.25) return sphereNode } func createCorners() { let scnView = self.view as! SCNView let extents = scnView.getExtents() let minEx = extents.min let maxEx = extents.max let scene = scnView.scene! let sphereCenterNode = createSphereNode(UIColor.redColor()) sphereCenterNode.position = SCNVector3Make(0.0, 0.0, 0.0) scene.rootNode.addChildNode(sphereCenterNode) let sphereLLNode = createSphereNode(UIColor.blueColor()) sphereLLNode.position = SCNVector3Make(minEx.x, minEx.y, 0.0) scene.rootNode.addChildNode(sphereLLNode) let sphereURNode = createSphereNode(UIColor.greenColor()) sphereURNode.position = SCNVector3Make(maxEx.x, maxEx.y, 0.0) scene.rootNode.addChildNode(sphereURNode) } private var _videoActionRate = FrequencyCounter(); func createMirror() -> Bool { var ret:Bool = false if !hasMirror { //createCorners() let scnView:SCNView = self.view as! SCNView let scene = scnView.scene! let triNode = SCNNode() //let geometry = Geometry.createKaleidoscopeMirrorWithEquilateralTriangles(scnView) let geometry = Geometry.createKaleidoscopeMirrorWithIsoscelesTriangles(scnView) //var geometry = Geometry.createSquare(scnView) triNode.geometry = geometry triNode.position = SCNVector3(x: 0, y: 0, z: 0) if(self.textureSource == .Video) { geometry.materials = [self.createVideoTextureMaterial()] } else if(self.textureSource == .Color) { let material = SCNMaterial() material.diffuse.contents = UIColor.randomColor() geometry.materials = [material] } else if(self.textureSource == .Image) { let me = UIImage(named: "me2") let material = SCNMaterial() material.diffuse.contents = me geometry.materials = [material] } //triNode.scale = SCNVector3(x: 0.5, y: 0.5, z: 0.5) triNode.name = "mirrors" let videoAction = SCNAction.customActionWithDuration(10000000000, actionBlock:{ (triNode:SCNNode, elapsedTime:CGFloat) -> Void in //NSLog("Running action: processNextVideoTexture") if self._videoActionRate.count == 0 { self._videoActionRate.start() } self._videoActionRate.increment() if self._videoActionRate.count % 30 == 0 { //NSLog("Video Action Rate: \(self._videoActionRate.frequency)/sec") } self.videoCapture.processNextVideoTexture() }) /* var swellAction = SCNAction.repeatActionForever(SCNAction.sequence( [ SCNAction.scaleTo(1.01, duration: 1), SCNAction.scaleTo(1.0, duration: 1), ])) */ let actions = SCNAction.group([videoAction]) triNode.runAction(actions) scene.rootNode.addChildNode(triNode) hasMirror = true ret = true } return ret; } func createVideoTextureMaterial() -> SCNMaterial { let material = SCNMaterial() let program = SCNProgram() let vertexShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "vsh") let fragmentShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "fsh") var vertexShaderSource: NSString? do { vertexShaderSource = try NSString(contentsOfURL: vertexShaderURL!, encoding: NSUTF8StringEncoding) } catch _ { vertexShaderSource = nil } var fragmentShaderSource: NSString? do { fragmentShaderSource = try NSString(contentsOfURL: fragmentShaderURL!, encoding: NSUTF8StringEncoding) } catch _ { fragmentShaderSource = nil } program.vertexShader = vertexShaderSource as? String program.fragmentShader = fragmentShaderSource as? String // Bind the position of the geometry and the model view projection // you would do the same for other geometry properties like normals // and other geometry properties/transforms. // // The attributes and uniforms in the shaders are defined as: // attribute vec4 position; // attribute vec2 textureCoordinate; // uniform mat4 modelViewProjection; program.setSemantic(SCNGeometrySourceSemanticVertex, forSymbol: "position", options: nil) program.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "textureCoordinate", options: nil) program.setSemantic(SCNModelViewProjectionTransform, forSymbol: "modelViewProjection", options: nil) program.delegate = self material.program = program material.doubleSided = true material.handleBindingOfSymbol("SamplerY", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1i(GLint(location), 0) } ) material.handleBindingOfSymbol("SamplerUV", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1i(GLint(location), 1) } ) material.handleBindingOfSymbol("TexRotation", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1f(GLint(location), self.textureRotation) } ) return material } // SCNProgramDelegate func program(program: SCNProgram, handleError error: NSError) { NSLog("%@", error) } func renderer(aRenderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: NSTimeInterval) { if _renderCount >= 1 && self.recordingStatus == RecordingStatus.Recording { if self.videoRecorder != nil{ self.videoRecorder!.bindRenderTextureFramebuffer() } } //self.videoRecorder!.bindRenderTextureFramebuffer() } // SCNSceneRendererDelegate private var _renderCount = 0 func renderer(aRenderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) { if _renderCount == 1 { self.createMirror() if(self.textureSource == .Video) { if let scnView:SCNView = self.view as? SCNView where scnView.eaglContext != nil { self.videoCapture.initVideoCapture(scnView.eaglContext!) } } glGetIntegerv(GLenum(GL_FRAMEBUFFER_BINDING), &self.defaultFBO) NSLog("Default framebuffer: %d", self.defaultFBO) } if _renderCount >= 1 { if self.snapshotRequested { self.takeShot() self.snapshotRequested = false } if self.recordingStatus == RecordingStatus.Recording { // var scnView = self.view as! SCNView glFlush() glFinish() if self.videoRecorder != nil{ self.videoRecorder!.grabFrameFromRenderTexture(time) // Works here glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO)) self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name) } } else if self.recordingStatus == RecordingStatus.FinishRequested { self.recordingStatus = RecordingStatus.Finishing Async.background({ () -> Void in self.finishRecording() }) } //glFinish() //glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO)) //self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name) } _renderCount++; /* let scnView:SCNView = self.view as SCNView var camera = scnView.pointOfView!.camera slideVelocity = Rotation.rotateCamera(scnView.pointOfView!, velocity: slideVelocity) */ } private var _lastRenderTime: NSTimeInterval = 0.0 func renderer(aRenderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) { if(_lastRenderTime > 0.0) { if self.rotateTexture { self.textureRotation += self.textureRotationSpeed * Float(time - _lastRenderTime) } else { self.textureRotation = 0.0 } } _lastRenderTime = time; } func handleTap(recognizer: UIGestureRecognizer) { // retrieve the SCNView let scnView:SCNView = self.view as! SCNView // check what nodes are tapped let viewPoint = recognizer.locationInView(scnView) for var node:SCNNode? = scnView.pointOfView; node != nil; node = node?.parentNode { NSLog("Node: " + node!.description) NSLog("Node pivot: " + node!.pivot.description) NSLog("Node constraints: \(node!.constraints?.description)") } let projectedOrigin = scnView.projectPoint(SCNVector3Zero) let vpWithZ = SCNVector3Make(Float(viewPoint.x), Float(viewPoint.y), projectedOrigin.z) let scenePoint = scnView.unprojectPoint(vpWithZ) print("tapPoint: (\(viewPoint.x), \(viewPoint.y)) scenePoint: (\(scenePoint.x), \(scenePoint.y), \(scenePoint.z))") } private var currentScale:Float = 1.0 private var lastScale:CGFloat = 1.0 func handlePinch(recognizer: UIPinchGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { lastScale = recognizer.scale } else if recognizer.state == UIGestureRecognizerState.Changed { let scnView:SCNView = self.view as! SCNView let cameraNode = scnView.pointOfView! let position = cameraNode.position var scale:Float = 1.0 - Float(recognizer.scale - lastScale) scale = min(scale, 40.0 / currentScale) scale = max(scale, 0.1 / currentScale) currentScale = scale lastScale = recognizer.scale let z = max(0.02, position.z * scale) cameraNode.position.z = z } } var slideVelocity = CGPointMake(0.0, 0.0) var cameraRot = CGPointMake(0.0, 0.0) var panPoint = CGPointMake(0.0, 0.0) func handlePan(recognizer: UIPanGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { panPoint = recognizer.locationInView(self.view) } else if recognizer.state == UIGestureRecognizerState.Changed { let pt = recognizer.locationInView(self.view) cameraRot.x += (pt.x - panPoint.x) * CGFloat(M_PI / 180.0) cameraRot.y += (pt.y - panPoint.y) * CGFloat(M_PI / 180.0) panPoint = pt } let x = Float(15 * sin(cameraRot.x)) let z = Float(15 * cos(cameraRot.x)) slideVelocity = recognizer.velocityInView(self.view) let scnView:SCNView = self.view as! SCNView let cameraNode = scnView.pointOfView! cameraNode.position = SCNVector3Make(x, 0, z) var vect = SCNVector3Make(0, 0, 0) - cameraNode.position vect.normalize() let at1 = atan2(vect.x, vect.z) let at2 = Float(atan2(0.0, -1.0)) let angle = at1 - at2 NSLog("Angle: %f", angle) cameraNode.rotation = SCNVector4Make(0, 1, 0, angle) } // // Settings // func startBreathing(depth:CGFloat, duration:NSTimeInterval) { self.stopBreathing() let scnView:SCNView = self.view as! SCNView let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false) if let mirrorNode = mirrorNode { let breatheAction = SCNAction.repeatActionForever(SCNAction.sequence( [ SCNAction.scaleTo(depth, duration: duration/2.0), SCNAction.scaleTo(1.0, duration: duration/2.0), ])) mirrorNode.runAction(breatheAction, forKey: "breatheAction") } } func stopBreathing() { let scnView = self.view as! SCNView let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false) if let mirrorNode = mirrorNode { mirrorNode.removeActionForKey("breatheAction") } } var isUsingFrontFacingCamera:Bool { get { return self.videoCapture.isUsingFrontFacingCamera } set { if newValue != self.videoCapture.isUsingFrontFacingCamera { self.videoCapture.switchCameras() } } } var maxZoom:CGFloat { get { return self.videoCapture.maxZoom } } var zoom:CGFloat { get { return self.videoCapture.zoom } set { self.videoCapture.zoom = newValue } } var isSettingsOpen = false @IBAction func settingsButtonFired(sender: UIButton) { if !self.isSettingsOpen { self.settingsViewController!.settingsWillOpen() } self.view.layoutIfNeeded() let offset = (self.isSettingsOpen ? -(self.settingsWidthConstraint.constant) : 0) UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: ({ self.settingsOffsetConstraint.constant = offset self.view.layoutIfNeeded() }), completion: { (finished:Bool) -> Void in self.isSettingsOpen = !self.isSettingsOpen let scnView = self.view as! SCNView scnView.allowsCameraControl = !self.isSettingsOpen if !self.isSettingsOpen { self.settingsViewController!.settingsDidClose() } }) } @IBAction func videoButtonFired(sender: UIButton) { if self.recordingStatus == RecordingStatus.Stopped { self.setupVideoRecorderRecording() self.recordingStatus = RecordingStatus.Recording; self.imageRecording.hidden = false } else if self.recordingStatus == RecordingStatus.Recording { self.imageRecording.hidden = true self.stopRecording() } } private func setupVideoRecorderRecording() { self.deleteFile(self.videoRecordingTmpUrl) if(self.videoRecorder == nil) { // retrieve the SCNView if let scnView = self.view as? SCNView where scnView.eaglContext != nil { let width:GLsizei = GLsizei(scnView.bounds.size.width * UIScreen.mainScreen().scale) let height:GLsizei = GLsizei(scnView.bounds.size.height * UIScreen.mainScreen().scale) self.videoRecorder = FrameBufferVideoRecorder(movieUrl: self.videoRecordingTmpUrl, width: width, height: height) self.videoRecorder!.initVideoRecorder(scnView.eaglContext!) self.videoRecorder!.generateFramebuffer(scnView.eaglContext!) } } } private func stopRecording() { if self.recordingStatus == RecordingStatus.Recording { self.recordingStatus = RecordingStatus.FinishRequested; } } private func finishRecording() { self.videoRecorder?.finish({ (status:FrameBufferVideoRecorderStatus) -> Void in NSLog("Video recorder finished with status: " + status.description); if(status == FrameBufferVideoRecorderStatus.Completed) { let fileManager: NSFileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(self.videoRecordingTmpUrl.path!) { UISaveVideoAtPathToSavedPhotosAlbum(self.videoRecordingTmpUrl.path!, self, "video:didFinishSavingWithError:contextInfo:", nil) } else { NSLog("File does not exist: " + self.videoRecordingTmpUrl.path!); } } }) } func video(videoPath:NSString, didFinishSavingWithError error:NSErrorPointer, contextInfo:UnsafeMutablePointer<Void>) { NSLog("Finished saving video") self.videoRecorder = nil; self.recordingStatus = RecordingStatus.Stopped self.deleteFile(self.videoRecordingTmpUrl) } func deleteFile(fileUrl:NSURL) { let fileManager: NSFileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(fileUrl.path!) { var error:NSError? = nil; do { try fileManager.removeItemAtURL(fileUrl) } catch let error1 as NSError { error = error1 } if(error != nil) { NSLog("Error deleing file: %@ Error: %@", fileUrl, error!) } } } func takeShot() { let image = self.imageFromSceneKitView(self.view as! SCNView) UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } func imageFromSceneKitView(sceneKitView:SCNView) -> UIImage { let w:Int = Int(sceneKitView.bounds.size.width * UIScreen.mainScreen().scale) let h:Int = Int(sceneKitView.bounds.size.height * UIScreen.mainScreen().scale) let myDataLength:Int = w * h * Int(4) let buffer = UnsafeMutablePointer<CGFloat>(calloc(myDataLength, Int(sizeof(CUnsignedChar)))) glReadPixels(0, 0, GLint(w), GLint(h), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), buffer) let provider = CGDataProviderCreateWithData(nil, buffer, Int(myDataLength), nil) let bitsPerComponent:Int = 8 let bitsPerPixel:Int = 32 let bytesPerRow:Int = 4 * w let colorSpaceRef = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo.ByteOrderDefault let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault // make the cgimage let decode:UnsafePointer<CGFloat> = nil; let cgImage = CGImageCreate(w, h, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, decode, false, renderingIntent) return UIImage(CGImage: cgImage!) } // // UIViewControlle overrides // override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
drscotthawley/add-menu-popover-demo
PopUpMenuTest/ViewController.swift
1
1401
// // ViewController.swift // PopUpMenuTest // // Created by Scott Hawley on 8/31/15. // Copyright © 2015 Scott Hawley. All rights reserved. // import UIKit class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBOutlet weak var addbutton: UIBarButtonItem! @IBOutlet weak var messageLabel: UILabel! var menuSelections : [String] = [] @IBAction func addButtonPress(sender: AnyObject) { self.performSegueWithIdentifier("showView", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showView" { let vc = segue.destinationViewController let controller = vc.popoverPresentationController if controller != nil { controller?.delegate = self } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. messageLabel.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } }
gpl-2.0
jkolb/Swiftish
Sources/Swiftish/Bounds3.swift
1
9624
/* The MIT License (MIT) Copyright (c) 2015-2017 Justin Kolb 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. */ public struct Bounds3<T: Vectorable> : Hashable { public var center: Vector3<T> public var extents: Vector3<T> public init() { self.init(center: Vector3<T>(), extents: Vector3<T>()) } public init(minimum: Vector3<T>, maximum: Vector3<T>) { precondition(minimum.x <= maximum.x) precondition(minimum.y <= maximum.y) precondition(minimum.z <= maximum.z) let center = (maximum + minimum) / 2 let extents = (maximum - minimum) / 2 self.init(center: center, extents: extents) } public init(center: Vector3<T>, extents: Vector3<T>) { precondition(extents.x >= 0) precondition(extents.y >= 0) precondition(extents.z >= 0) self.center = center self.extents = extents } public init(union: [Bounds3<T>]) { var minmax = [Vector3<T>]() for other in union { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } self.init(containingPoints: minmax) } public init(containingPoints points: [Vector3<T>]) { if points.count == 0 { self.init() return } var minimum = Vector3<T>(+T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude) var maximum = Vector3<T>(-T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude) for point in points { if point.x < minimum.x { minimum.x = point.x } if point.x > maximum.x { maximum.x = point.x } if point.y < minimum.y { minimum.y = point.y } if point.y > maximum.y { maximum.y = point.y } if point.z < minimum.z { minimum.z = point.z } if point.z > maximum.z { maximum.z = point.z } } self.init(minimum: minimum, maximum: maximum) } public var minimum: Vector3<T> { return center - extents } public var maximum: Vector3<T> { return center + extents } public var isNull: Bool { return center == Vector3<T>() && extents == Vector3<T>() } public func contains(point: Vector3<T>) -> Bool { if point.x < minimum.x { return false } if point.y < minimum.y { return false } if point.z < minimum.z { return false } if point.x > maximum.x { return false } if point.y > maximum.y { return false } if point.z > maximum.z { return false } return true } /// If `other` bounds intersects current bounds, return their intersection. /// A `null` Bounds3 object is returned if any of those are `null` or if they don't intersect at all. /// /// - Note: A Bounds3 object `isNull` if it's center and extents are zero. /// - Parameter other: The second Bounds3 object to intersect with. /// - Returns: A Bounds3 object intersection. public func intersection(other: Bounds3<T>) -> Bounds3<T> { if isNull { return self } else if other.isNull { return other } else if minimum.x <= other.maximum.x && other.minimum.x <= maximum.x && maximum.y <= other.minimum.y && other.maximum.y <= minimum.y && maximum.z <= other.minimum.z && other.maximum.z <= minimum.z { let minX = max(minimum.x, other.minimum.x) let minY = max(minimum.y, other.minimum.y) let minZ = max(minimum.z, other.minimum.z) let maxX = min(maximum.x, other.maximum.x) let maxY = min(maximum.y, other.maximum.y) let maxZ = min(maximum.z, other.maximum.z) return Bounds3<T>(minimum: Vector3<T>(minX, minY, minZ), maximum: Vector3<T>(maxX, maxY, maxZ)) } return Bounds3<T>() } public func union(other: Bounds3<T>) -> Bounds3<T> { if isNull { return other } else if other.isNull { return self } else { return Bounds3<T>(containingPoints: [minimum, maximum, other.minimum, other.maximum]) } } public func union(others: [Bounds3<T>]) -> Bounds3<T> { var minmax = [Vector3<T>]() if !isNull { minmax.append(minimum) minmax.append(maximum) } for other in others { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } if minmax.count == 0 { return self } else { return Bounds3<T>(containingPoints: minmax) } } public var description: String { return "{\(center), \(extents)}" } public var corners: [Vector3<T>] { let max: Vector3<T> = maximum let corner0: Vector3<T> = max * Vector3<T>(+1, +1, +1) let corner1: Vector3<T> = max * Vector3<T>(-1, +1, +1) let corner2: Vector3<T> = max * Vector3<T>(+1, -1, +1) let corner3: Vector3<T> = max * Vector3<T>(+1, +1, -1) let corner4: Vector3<T> = max * Vector3<T>(-1, -1, +1) let corner5: Vector3<T> = max * Vector3<T>(+1, -1, -1) let corner6: Vector3<T> = max * Vector3<T>(-1, +1, -1) let corner7: Vector3<T> = max * Vector3<T>(-1, -1, -1) return [ corner0, corner1, corner2, corner3, corner4, corner5, corner6, corner7, ] } public static func distance2<T>(_ point: Vector3<T>, _ bounds: Bounds3<T>) -> T { var distanceSquared: T = 0 let minimum = bounds.minimum let maximum = bounds.maximum for index in 0..<3 { let p = point[index] let bMin = minimum[index] let bMax = maximum[index] if p < bMin { let delta = bMin - p distanceSquared = distanceSquared + delta * delta } if p > bMax { let delta = p - bMax distanceSquared = distanceSquared + delta * delta } } return distanceSquared } public func intersectsOrIsInside(_ plane: Plane<T>) -> Bool { let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal)) let distanceOfBoxCenterFromPlane = Vector3<T>.dot(plane.normal, center) - plane.distance let intersects = abs(distanceOfBoxCenterFromPlane) <= projectionRadiusOfBox let isInside = projectionRadiusOfBox <= distanceOfBoxCenterFromPlane return intersects || isInside } public func intersectsOrIsInside(_ frustum: Frustum<T>) -> Bool { if isNull { return false } // In order of most likely to cause early exit if !intersectsOrIsInside(frustum.near) { return false } if !intersectsOrIsInside(frustum.left) { return false } if !intersectsOrIsInside(frustum.right) { return false } if !intersectsOrIsInside(frustum.top) { return false } if !intersectsOrIsInside(frustum.bottom) { return false } if !intersectsOrIsInside(frustum.far) { return false } return true } public func intersects(_ plane: Plane<T>) -> Bool { let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal)) let distanceOfBoxCenterFromPlane = Swift.abs(Vector3<T>.dot(plane.normal, center) - plane.distance) return distanceOfBoxCenterFromPlane <= projectionRadiusOfBox } public func intersects(_ bounds: Bounds3<T>) -> Bool { if Swift.abs(center.x - bounds.center.x) > (extents.x + bounds.extents.x) { return false } if Swift.abs(center.y - bounds.center.y) > (extents.y + bounds.extents.y) { return false } if Swift.abs(center.z - bounds.center.z) > (extents.z + bounds.extents.z) { return false } return true } public func transform(_ t: Transform3<T>) -> Bounds3<T> { return Bounds3<T>(containingPoints: corners.map({ $0.transform(t) })) } }
mit
muukii0803/PhotosPicker
PhotosPicker/Sources/PhotosPickerController.swift
2
3441
// PhotosPickerController.swift // // Copyright (c) 2015 muukii // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Photos import AssetsLibrary import CoreLocation /** * PhotosPickerController */ public class PhotosPickerController: UINavigationController { public private(set) var collectionController: PhotosPickerCollectionsController? /// public var allowsEditing: Bool = false public var didFinishPickingAssets: ((controller: PhotosPickerController, assets: [PhotosPickerAsset]) -> Void)? public var didCancel: ((controller: PhotosPickerController) -> Void)? public var setupSections: ((defaultSection: PhotosPickerCollectionsSection) -> [PhotosPickerCollectionsSection])? /** :returns: */ public init() { let controller = PhotosPicker.CollectionsControllerClass(nibName: nil, bundle: nil) super.init(rootViewController: controller) self.collectionController = controller } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.setup() } private func setup() { if PhotosPicker.authorizationStatus != .Authorized { if AvailablePhotos() { PhotosPicker.requestAuthorization({ (status) -> Void in self.setup() }) } return } PhotosPicker.requestDefaultSection { section in self.collectionController?.sectionInfo = self.setupSections?(defaultSection: section) } } public static var defaultSelectionHandler = { (collectionsController: PhotosPickerCollectionsController, item: PhotosPickerCollectionsItem) -> Void in let controller = PhotosPicker.AssetsControllerClass() controller.item = item collectionsController.navigationController?.pushViewController(controller, animated: true) } }
mit
ksco/swift-algorithm-club-cn
Union-Find/UnionFind.playground/Contents.swift
1
2968
//: Playground - noun: a place where people can play public struct UnionFind<T: Hashable> { private var index = [T: Int]() private var parent = [Int]() private var size = [Int]() public mutating func addSetWith(element: T) { index[element] = parent.count parent.append(parent.count) size.append(1) } private mutating func setByIndex(index: Int) -> Int { if parent[index] == index { return index } else { parent[index] = setByIndex(parent[index]) return parent[index] } } public mutating func setOf(element: T) -> Int? { if let indexOfElement = index[element] { return setByIndex(indexOfElement) } else { return nil } } public mutating func unionSetsContaining(firstElement: T, and secondElement: T) { if let firstSet = setOf(firstElement), secondSet = setOf(secondElement) { if firstSet != secondSet { if size[firstSet] < size[secondSet] { parent[firstSet] = secondSet size[secondSet] += size[firstSet] } else { parent[secondSet] = firstSet size[firstSet] += size[secondSet] } } } } public mutating func inSameSet(firstElement: T, and secondElement: T) -> Bool { if let firstSet = setOf(firstElement), secondSet = setOf(secondElement) { return firstSet == secondSet } else { return false } } } var dsu = UnionFind<Int>() for i in 1...10 { dsu.addSetWith(i) } // now our dsu contains 10 independent sets // let's divide our numbers into two sets by divisibility by 2 for i in 3...10 { if i % 2 == 0 { dsu.unionSetsContaining(2, and: i) } else { dsu.unionSetsContaining(1, and: i) } } // check our division print(dsu.inSameSet(2, and: 4)) print(dsu.inSameSet(4, and: 6)) print(dsu.inSameSet(6, and: 8)) print(dsu.inSameSet(8, and: 10)) print(dsu.inSameSet(1, and: 3)) print(dsu.inSameSet(3, and: 5)) print(dsu.inSameSet(5, and: 7)) print(dsu.inSameSet(7, and: 9)) print(dsu.inSameSet(7, and: 4)) print(dsu.inSameSet(3, and: 6)) var dsuForStrings = UnionFind<String>() let words = ["all", "border", "boy", "afternoon", "amazing", "awesome", "best"] dsuForStrings.addSetWith("a") dsuForStrings.addSetWith("b") // In that example we divide strings by its first letter for word in words { dsuForStrings.addSetWith(word) if word.hasPrefix("a") { dsuForStrings.unionSetsContaining("a", and: word) } else if word.hasPrefix("b") { dsuForStrings.unionSetsContaining("b", and: word) } } print(dsuForStrings.inSameSet("a", and: "all")) print(dsuForStrings.inSameSet("all", and: "awesome")) print(dsuForStrings.inSameSet("amazing", and: "afternoon")) print(dsuForStrings.inSameSet("b", and: "boy")) print(dsuForStrings.inSameSet("best", and: "boy")) print(dsuForStrings.inSameSet("border", and: "best")) print(dsuForStrings.inSameSet("amazing", and: "boy")) print(dsuForStrings.inSameSet("all", and: "border"))
mit
ijoshsmith/json2swift
json2swift/json-schema-inference.swift
1
5642
// // json-schema-inference.swift // json2swift // // Created by Joshua Smith on 10/10/16. // Copyright © 2016 iJoshSmith. All rights reserved. // import Foundation // MARK: - JSONElementSchema extension extension JSONElementSchema { static func inferred(from jsonElementArray: [JSONElement], named name: String) -> JSONElementSchema { let jsonElement = [name: jsonElementArray] let schema = JSONElementSchema.inferred(from: jsonElement, named: name) let (_, attributeType) = schema.attributes.first! switch attributeType { case .elementArray(_, let elementSchema, _): return elementSchema case .emptyArray: return JSONElementSchema(name: name) default: abort() } } static func inferred(from jsonElement: JSONElement, named name: String) -> JSONElementSchema { let attributes = createAttributeMap(for: jsonElement) return JSONElementSchema(name: name, attributes: attributes) } private static func createAttributeMap(for jsonElement: JSONElement) -> JSONAttributeMap { let attributes = jsonElement.map { (name, value) -> (String, JSONType) in let type = JSONType.inferType(of: value, named: name) return (name, type) } return JSONAttributeMap(entries: attributes) } } // MARK: - JSONType extension fileprivate extension JSONType { static func inferType(of value: Any, named name: String) -> JSONType { switch value { case let element as JSONElement: return inferType(of: element, named: name) case let array as [Any]: return inferType(of: array, named: name) case let nsValue as NSValue: return inferType(of: nsValue) case let string as String: return inferType(of: string) case is NSNull: return .nullable default: assertionFailure("Unexpected type of value in JSON: \(value)") abort() } } private static func inferType(of element: JSONElement, named name: String) -> JSONType { let schema = JSONElementSchema.inferred(from: element, named: name) return .element(isRequired: true, schema: schema) } private static func inferType(of array: [Any], named name: String) -> JSONType { let arrayWithoutNulls = array.filter { $0 is NSNull == false } if let elements = arrayWithoutNulls as? [JSONElement] { let hasNullableElements = arrayWithoutNulls.count < array.count return inferType(ofElementArray: elements, named: name, hasNullableElements: hasNullableElements) } else { return inferType(ofValueArray: array, named: name) } } private static func inferType(ofElementArray elementArray: [JSONElement], named name: String, hasNullableElements: Bool) -> JSONType { if elementArray.isEmpty { return .emptyArray } let schemas = elementArray.map { jsonElement in JSONElementSchema.inferred(from: jsonElement, named: name) } let mergedSchema = JSONElementSchema.inferredByMergingAttributes(of: schemas, named: name) return .elementArray(isRequired: true, elementSchema: mergedSchema, hasNullableElements: hasNullableElements) } private static func inferType(ofValueArray valueArray: [JSONValue], named name: String) -> JSONType { if valueArray.isEmpty { return .emptyArray } let valueType = inferValueType(of: valueArray, named: name) return .valueArray(isRequired: true, valueType: valueType) } private static func inferValueType(of values: [JSONValue], named name: String) -> JSONType { let types = values.map { inferType(of: $0, named: name) } switch types.count { case 0: abort() // Should never introspect an empty array. case 1: return types[0] default: return types.dropFirst().reduce(types[0]) { $0.findCompatibleType(with: $1) } } } private static func inferType(of nsValue: NSValue) -> JSONType { if nsValue.isBoolType { return .bool(isRequired: true) } else { return .number(isRequired: true, isFloatingPoint: nsValue.isFloatType) } } private static func inferType(of string: String) -> JSONType { if let dateFormat = string.extractDateFormat() { return .date(isRequired: true, format: dateFormat) } else if string.isWebAddress { return .url(isRequired: true) } else { return .string(isRequired: true) } } } // MARK: - String extension fileprivate extension String { func extractDateFormat() -> String? { let trimmed = trimmingCharacters(in: CharacterSet.whitespaces) return String.extractDateFormat(from: trimmed) } private static func extractDateFormat(from string: String) -> String? { guard let prefixRange = string.range(of: dateFormatPrefix) else { return nil } guard prefixRange.lowerBound == string.startIndex else { return nil } return String(string[prefixRange.upperBound...]) } var isWebAddress: Bool { guard let url = URL(string: self) else { return false } return url.scheme != nil && url.host != nil } } // MARK: - NSValue extension fileprivate extension NSValue { var isBoolType: Bool { return CFNumberGetType((self as! CFNumber)) == CFNumberType.charType } var isFloatType: Bool { return CFNumberIsFloatType((self as! CFNumber)) } }
mit
jonnguy/HSTracker
HSTracker/UIs/Trackers/CardHudContainer.swift
1
5038
// // CardHudContainer.swift // HSTracker // // Created by Benjamin Michotte on 16/06/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import AppKit class CardHudContainer: OverWindowController { var positions: [Int: [NSPoint]] = [:] var huds: [CardHud] = [] @IBOutlet weak var container: NSView! override func windowDidLoad() { super.windowDidLoad() for _ in 0 ..< 10 { let hud = CardHud() hud.alphaValue = 0.0 container.addSubview(hud) huds.append(hud) } initPoints() } func initPoints() { positions[1] = [ NSPoint(x: 144, y: -3) ] positions[2] = [ NSPoint(x: 97, y: -1), NSPoint(x: 198, y: -1) ] positions[3] = [ NSPoint(x: 42, y: 19), NSPoint(x: 146, y: -1), NSPoint(x: 245, y: 8) ] positions[4] = [ NSPoint(x: 31, y: 28), NSPoint(x: 109, y: 6), NSPoint(x: 185, y: -1), NSPoint(x: 262, y: 5) ] positions[5] = [ NSPoint(x: 21, y: 26), NSPoint(x: 87, y: 6), NSPoint(x: 148, y: -4), NSPoint(x: 211, y: -2), NSPoint(x: 274, y: 9) ] positions[6] = [ NSPoint(x: 19, y: 36), NSPoint(x: 68, y: 15), NSPoint(x: 123, y: 2), NSPoint(x: 175, y: -3), NSPoint(x: 229, y: 0), NSPoint(x: 278, y: 9) ] positions[7] = [ NSPoint(x: 12.0, y: 36.0), NSPoint(x: 57.0, y: 16.0), NSPoint(x: 104.0, y: 4.0), NSPoint(x: 153.0, y: -1.0), NSPoint(x: 194.0, y: -3.0), NSPoint(x: 240.0, y: 6.0), NSPoint(x: 283.0, y: 19.0) ] positions[8] = [ NSPoint(x: 14.0, y: 38.0), NSPoint(x: 52.0, y: 22.0), NSPoint(x: 92.0, y: 6.0), NSPoint(x: 134.0, y: -2.0), NSPoint(x: 172.0, y: -5.0), NSPoint(x: 210.0, y: -4.0), NSPoint(x: 251.0, y: 1.0), NSPoint(x: 289.0, y: 10.0) ] positions[9] = [ NSPoint(x: 16.0, y: 38.0), NSPoint(x: 57.0, y: 25.0), NSPoint(x: 94.0, y: 12.0), NSPoint(x: 127.0, y: 3.0), NSPoint(x: 162.0, y: -1.0), NSPoint(x: 201.0, y: -6.0), NSPoint(x: 238.0, y: 2.0), NSPoint(x: 276.0, y: 13.0), NSPoint(x: 315.0, y: 28.0) ] positions[10] = [ NSPoint(x: 21.0, y: 40.0), NSPoint(x: 53.0, y: 30.0), NSPoint(x: 86.0, y: 20.0), NSPoint(x: 118.0, y: 8.0), NSPoint(x: 149.0, y: -1.0), NSPoint(x: 181.0, y: -2.0), NSPoint(x: 211.0, y: -0.0), NSPoint(x: 245.0, y: 1.0), NSPoint(x: 281.0, y: 12.0), NSPoint(x: 319.0, y: 23.0) ] } func reset() { for hud in huds { hud.alphaValue = 0.0 hud.frame = NSRect.zero } } func update(entities: [Entity], cardCount: Int) { for (i, hud) in huds.enumerated() { var hide = true if let entity = entities.first(where: { $0[.zone_position] == i + 1 }) { hud.entity = entity var pos: NSPoint? if let points = positions[cardCount], points.count > i { pos = points[i] if let pos = pos { hide = false let rect = NSRect(x: pos.x * SizeHelper.hearthstoneWindow.scaleX, y: pos.y * SizeHelper.hearthstoneWindow.scaleY, width: 36, height: 45) hud.needsDisplay = true // this will avoid a weird move if hud.frame == NSRect.zero { hud.frame = rect } NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 hud.animator().frame = rect hud.animator().alphaValue = 1.0 }, completionHandler: nil) } } } if hide { NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 hud.animator().alphaValue = 0.0 }, completionHandler: nil) } } } }
mit
HTWDD/htwcampus
HTWDD/Main Categories/General/Service.swift
2
364
// // Service.swift // HTWDD // // Created by Benjamin Herzog on 29.10.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import RxSwift /// A Service is a type that can load a result for a given authentication protocol Service { associatedtype Parameter associatedtype Result func load(parameters: Parameter) -> Observable<Result> }
mit
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/Main/VC/WKDelegateVC.swift
2
794
// // WKDelegateVC.swift // SwiftTest // // Created by MAC on 2016/12/13. // Copyright © 2016年 MAC. All rights reserved. // import UIKit import WebKit @objc protocol WKDelegateVCDelegate { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) } class WKDelegateVC: UIViewController { weak var delegate: WKDelegateVCDelegate? override func viewDidLoad() { super.viewDidLoad() } } // MARK: - 主要解决WKWebView不能释放的问题 extension WKDelegateVC: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { delegate?.userContentController(userContentController, didReceive: message) } }
apache-2.0
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01274-resolvetypedecl.swift
12
297
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b( ( ( ( ) ) ) ) -> { { ( ) -> Any in { } { } { { } } { } { } { } { } { { } } { } class b<h , i : c struct c<d where d = e
mit
ale84/ABLE
ABLE/Mocks/CBServiceMock.swift
1
611
// // Created by Alessio Orlando on 14/06/18. // Copyright © 2019 Alessio Orlando. All rights reserved. // import Foundation import CoreBluetooth public class CBServiceMock: CBServiceType { public var cbCharacteristics: [CBCharacteristicType]? public var isPrimary: Bool public var characteristics: [CBCharacteristic]? public var uuid: CBUUID public init(with id: CBUUID = CBUUID(), isPrimary: Bool = true, characteristics: [CBCharacteristic]? = nil) { self.uuid = id self.isPrimary = isPrimary self.characteristics = characteristics } }
mit
TylerTheCompiler/TTPOverlayViewController
Example/ViewController.swift
2
4582
// The MIT License (MIT) // // Copyright (c) 2017 Tyler Prevost // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import OverlayViewController class ViewController: UIViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segue = segue as? OverlaySegue { let overlayVC = segue.overlayViewController if let senderView = sender as? UIView { overlayVC.sourceFrameForOverlayViewHandler = { [weak senderView] _ in return senderView?.frame ?? .null } } overlayVC.minimumMargins = { overlayVC in switch overlayVC.viewSizeClass { case .phonePortrait: return UIEdgeInsets(top: 50, left: 20, bottom: 50, right: 20) case .smallPhoneLandscape: return UIEdgeInsets(top: 30, left: 20, bottom: 30, right: 20) case .largePhoneLandscape: return UIEdgeInsets(top: 60, left: 50, bottom: 60, right: 50) case .padWideTall: return UIEdgeInsets(top: 100, left: 50, bottom: 100, right: 50) case .padWideShort: return UIEdgeInsets(top: 60, left: 60, bottom: 60, right: 60) case .padThin: return UIEdgeInsets(top: 80, left: 30, bottom: 80, right: 30) default: return .zero } } } } @IBAction func unwindToViewController(_ segue: UIStoryboardSegue) { // empty } } enum UserInterfaceIdiomSizeClass { case phonePortrait case smallPhoneLandscape case largePhoneLandscape case pad case padThin case tv case carPlay case unknown } extension UITraitCollection { var userInterfaceIdiomSizeClass: UserInterfaceIdiomSizeClass { switch (horizontalSizeClass, verticalSizeClass, userInterfaceIdiom) { case (.compact, .compact, .phone): return .smallPhoneLandscape case (.compact, .regular, .phone): return .phonePortrait case (.regular, .compact, .phone): return .largePhoneLandscape case (.compact, .regular, .pad): return .padThin case (.regular, .regular, .pad): return .pad case (_, _, .tv): return .tv case (_, _, .carPlay): return .carPlay default: return .unknown } } } enum ViewSizeClass { case phonePortrait case smallPhoneLandscape case largePhoneLandscape case padWideTall case padWideShort case padThin case tv case carPlay case unknown } extension UIView { var viewSizeClass: ViewSizeClass { let windowFrame = window?.frame ?? .zero switch (traitCollection.userInterfaceIdiomSizeClass, windowFrame.width > windowFrame.height) { case (.phonePortrait, _): return .phonePortrait case (.smallPhoneLandscape, _): return .smallPhoneLandscape case (.largePhoneLandscape, _): return .largePhoneLandscape case (.padThin, _): return .padThin case (.pad, true): return .padWideShort case (.pad, false): return .padWideTall case (.tv, _): return .tv case (.carPlay, _): return .carPlay default: return .unknown } } } extension UIViewController { var viewSizeClass: ViewSizeClass { guard isViewLoaded else { return .unknown } return view.viewSizeClass } }
mit
Fenrikur/ef-app_ios
Eurofurence/Modules/Event Feedback/Scene/EventFeedbackSceneFactory.swift
1
155
import UIKit.UIViewController protocol EventFeedbackSceneFactory { func makeEventFeedbackScene() -> UIViewController & EventFeedbackScene }
mit
WeHUD/app
weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/PagerTabStripBehaviour.swift
6
2216
// PagerTabStripOptions.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public enum PagerTabStripBehaviour { case common(skipIntermediateViewControllers: Bool) case progressive(skipIntermediateViewControllers: Bool, elasticIndicatorLimit: Bool) public var skipIntermediateViewControllers: Bool { switch self { case .common(let skipIntermediateViewControllers): return skipIntermediateViewControllers case .progressive(let skipIntermediateViewControllers, _): return skipIntermediateViewControllers } } public var isProgressiveIndicator: Bool { switch self { case .common(_): return false case .progressive(_, _): return true } } public var isElasticIndicatorLimit: Bool { switch self { case .common(_): return false case .progressive(_, let elasticIndicatorLimit): return elasticIndicatorLimit } } }
bsd-3-clause
funky-monkey/Valide.swift
Valide/Classes/ValidationErrors.swift
2
211
// // ValidationErrors.swift // Valide // // Created by Sidney De Koning on 10-11-15. // Copyright © 2015 Sidney De Koning. All rights reserved. // import Foundation enum ValidationErrors: Error { }
unlicense
Swiftodon/Leviathan
Leviathan/Sources/Model/Mastodon/FederatedTimelineModel.swift
1
1139
// // FederatedTimelineModel.swift // Leviathan // // Created by Thomas Bonk on 31.10.22. // Copyright 2022 The Swiftodon Team // // 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 MastodonSwift class FederatedTimelineModel: TimelineModel { // MARK: - Public Properties public override var timelineId: TimelineId { TimelineId.federated } // MARK: - Public Methods override func retrieveTimeline() async throws -> [Status]? { return try await SessionModel.shared.currentSession?.auth?.getPublicTimeline(isLocal: false, sinceId: lastStatusId) } }
apache-2.0
rudkx/swift
test/Generics/superclass_constraint_self_derived.swift
1
511
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=verify 2>&1 | %FileCheck %s protocol P { associatedtype T : Q } protocol Q { associatedtype T : R var t: T { get } } protocol R {} func takesR<T : R>(_: T) {} class C<T : Q> : P {} struct Outer<T : P> { // CHECK-LABEL: .Inner@ // CHECK-NEXT: Generic signature: <T, U where T : C<U>, U : Q> struct Inner<U> where T : C<U> { func doStuff(_ u: U) { takesR(u.t) } } }
apache-2.0
vincent-cheny/DailyRecord
DailyRecord/ChartViewController.swift
1
13333
// // ChartViewController.swift // DailyRecord // // Created by ChenYong on 16/2/12. // Copyright © 2016年 LazyPanda. All rights reserved. // import UIKit import RealmSwift import PNChart class ChartViewController: UIViewController { @IBOutlet weak var dateType: UIBarButtonItem! @IBOutlet weak var chartType: UIBarButtonItem! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var pieChart: CustomPNPieChart! @IBOutlet weak var lineChart: PNLineChart! let realm = try! Realm() let dateFormatter = NSDateFormatter() var showDate = NSDate() var dateRange: [NSTimeInterval]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. dateFormatter.dateFormat = "yyyy.M.d" updateTime(dateType.title!, diff: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = false; } @IBAction func plusDate(sender: AnyObject) { updateTime(dateType.title!, diff: 1) } @IBAction func minusDate(sender: AnyObject) { updateTime(dateType.title!, diff: -1) } @IBAction func switchChartType(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) addChartType(alert, type: "饼状图") addChartType(alert, type: "折线图") self.presentViewController(alert, animated: true, completion: nil) } @IBAction func switchDateType(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) addDateType(alert, type: "本周") addDateType(alert, type: "本月") addDateType(alert, type: "本年") self.presentViewController(alert, animated: true, completion: nil) } @IBAction func respondToRightSwipeGesture(sender: AnyObject) { updateTime(dateType.title!, diff: -1) } @IBAction func respondToLeftSwipeGesture(sender: AnyObject) { updateTime(dateType.title!, diff: 1) } @IBAction func respondToUpSwipeGesture(sender: AnyObject) { switchChartType() } @IBAction func respondToDownSwipeGesture(sender: AnyObject) { switchChartType() } func switchChartType() { if chartType.title == "饼状图" { chartType.title = "折线图" } else { chartType.title = "饼状图" } updateChart() } func addChartType(alert: UIAlertController, type: String) { alert.addAction(UIAlertAction(title: type, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.chartType.title = type self.updateChart() })) } func addDateType(alert: UIAlertController, type: String) { alert.addAction(UIAlertAction(title: type, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.dateType.title = type self.showDate = NSDate() self.updateTime(type, diff: 0) })) } func updateTime(type: String, diff: Int) { switch type { case "本周": let weekComponent = NSDateComponents() weekComponent.day = diff * 7; showDate = NSCalendar.currentCalendar().dateByAddingComponents(weekComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getWeek(dateFormatter, date: showDate) dateRange = Utils.getWeekRange(showDate) updateChart() case "本月": let monthComponent = NSDateComponents() monthComponent.month = diff; showDate = NSCalendar.currentCalendar().dateByAddingComponents(monthComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getYearMonth(showDate) dateRange = Utils.getMonthRange(showDate) updateChart() case "本年": let yearComponent = NSDateComponents() yearComponent.year = diff; showDate = NSCalendar.currentCalendar().dateByAddingComponents(yearComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getYear(showDate) dateRange = Utils.getYearRange(showDate) updateChart() default: break } } func updateChart() { let black = realm.objects(Industry).filter("type = '黑业' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let blackCheck = realm.objects(Industry).filter("type = '黑业对治' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let white = realm.objects(Industry).filter("type = '白业' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let whiteCheck = realm.objects(Industry).filter("type = '白业对治' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count pieChart.hidden = true lineChart.hidden = true if black + blackCheck + white + whiteCheck > 0 { switch chartType.title! { case "饼状图": pieChart.hidden = false var dataItems = [PNPieChartDataItem]() if black > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(black), color: UIColor.blackColor(), description: "黑业")) } if blackCheck > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(blackCheck), color: UIColor.greenColor(), description: "黑业对治")) } if white > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(white), color: UIColor.whiteColor(), description: "白业")) } if whiteCheck > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(whiteCheck), color: UIColor.redColor(), description: "白业对治")) } pieChart.updateChartData(dataItems) pieChart.descriptionTextColor = UIColor.lightGrayColor() pieChart.descriptionTextFont = UIFont.systemFontOfSize(11.0) pieChart.descriptionTextShadowColor = UIColor.clearColor() pieChart.displayAnimated = false pieChart.showAbsoluteValues = true pieChart.userInteractionEnabled = false pieChart.strokeChart() pieChart.legendStyle = PNLegendItemStyle.Stacked pieChart.legendFontColor = UIColor.lightGrayColor() pieChart.legendFont = UIFont.boldSystemFontOfSize(12.0) let legend = pieChart.getLegendWithMaxWidth(200) legend.frame = CGRect(x: 0, y: view.frame.width * 2 / 3, width: legend.frame.size.width, height: legend.frame.size.height) pieChart.addSubview(legend) break case "折线图": lineChart.hidden = false lineChart.displayAnimated = false lineChart.chartMarginLeft = 35 lineChart.chartCavanHeight = lineChart.frame.height - 250 var data01Array: [NSNumber]! var data02Array: [NSNumber]! var data03Array: [NSNumber]! var data04Array: [NSNumber]! switch dateType.title! { case "本周": lineChart.setXLabels(["", "2", "", "4", "", "6", ""], withWidth: (view.frame.width - 75) / 8) data01Array = getEveryDayData("黑业") data02Array = getEveryDayData("黑业对治") data03Array = getEveryDayData("白业") data04Array = getEveryDayData("白业对治") case "本月": lineChart.setXLabels(["", "", "", "", "", "", "", "", "", "10", "", "", "", "", "", "", "", "", "", "20", "", "", "", "", "", "", "", "", "", "30", ""], withWidth: (view.frame.width - 75) / 32) data01Array = getEveryDayData("黑业") data02Array = getEveryDayData("黑业对治") data03Array = getEveryDayData("白业") data04Array = getEveryDayData("白业对治") case "本年": lineChart.setXLabels(["", "", "", "", "5", "", "", "", "", "10", "", ""], withWidth: (view.frame.width - 75) / 13) data01Array = getEveryMonthData("黑业") data02Array = getEveryMonthData("黑业对治") data03Array = getEveryMonthData("白业") data04Array = getEveryMonthData("白业对治") default: break } lineChart.showCoordinateAxis = true lineChart.yFixedValueMin = 0.0 lineChart.backgroundColor = UIColor.clearColor() lineChart.axisColor = UIColor.lightGrayColor() let data01 = PNLineChartData() data01.inflexionPointStyle = PNLineChartPointStyle.Circle; data01.inflexionPointWidth = 2 data01.dataTitle = "黑业" data01.color = UIColor.blackColor() data01.itemCount = UInt(data01Array.count) data01.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data01Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data02 = PNLineChartData() data02.inflexionPointStyle = PNLineChartPointStyle.Circle; data02.inflexionPointWidth = 2 data02.dataTitle = "黑业对治" data02.color = UIColor.greenColor() data02.itemCount = UInt(data02Array.count) data02.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data02Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data03 = PNLineChartData() data03.inflexionPointStyle = PNLineChartPointStyle.Circle; data03.inflexionPointWidth = 2 data03.dataTitle = "白业" data03.color = UIColor.whiteColor() data03.itemCount = UInt(data03Array.count) data03.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data03Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data04 = PNLineChartData() data04.inflexionPointStyle = PNLineChartPointStyle.Circle; data04.inflexionPointWidth = 2 data04.dataTitle = "白业对治" data04.color = UIColor.redColor() data04.itemCount = UInt(data04Array.count) data04.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data04Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } lineChart.chartData = [data01, data02, data03, data04] lineChart.strokeChart() lineChart.legendStyle = PNLegendItemStyle.Stacked lineChart.legendFont = UIFont.boldSystemFontOfSize(12.0) lineChart.legendFontColor = UIColor.lightGrayColor() let legend = lineChart.getLegendWithMaxWidth(320) legend.frame = CGRect(x: 100, y: view.frame.height - 280, width: legend.frame.size.width, height: legend.frame.size.height) lineChart.addSubview(legend) default: break } } } func getEveryDayData(type: String) -> [NSNumber] { var result = [NSNumber]() let dayDuration = Double(60 * 60 * 24) var startDay = dateRange[0] while startDay < dateRange[1] { result.append(realm.objects(Industry).filter("type = %@ AND time BETWEEN {%@, %@}", type, startDay, startDay + dayDuration - 1).count) startDay += dayDuration } return result } func getEveryMonthData(type: String) -> [NSNumber] { var result = [NSNumber]() let calendar = NSCalendar.currentCalendar() let monthComponent = NSDateComponents() monthComponent.month = 1; var startDay = dateRange[0] while startDay < dateRange[1] { let nextStartDay = calendar.dateByAddingComponents(monthComponent, toDate: NSDate(timeIntervalSince1970: startDay), options: NSCalendarOptions())!.timeIntervalSince1970 result.append(realm.objects(Industry).filter("type = %@ AND time BETWEEN {%@, %@}", type, startDay, nextStartDay - 1).count) startDay = nextStartDay } return result } }
gpl-2.0
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift
57
2189
// // DistinctUntilChanged.swift // RxSwift // // Created by Krunoslav Zaher on 3/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType { typealias E = O.E private let _parent: DistinctUntilChanged<E, Key> private var _currentKey: Key? = nil init(parent: DistinctUntilChanged<E, Key>, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .next(let value): do { let key = try _parent._selector(value) var areEqual = false if let currentKey = _currentKey { areEqual = try _parent._comparer(currentKey, key) } if areEqual { return } _currentKey = key forwardOn(event) } catch let error { forwardOn(.error(error)) dispose() } case .error, .completed: forwardOn(event) dispose() } } } class DistinctUntilChanged<Element, Key>: Producer<Element> { typealias KeySelector = (Element) throws -> Key typealias EqualityComparer = (Key, Key) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _selector: KeySelector fileprivate let _comparer: EqualityComparer init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { _source = source _selector = selector _comparer = comparer } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
PLJNS/TZStackView
TZStackView/TZStackView.swift
1
25972
// // TZStackView.swift // TZStackView // // Created by Tom van Zummeren on 10/06/15. // Copyright © 2015 Tom van Zummeren. All rights reserved. // import UIKit struct TZAnimationDidStopQueueEntry: Equatable { let view: UIView let hidden: Bool } func ==(lhs: TZAnimationDidStopQueueEntry, rhs: TZAnimationDidStopQueueEntry) -> Bool { return lhs.view === rhs.view } @IBDesignable public class TZStackView: UIView { public var distribution: TZStackViewDistribution = .Fill { didSet { setNeedsUpdateConstraints() } } public var axis: UILayoutConstraintAxis = .Horizontal { didSet { setNeedsUpdateConstraints() } } public var alignment: TZStackViewAlignment = .Fill public var spacing: CGFloat = 0 public var layoutMarginsRelativeArrangement = false public var arrangedSubviews: [UIView] = [] { didSet { setNeedsUpdateConstraints() registerHiddenListeners(oldValue) } } private var kvoContext = UInt8() private var stackViewConstraints = [NSLayoutConstraint]() private var subviewConstraints = [NSLayoutConstraint]() private var spacerViews = [UIView]() private var animationDidStopQueueEntries = [TZAnimationDidStopQueueEntry]() private var registeredKvoSubviews = [UIView]() private var animatingToHiddenViews = [UIView]() public override init(frame: CGRect) { super.init(frame: CGRectZero) } public init(arrangedSubviews: [UIView] = []) { super.init(frame: CGRectZero) for arrangedSubview in arrangedSubviews { arrangedSubview.translatesAutoresizingMaskIntoConstraints = false addSubview(arrangedSubview) } // Closure to invoke didSet() { self.arrangedSubviews = arrangedSubviews }() } deinit { // This removes `hidden` value KVO observers using didSet() { self.arrangedSubviews = [] }() } private func registerHiddenListeners(previousArrangedSubviews: [UIView]) { for subview in previousArrangedSubviews { self.removeHiddenListener(subview) } for subview in arrangedSubviews { self.addHiddenListener(subview) } } private func addHiddenListener(view: UIView) { view.addObserver(self, forKeyPath: "hidden", options: [.Old, .New], context: &kvoContext) registeredKvoSubviews.append(view) } private func removeHiddenListener(view: UIView) { if let index = registeredKvoSubviews.indexOf(view) { view.removeObserver(self, forKeyPath: "hidden", context: &kvoContext) registeredKvoSubviews.removeAtIndex(index) } } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let view = object as? UIView, change = change where keyPath == "hidden" { let hidden = view.hidden let previousValue = change["old"] as! Bool if hidden == previousValue { return } if hidden { animatingToHiddenViews.append(view) } // Perform the animation setNeedsUpdateConstraints() setNeedsLayout() layoutIfNeeded() removeHiddenListener(view) view.hidden = false if let _ = view.layer.animationKeys() { UIView.setAnimationDelegate(self) animationDidStopQueueEntries.insert(TZAnimationDidStopQueueEntry(view: view, hidden: hidden), atIndex: 0) UIView.setAnimationDidStopSelector("hiddenAnimationStopped") } else { didFinishSettingHiddenValue(view, hidden: hidden) } } } private func didFinishSettingHiddenValue(arrangedSubview: UIView, hidden: Bool) { arrangedSubview.hidden = hidden if let index = animatingToHiddenViews.indexOf(arrangedSubview) { animatingToHiddenViews.removeAtIndex(index) } addHiddenListener(arrangedSubview) } func hiddenAnimationStopped() { var queueEntriesToRemove = [TZAnimationDidStopQueueEntry]() for entry in animationDidStopQueueEntries { let view = entry.view if view.layer.animationKeys() == nil { didFinishSettingHiddenValue(view, hidden: entry.hidden) queueEntriesToRemove.append(entry) } } for entry in queueEntriesToRemove { if let index = animationDidStopQueueEntries.indexOf(entry) { animationDidStopQueueEntries.removeAtIndex(index) } } } public func addArrangedSubview(view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.append(view) } public func removeArrangedSubview(view: UIView) { if let index = arrangedSubviews.indexOf(view) { arrangedSubviews.removeAtIndex(index) } } public func insertArrangedSubview(view: UIView, atIndex stackIndex: Int) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.insert(view, atIndex: stackIndex) } override public func willRemoveSubview(subview: UIView) { removeArrangedSubview(subview) } override public func updateConstraints() { removeConstraints(stackViewConstraints) stackViewConstraints.removeAll() for arrangedSubview in arrangedSubviews { arrangedSubview.removeConstraints(subviewConstraints) } subviewConstraints.removeAll() for arrangedSubview in arrangedSubviews { if alignment != .Fill { let guideConstraint: NSLayoutConstraint switch axis { case .Horizontal: guideConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) case .Vertical: guideConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) } subviewConstraints.append(guideConstraint) arrangedSubview.addConstraint(guideConstraint) } if isHidden(arrangedSubview) { let hiddenConstraint: NSLayoutConstraint switch axis { case .Horizontal: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0) case .Vertical: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0) } subviewConstraints.append(hiddenConstraint) arrangedSubview.addConstraint(hiddenConstraint) } } for spacerView in spacerViews { spacerView.removeFromSuperview() } spacerViews.removeAll() if arrangedSubviews.count > 0 { let visibleArrangedSubviews = arrangedSubviews.filter({!self.isHidden($0)}) switch distribution { case .FillEqually, .Fill, .FillProportionally: if alignment != .Fill || layoutMarginsRelativeArrangement { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() if alignment == .FirstBaseline && axis == .Horizontal { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } if distribution == .FillEqually { stackViewConstraints += createFillEquallyConstraints(arrangedSubviews) } if distribution == .FillProportionally { stackViewConstraints += createFillProportionallyConstraints(arrangedSubviews) } stackViewConstraints += createFillConstraints(arrangedSubviews, constant: spacing) case .EqualSpacing: var views = [UIView]() var index = 0 for arrangedSubview in arrangedSubviews { if isHidden(arrangedSubview) { continue } if index > 0 { views.append(addSpacerView()) } views.append(arrangedSubview) index++ } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } stackViewConstraints += createFillConstraints(views, constant: 0) stackViewConstraints += createFillEquallyConstraints(spacerViews) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) case .EqualCentering: for (index, _) in visibleArrangedSubviews.enumerate() { if index > 0 { addSpacerView() } } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } var previousArrangedSubview: UIView? for (index, arrangedSubview) in visibleArrangedSubviews.enumerate() { if let previousArrangedSubview = previousArrangedSubview { let spacerView = spacerViews[index - 1] switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Leading)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Trailing)) case .Vertical: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Top)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Bottom)) } } previousArrangedSubview = arrangedSubview } stackViewConstraints += createFillEquallyConstraints(spacerViews, priority: 150) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) } if spacerViews.count > 0 { stackViewConstraints += createSurroundingSpacerViewConstraints(spacerViews[0], views: visibleArrangedSubviews) } if layoutMarginsRelativeArrangement { if spacerViews.count > 0 { stackViewConstraints.append(constraint(item: self, attribute: .BottomMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .LeftMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .RightMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .TopMargin, toItem: spacerViews[0])) } } addConstraints(stackViewConstraints) } super.updateConstraints() } override public func prepareForInterfaceBuilder() { } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } private func addSpacerView() -> TZSpacerView { let spacerView = TZSpacerView() spacerView.translatesAutoresizingMaskIntoConstraints = false spacerViews.append(spacerView) insertSubview(spacerView, atIndex: 0) return spacerView } private func createSurroundingSpacerViewConstraints(spacerView: UIView, views: [UIView]) -> [NSLayoutConstraint] { if alignment == .Fill { return [] } var topPriority: Float = 1000 var topRelation: NSLayoutRelation = .LessThanOrEqual var bottomPriority: Float = 1000 var bottomRelation: NSLayoutRelation = .GreaterThanOrEqual if alignment == .Top || alignment == .Leading { topPriority = 999.5 topRelation = .Equal } if alignment == .Bottom || alignment == .Trailing { bottomPriority = 999.5 bottomRelation = .Equal } var constraints = [NSLayoutConstraint]() for view in views { switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Top, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Bottom, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Leading, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Trailing, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) } } switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) } return constraints } private func createFillProportionallyConstraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var totalSize: CGFloat = 0 var totalCount = 0 for arrangedSubview in views { if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: totalSize += arrangedSubview.intrinsicContentSize().width case .Vertical: totalSize += arrangedSubview.intrinsicContentSize().height } totalCount++ } totalSize += (CGFloat(totalCount - 1) * spacing) var priority: Float = 1000 let countDownPriority = (views.filter({!self.isHidden($0)}).count > 1) for arrangedSubview in views { if countDownPriority { priority-- } if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: let multiplier = arrangedSubview.intrinsicContentSize().width / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Width, toItem: self, multiplier: multiplier, priority: priority)) case .Vertical: let multiplier = arrangedSubview.intrinsicContentSize().height / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Height, toItem: self, multiplier: multiplier, priority: priority)) } } return constraints } // Matchs all Width or Height attributes of all given views private func createFillEquallyConstraints(views: [UIView], priority: Float = 1000) -> [NSLayoutConstraint] { switch axis { case .Horizontal: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Width, priority: priority) case .Vertical: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Height, priority: priority) } } // Chains together the given views using Leading/Trailing or Top/Bottom private func createFillConstraints(views: [UIView], priority: Float = 1000, relatedBy relation: NSLayoutRelation = .Equal, constant: CGFloat) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var previousView: UIView? for view in views { if let previousView = previousView { var c: CGFloat = 0 if !isHidden(previousView) && !isHidden(view) { c = constant } else if isHidden(previousView) && !isHidden(view) && views.first != previousView { c = (constant / 2) } else if isHidden(view) && !isHidden(previousView) && views.last != view { c = (constant / 2) } switch axis { case .Horizontal: constraints.append(constraint(item: view, attribute: .Leading, relatedBy: relation, toItem: previousView, attribute: .Trailing, constant: c, priority: priority)) case .Vertical: constraints.append(constraint(item: view, attribute: .Top, relatedBy: relation, toItem: previousView, attribute: .Bottom, constant: c, priority: priority)) } } previousView = view } return constraints } // Matches all Bottom/Top or Leading Trailing constraints of te given views and matches those attributes of the first/last view to the container private func createMatchEdgesContraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() switch axis { case .Horizontal: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Bottom) constraints += equalAttributes(views: views, attribute: .Top) case .Center: constraints += equalAttributes(views: views, attribute: .CenterY) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Top) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Bottom) case .FirstBaseline: constraints += equalAttributes(views: views, attribute: .FirstBaseline) } case .Vertical: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Leading) constraints += equalAttributes(views: views, attribute: .Trailing) case .Center: constraints += equalAttributes(views: views, attribute: .CenterX) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Leading) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Trailing) case .FirstBaseline: constraints += [] } } return constraints } private func createFirstAndLastViewMatchEdgesContraints() -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() let visibleViews = arrangedSubviews.filter({!self.isHidden($0)}) let firstView = visibleViews.first let lastView = visibleViews.last var topView = arrangedSubviews.first! var bottomView = arrangedSubviews.first! if spacerViews.count > 0 { if alignment == .Center { topView = spacerViews[0] bottomView = spacerViews[0] } else if alignment == .Top || alignment == .Leading { bottomView = spacerViews[0] } else if alignment == .Bottom || alignment == .Trailing { topView = spacerViews[0] } else if alignment == .FirstBaseline { switch axis { case .Horizontal: bottomView = spacerViews[0] case .Vertical: topView = spacerViews[0] bottomView = spacerViews[0] } } } let firstItem = layoutMarginsRelativeArrangement ? spacerViews[0] : self switch axis { case .Horizontal: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Top, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterY, toItem: arrangedSubviews.first!)) } case .Vertical: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Top, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterX, toItem: arrangedSubviews.first!)) } } return constraints } private func equalAttributes(views views: [UIView], attribute: NSLayoutAttribute, priority: Float = 1000) -> [NSLayoutConstraint] { var currentPriority = priority var constraints = [NSLayoutConstraint]() if views.count > 0 { var firstView: UIView? let countDownPriority = (currentPriority < 1000) for view in views { if let firstView = firstView { constraints.append(constraint(item: firstView, attribute: attribute, toItem: view, priority: currentPriority)) } else { firstView = view } if countDownPriority { currentPriority-- } } } return constraints } // Convenience method to help make NSLayoutConstraint in a less verbose way private func constraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation = .Equal, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant c: CGFloat = 0, priority: Float = 1000) -> NSLayoutConstraint { let attribute2 = attr2 != nil ? attr2! : attr1 let constraint = NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attribute2, multiplier: multiplier, constant: c) constraint.priority = priority return constraint } private func isHidden(view: UIView) -> Bool { if view.hidden { return true } return animatingToHiddenViews.indexOf(view) != nil } }
mit
garywong89/PetStoreAPI
src/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift
4
1121
// APIHelper.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // class APIHelper { static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { var destination = [String:AnyObject]() for (key, nillableValue) in source { if let value: AnyObject = nillableValue { destination[key] = value } } if destination.isEmpty { return nil } return destination } static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { guard let source = source else { return nil } var destination = [String:AnyObject]() let theTrue = NSNumber(bool: true) let theFalse = NSNumber(bool: false) for (key, value) in source { switch value { case let x where x === theTrue || x === theFalse: destination[key] = "\(value as! Bool)" default: destination[key] = value } } return destination } }
apache-2.0
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Structs/Contract.swift
1
3407
// // Contract.swift // MoyskladNew // // Created by Anton Efimenko on 24.10.16. // Copyright © 2016 Andrey Parshakov. All rights reserved. // //import Money import Foundation public enum MSContractType : String { case commission = "Commission" case sales = "Sales" } public enum MSRewardType : String { case percentOfSales = "PercentOfSales" case none = "None" } /** Represents Contract. Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#договор) */ public class MSContract: MSAttributedEntity, Metable { public var meta: MSMeta public var id : MSID public var info : MSInfo public var accountId: String public var owner: MSEntity<MSEmployee>? public var shared: Bool public var group: MSEntity<MSGroup> public var code: String? public var externalCode: String? public var archived: Bool public var moment: Date? public var sum: Money public var contractType: MSContractType? public var rewardType: MSRewardType? public var rewardPercent: Int? public var ownAgent: MSEntity<MSAgent>? public var agent: MSEntity<MSAgent>? public var state: MSEntity<MSState>? public var organizationAccount: MSEntity<MSAccount>? public var agentAccount: MSEntity<MSAccount>? public var rate: MSRate? public init(meta: MSMeta, id : MSID, info : MSInfo, accountId: String, owner: MSEntity<MSEmployee>?, shared: Bool, group: MSEntity<MSGroup>, code: String?, externalCode: String?, archived: Bool, moment: Date?, sum: Money, contractType: MSContractType?, rewardType: MSRewardType?, rewardPercent: Int?, ownAgent: MSEntity<MSAgent>?, agent: MSEntity<MSAgent>?, state: MSEntity<MSState>?, organizationAccount: MSEntity<MSAccount>?, agentAccount: MSEntity<MSAccount>?, rate: MSRate?, attributes: [MSEntity<MSAttribute>]?) { self.meta = meta self.id = id self.info = info self.accountId = accountId self.owner = owner self.shared = shared self.group = group self.code = code self.externalCode = externalCode self.archived = archived self.moment = moment self.sum = sum self.contractType = contractType self.rewardType = rewardType self.rewardPercent = rewardPercent self.ownAgent = ownAgent self.agent = agent self.state = state self.organizationAccount = organizationAccount self.agentAccount = agentAccount self.rate = rate super.init(attributes: attributes) } public func copy() -> MSContract { return MSContract(meta: meta.copy(), id: id.copy(), info: info, accountId: accountId, owner: owner, shared: shared, group: group, code: code, externalCode: externalCode, archived: archived, moment: moment, sum: sum, contractType: contractType, rewardType: rewardType, rewardPercent: rewardPercent, ownAgent: ownAgent, agent: agent, state: state, organizationAccount: organizationAccount, agentAccount: agentAccount, rate: rate, attributes: attributes) } public func hasChanges(comparedTo other: MSContract) -> Bool { return (try? JSONSerialization.data(withJSONObject: dictionary(metaOnly: false), options: [])) ?? nil == (try? JSONSerialization.data(withJSONObject: other.dictionary(metaOnly: false), options: [])) ?? nil } }
mit
tsraveling/TSRConvenience
TSRConvenienceTests/TSRConvenienceTests.swift
1
1000
// // TSRConvenienceTests.swift // TSRConvenienceTests // // Created by Timothy Raveling on 9/2/16. // Copyright © 2016 TSRaveling. All rights reserved. // import XCTest @testable import TSRConvenience class TSRConvenienceTests: 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.measure { // Put the code you want to measure the time of here. } } }
mit
gcba/hermes
sdks/swift/Pods/SwifterSwift/Sources/Extensions/Foundation/IntExtensions.swift
1
5795
// // IntExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Properties public extension Int { /// SwifterSwift: CountableRange 0..<Int. public var countableRange: CountableRange<Int> { return 0..<self } /// SwifterSwift: Radian value of degree input. public var degreesToRadians: Double { return Double.pi * Double(self) / 180.0 } /// SwifterSwift: Degree value of radian input public var radiansToDegrees: Double { return Double(self) * 180 / Double.pi } /// SwifterSwift: Number of digits of integer value. public var digitsCount: Int { return String(self).characters.count } /// SwifterSwift: UInt. public var uInt: UInt { return UInt(self) } /// SwifterSwift: Double. public var double: Double { return Double(self) } /// SwifterSwift: Float. public var float: Float { return Float(self) } /// SwifterSwift: CGFloat. public var cgFloat: CGFloat { return CGFloat(self) } /// SwifterSwift: Roman numeral string from integer (if applicable). public var romanNumeral: String? { // https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7 guard self > 0 else { // there is no roman numerals for 0 or negative numbers return nil } let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] var romanValue = "" var startingValue = self for (index, romanChar) in romanValues.enumerated() { let arabicValue = arabicValues[index] let div = startingValue / arabicValue if (div > 0) { for _ in 0..<div { romanValue += romanChar } startingValue -= arabicValue * div } } return romanValue } /// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..) public var kFormatted: String { var sign: String { return self >= 0 ? "" : "-" } let abs = self.abs if abs == 0 { return "0k" } else if abs >= 0 && abs < 1000 { return "0k" } else if abs >= 1000 && abs < 1000000 { return String(format: "\(sign)%ik", abs / 1000) } return String(format: "\(sign)%ikk", abs / 100000) } } // MARK: - Methods public extension Int { /// SwifterSwift: Random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. /// - Returns: random double between two double values. public static func random(between min: Int, and max: Int) -> Int { return random(inRange: min...max) } /// SwifterSwift: Random integer in a closed interval range. /// /// - Parameter range: closed interval range. /// - Returns: random double in the given closed range. public static func random(inRange range: ClosedRange<Int>) -> Int { let delta = UInt32(range.upperBound - range.lowerBound + 1) return range.lowerBound + Int(arc4random_uniform(delta)) } /// SwifterSwift: check if given integer prime or not. /// Warning: Using big numbers can be computationally expensive! /// - Returns: true or false depending on prime-ness public func isPrime() -> Bool { guard self > 1 || self % 2 == 0 else { return false } // To improve speed on latter loop :) if self == 2 { return true } // Explanation: It is enough to check numbers until // the square root of that number. If you go up from N by one, // other multiplier will go 1 down to get similar result // (integer-wise operation) such way increases speed of operation let base = Int(sqrt(Double(self)) + 1) for i in Swift.stride(from: 3, to: base, by: 2) { if self % i == 0 { return false } } return true } } // MARK: - Initializers public extension Int { /// SwifterSwift: Created a random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. public init(randomBetween min: Int, and max: Int) { self = Int.random(between: min, and: max) } /// SwifterSwift: Create a random integer in a closed interval range. /// /// - Parameter range: closed interval range. public init(randomInRange range: ClosedRange<Int>) { self = Int.random(inRange: range) } } // MARK: - Operators precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ** : PowerPrecedence /// SwifterSwift: Value of exponentiation. /// /// - Parameters: /// - lhs: base integer. /// - rhs: exponent integer. /// - Returns: exponentiation result (example: 2 ** 3 = 8). public func ** (lhs: Int, rhs: Int) -> Double { // http://nshipster.com/swift-operators/ return pow(Double(lhs), Double(rhs)) } prefix operator √ /// SwifterSwift: Square root of integer. /// /// - Parameter int: integer value to find square root for /// - Returns: square root of given integer. public prefix func √ (int: Int) -> Double { // http://nshipster.com/swift-operators/ return sqrt(Double(int)) } infix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameters: /// - lhs: integer number. /// - rhs: integer number. /// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)). public func ± (lhs: Int, rhs: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return (lhs + rhs, lhs - rhs) } prefix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameter int: integer number /// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)). public prefix func ± (int: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return 0 ± int }
mit
nicksnyder/iOS-UIWebView-vs-UITableView
Tab/Tab/TabBarController.swift
1
1285
// // Created by Nick Snyder on 4/28/15. // Copyright (c) 2015 Example. All rights reserved. // import UIKit class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.viewControllers = [ TabViewController(url: nil, backgroundColor: UIColor.yellowColor(), tabBarItem: UITabBarItem(title: "Reset", image: nil, selectedImage: nil)), //TabViewController(url: urlForHtmlFileNamed("list")!, backgroundColor: UIColor.blueColor(), tabBarItem: UITabBarItem(tabBarSystemItem: .Contacts, tag: 1)), TabViewController(url: urlForHtmlFileNamed("list10")!, backgroundColor: UIColor.blueColor(), tabBarItem: UITabBarItem(title: "UIWebView 10", image: nil, selectedImage: nil)), TabViewController(url: urlForHtmlFileNamed("list20")!, backgroundColor: UIColor.blueColor(), tabBarItem: UITabBarItem(title: "UIWebView 20", image: nil, selectedImage: nil)), TabViewController(url: urlForHtmlFileNamed("list100")!, backgroundColor: UIColor.blueColor(), tabBarItem: UITabBarItem(title: "UIWebView 100", image: nil, selectedImage: nil)), TableViewController() ] } private func urlForHtmlFileNamed(name: String) -> NSURL? { return NSBundle.mainBundle().URLForResource(name, withExtension: "html") } }
mit
TENDIGI/Obsidian-UI-iOS
src/Permissions.swift
1
8264
// // Permissions.swift // Alfredo // // Created by Eric Kunz on 8/14/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation import AddressBook import EventKit import CoreLocation import AVFoundation import Photos /// Easily acces the app's permissions to open class Permissions { public enum PermissionStatus { case authorized, unauthorized, unknown, disabled } // MARK: Constants fileprivate let AskedForNotificationsDefaultsKey = "AskedForNotificationsDefaultsKey" // MARK: Managers lazy var locationManager = CLLocationManager() // MARK:- Permissions // MARK: Contacts /// The authorization status of access to the device's contacts. open func authorizationStatusContacts() -> PermissionStatus { let status = ABAddressBookGetAuthorizationStatus() switch status { case .authorized: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationContacts() { switch authorizationStatusContacts() { case .unknown: ABAddressBookRequestAccessWithCompletion(nil, nil) default: break } } // MARK: Location Always /// The authorization status of access to the device's location at all times. open func authorizationStatusLocationAlways() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .disabled } let status = CLLocationManager.authorizationStatus() switch status { case .authorizedAlways: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined, .authorizedWhenInUse: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationLocationAlways() -> Bool { switch authorizationStatusLocationAlways() { case .unknown: locationManager.requestAlwaysAuthorization() return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Location While In Use /// The authorization status of access to the device's location. open func authorizationStatusLocationInUse() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .disabled } let status = CLLocationManager.authorizationStatus() switch status { case .authorizedWhenInUse, .authorizedAlways: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationLocationInUse() -> Bool { switch authorizationStatusLocationAlways() { case .unknown: locationManager.requestAlwaysAuthorization() return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Notifications /// The authorization status of the app receiving notifications. open func authorizationStatusNotifications() -> PermissionStatus { let settings = UIApplication.shared.currentUserNotificationSettings if settings?.types != UIUserNotificationType() { return .authorized } else { if UserDefaults.standard.bool(forKey: AskedForNotificationsDefaultsKey) { return .unauthorized } else { return .unknown } } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationNotifications() -> Bool { switch authorizationStatusNotifications() { case .unknown: let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Photos /// The authorization status for access to the photo library. open func authorizationStatusPhotos() -> PermissionStatus { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: return .authorized case .denied, .restricted: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationStatusPhotos() -> Bool { let status = authorizationStatusPhotos() switch status { case .unknown: PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) -> Void in } return true case .authorized, .disabled, .unauthorized: return false } } // MARK: Camera /// The authorization status for use of the camera. open func authorizationStatusCamera() -> PermissionStatus { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch status { case .authorized: return .authorized case .denied, .restricted: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationStatusCamera() -> Bool { let status = authorizationStatusCamera() switch status { case .unknown: AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in }) return true case .disabled, .unauthorized, .authorized: return false } } // MARK: System Settings /** Opens the app's system settings If the app has its own settings bundle they will be opened, else the main settings view will be presented. */ open func openAppSettings() { let url = URL(string: UIApplicationOpenSettingsURLString)! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } }
mit
lorismaz/LaDalle
LaDalle/LaDalle/BusinessDetailsViewController.swift
1
6334
// // BusinessDetailsViewController.swift // LaDalle // // Created by Loris Mazloum on 9/16/16. // Copyright © 2016 Loris Mazloum. All rights reserved. // import UIKit import MapKit import CoreLocation class BusinessDetailsViewController: UIViewController, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource { //MARK: Global Declarations var business: Business? var userLocation: CLLocation? var reviews: [Review] = [Review]() //MARK: Properties and Outlets @IBOutlet weak var businessMapView: MKMapView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var businessReviewImageView: UIImageView! @IBOutlet weak var businessReviewCountLabel: UILabel! @IBOutlet weak var reviewTableView: UITableView! @IBAction func actionButtonTapped(_ sender: UIBarButtonItem) { shareSheetController() } //MARK: - Annotations //MARK: - Overlays //MARK: - Map setup //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() guard let currentBusiness = business else { return } currentBusiness.getReviews(completionHandler: { (reviews) in self.main.addOperation { self.reviews = reviews for review in reviews { print("Review: \(review.text)") //self.businessReviewLabel.text = review.text } self.reviewTableView.reloadData() } }) //Delegates reviewTableView.delegate = self reviewTableView.dataSource = self // set estimated height reviewTableView.estimatedRowHeight = 95.0 // set automaticdimension reviewTableView.rowHeight = UITableViewAutomaticDimension businessMapView.delegate = self populateBusinessInfo() addAnnotation() zoomToBusinessLocation() } //The Main OperationQueue is where any UI changes or updates happen private let main = OperationQueue.main //The Async OperationQueue is where any background tasks such as //Loading from the network, and parsing JSON happen. //This makes sure the Main UI stays sharp, responsive, and smooth private let async: OperationQueue = { //The Queue is being created by this closure let operationQueue = OperationQueue() //This represents how many tasks can run at the same time, in this case 8 tasks //That means that we can load 8 images at a time operationQueue.maxConcurrentOperationCount = 8 return operationQueue }() func zoomToBusinessLocation() { guard let currentBusiness = self.business else { return } guard let userLocation = self.userLocation else { return } let businessLocation = CLLocation(latitude: currentBusiness.coordinate.latitude, longitude: currentBusiness.coordinate.longitude) //get distance between user and business let distanceFromBusiness = userLocation.distance(from: businessLocation) print("Distance: \(distanceFromBusiness) meters") //let distanceFromBusiness = userCoordinate.distance(from: currentBusiness.coordinate) let regionRadius: CLLocationDistance = distanceFromBusiness * 10 print("Region Radius: \(regionRadius) meters") let coordinateRegion = MKCoordinateRegionMakeWithDistance(businessLocation.coordinate, regionRadius, regionRadius) businessMapView.setRegion(coordinateRegion, animated: true) } func addAnnotation(){ guard let currentBusiness = business else { return } businessMapView.addAnnotation(currentBusiness) } func populateBusinessInfo() { guard let business = business else { return } businessNameLabel.text = business.name let ratingImageName = Business.getRatingImage(rating: business.rating) businessReviewImageView.image = UIImage(named: ratingImageName) //businessReviewImageView.image businessReviewCountLabel.text = "Based on " + String(business.reviewCount) + " reviews." } func shareSheetController() { guard let business = business else { return } var activities: [Any] = [] let message = "Trying out \(business.name), thanks to La Dalle by @lorismaz & the new @Yelp Fusion API" activities.append(message) if let image: UIImage = Business.getImage(from: business.imageUrl) { activities.append(image) } if business.url != "" { activities.append(business.url) } let shareSheet = UIActivityViewController(activityItems: activities, applicationActivities: nil) shareSheet.excludedActivityTypes = [ UIActivityType.postToWeibo, UIActivityType.mail, UIActivityType.print, UIActivityType.copyToPasteboard, UIActivityType.assignToContact, UIActivityType.saveToCameraRoll, UIActivityType.addToReadingList, UIActivityType.postToFlickr, UIActivityType.postToVimeo, UIActivityType.postToTencentWeibo ] present(shareSheet, animated: true, completion: nil) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return reviews.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = indexPath.row let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell", for: indexPath) as! ReviewCell // Get current row's category let review = reviews[row] // Design the cell cell.reviewContentTextView.text = review.text cell.userNameLabel.text = review.user.name return cell } }
mit
manikad24/JASidePanelsSwift
JASidePanelsSwift/Classes/UIViewController+JASidePanel.swift
1
885
// // UIViewController+JASidePanel.swift // Pods // // Created by Manikandan Prabhu on 18/11/16. // // import Foundation import UIKit extension UIViewController{ public func sidePanelController() -> JASidePanelController { var iter = self.parent while (iter != nil) { if (iter is JASidePanelController) { return (iter as! JASidePanelController) } else if (iter!.parent! != iter) { iter = iter!.parent! } else { iter = nil } } return JASidePanelController() } } extension Int { var f: CGFloat { return CGFloat(self) } } extension Float { var f: CGFloat { return CGFloat(self) } } extension Double { var f: CGFloat { return CGFloat(self) } } extension CGFloat { var swf: Float { return Float(self) } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/Cells/AudioMessageCell.swift
1
3803
// // AudioMessageCell.swift // Rocket.Chat // // Created by Filipe Alvarenga on 15/10/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import Foundation import AVFoundation import RocketChatViewController final class AudioMessageCell: BaseAudioMessageCell, SizingCell { static let identifier = String(describing: AudioMessageCell.self) static let sizingCell: UICollectionViewCell & ChatCell = { guard let cell = AudioMessageCell.instantiateFromNib() else { return AudioMessageCell() } return cell }() @IBOutlet weak var avatarContainerView: UIView! { didSet { avatarContainerView.layer.cornerRadius = 4 avatarView.frame = avatarContainerView.bounds avatarContainerView.addSubview(avatarView) } } @IBOutlet weak var viewPlayerBackground: UIView! { didSet { viewPlayerBackground.layer.borderWidth = 1 viewPlayerBackground.layer.cornerRadius = 4 } } @IBOutlet weak var username: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var statusView: UIImageView! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet weak var buttonPlay: UIButton! @IBOutlet weak var readReceiptButton: UIButton! @IBOutlet weak var slider: UISlider! { didSet { slider.value = 0 slider.setThumbImage(UIImage(named: "Player Progress Button"), for: .normal) } } @IBOutlet weak var labelAudioTime: UILabel! { didSet { labelAudioTime.font = labelAudioTime.font.bold() } } override var playing: Bool { didSet { updatePlayingState(with: buttonPlay) } } override var loading: Bool { didSet { updateLoadingState(with: activityIndicatorView, and: labelAudioTime) } } deinit { updateTimer?.invalidate() } override func awakeFromNib() { super.awakeFromNib() updateTimer = setupPlayerTimer(with: slider, and: labelAudioTime) insertGesturesIfNeeded(with: username) } override func configure(completeRendering: Bool) { configure(readReceipt: readReceiptButton) configure( with: avatarView, date: date, status: statusView, and: username, completeRendering: completeRendering ) if completeRendering { updateAudio() } } override func prepareForReuse() { super.prepareForReuse() slider.value = 0 labelAudioTime.text = "--:--" playing = false loading = false } // MARK: IBAction @IBAction func didStartSlidingSlider(_ sender: UISlider) { startSlidingSlider(sender) } @IBAction func didFinishSlidingSlider(_ sender: UISlider) { finishSlidingSlider(sender) } @IBAction func didPressPlayButton(_ sender: UIButton) { pressPlayButton(sender) } } // MARK: Theming extension AudioMessageCell { override func applyTheme() { super.applyTheme() let theme = self.theme ?? .light date.textColor = theme.auxiliaryText username.textColor = theme.titleText viewPlayerBackground.backgroundColor = theme.chatComponentBackground labelAudioTime.textColor = theme.auxiliaryText updatePlayingState(with: buttonPlay) viewPlayerBackground.layer.borderColor = theme.borderColor.cgColor } } // MARK: AVAudioPlayerDelegate extension AudioMessageCell { override func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { playing = false slider.value = 0.0 } }
mit
ben-ng/swift
stdlib/public/SDK/Intents/INStartWorkoutIntent.swift
1
1359
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) @available(iOS 10.0, *) extension INStartWorkoutIntent { @nonobjc public convenience init( workoutName: INSpeakableString? = nil, goalValue: Double? = nil, workoutGoalUnitType: INWorkoutGoalUnitType = .unknown, workoutLocationType: INWorkoutLocationType = .unknown, isOpenEnded: Bool? = nil ) { self.init(__workoutName: workoutName, goalValue: goalValue.map { NSNumber(value: $0) }, workoutGoalUnitType: workoutGoalUnitType, workoutLocationType: workoutLocationType, isOpenEnded: isOpenEnded.map { NSNumber(value: $0) }) } @nonobjc public final var goalValue: Double? { return __goalValue?.doubleValue } @nonobjc public final var isOpenEnded: Bool? { return __isOpenEnded?.boolValue } } #endif
apache-2.0
RobotRebels/Kratos2
Kratos2/Kratos2/Acronym.swift
1
495
// // Acronym.swift // Kratos2 // // Created by nbelopotapov on 17/05/17. // Copyright © 2017 RobotRebles. All rights reserved. // import UIKit class Acronym { var long: String = "" var short: String = "" var description: String = "" init() {} init(long: String, short: String, description: String) { self.long = long self.short = short self.description = description } init(dict: [String: AnyObject]?) { } }
mit
ben-ng/swift
test/SILGen/switch_fallthrough.swift
1
3645
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // 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 a() {} func b() {} func c() {} func d() {} func e() {} func f() {} func g() {} // CHECK-LABEL: sil hidden @_TF18switch_fallthrough5test1FT_T_ func test1() { switch foo() { // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], {{bb[0-9]+}} // CHECK: [[YES_CASE1]]: case foo(): // CHECK: function_ref @_TF18switch_fallthrough1aFT_T_ // CHECK: br [[CASE2:bb[0-9]+]] a() fallthrough case bar(): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF18switch_fallthrough1bFT_T_ // CHECK: br [[CASE3:bb[0-9]+]] b() fallthrough case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF18switch_fallthrough1cFT_T_ // CHECK: br [[CONT:bb[0-9]+]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF18switch_fallthrough1dFT_T_ d() } // Fallthrough should work even if the next case is normally unreachable // CHECK-LABEL: sil hidden @_TF18switch_fallthrough5test2FT_T_ func test2() { switch foo() { // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], {{bb[0-9]+}} // CHECK: [[YES_CASE1]]: case foo(): // CHECK: function_ref @_TF18switch_fallthrough1aFT_T_ // CHECK: br [[CASE2:bb[0-9]+]] a() fallthrough case _: // CHECK: [[CASE2]]: // CHECK: function_ref @_TF18switch_fallthrough1bFT_T_ // CHECK: br [[CASE3:bb[0-9]+]] b() fallthrough case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF18switch_fallthrough1cFT_T_ // CHECK: br [[CONT:bb[0-9]+]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF18switch_fallthrough1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF18switch_fallthrough5test3FT_T_ func test3() { switch (foo(), bar()) { // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], {{bb[0-9]+}} // CHECK: [[YES_CASE1]]: case (foo(), bar()): // CHECK: function_ref @_TF18switch_fallthrough1aFT_T_ // CHECK: br [[CASE2:bb[0-9]+]] a() fallthrough case (foo(), _): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF18switch_fallthrough1bFT_T_ // CHECK: br [[CASE3:bb[0-9]+]] b() fallthrough case (_, _): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF18switch_fallthrough1cFT_T_ // CHECK: br [[CASE4:bb[0-9]+]] c() fallthrough case (_, _): // CHECK: [[CASE4]]: // CHECK: function_ref @_TF18switch_fallthrough1dFT_T_ // CHECK: br [[CONT:bb[0-9]+]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF18switch_fallthrough1eFT_T_ e() } // Fallthrough should clean up nested pattern variables from the exited scope. func test4() { switch (foo(), bar()) { // CHECK: [[A:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int, Int)> // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], {{bb[0-9]+}} case var a where runced(): // CHECK: [[CASE1]]: // CHECK: br [[CASE2:bb[0-9]+]] fallthrough case _ where funged(): // CHECK: [[CASE2]]: // CHECK: br [[CONT:bb[0-9]+]] () // CHECK: [[B:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[C:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], case (var b, var c) where ansed(): // CHECK: [[CASE4]]: // CHECK: br [[CASE5:bb[0-9]+]] fallthrough case _: // CHECK: [[CASE5]]: // CHECK: br [[CONT]] () } // CHECK: [[CONT]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return }
apache-2.0
Rdxer/SnapKit
Sources/LayoutConstraintItem.swift
6
3013
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public protocol LayoutConstraintItem: AnyObject { } @available(iOS 9.0, OSX 10.11, *) extension ConstraintLayoutGuide : LayoutConstraintItem { } extension ConstraintView : LayoutConstraintItem { } extension LayoutConstraintItem { internal func prepare() { if let view = self as? ConstraintView { view.translatesAutoresizingMaskIntoConstraints = false } } internal var superview: ConstraintView? { if let view = self as? ConstraintView { return view.superview } if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { return guide.owningView } return nil } internal var constraints: [Constraint] { return self.constraintsSet.allObjects as! [Constraint] } internal func add(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.add(constraint) } } internal func remove(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.remove(constraint) } } private var constraintsSet: NSMutableSet { let constraintsSet: NSMutableSet if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { constraintsSet = existing } else { constraintsSet = NSMutableSet() objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraintsSet } } private var constraintsKey: UInt8 = 0
mit
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MaskCropper/View/MaskCropperUITheme.swift
1
147
public protocol MaskCropperUITheme { var maskCropperDiscardPhotoIcon: UIImage? { get } var maskCropperConfirmPhotoIcon: UIImage? { get } }
mit
sosaucily/rottentomatoes
rottentomatoes/ViewController.swift
1
4344
// // ViewController.swift // rottentomatoes // // Created by Jesse Smith on 9/14/14. // Copyright (c) 2014 Jesse Smith. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var movieTableView: UITableView! var refreshControl: UIRefreshControl! var moviesArray: NSArray? let RottenTomatoesAPIKey = "3ep56bczb367ku9hruf7xpdq" override func viewDidLoad() { super.viewDidLoad() self.getMovieData() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged) movieTableView.insertSubview(refreshControl, atIndex: 0) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (moviesArray != nil) ? moviesArray!.count : 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = movieTableView.dequeueReusableCellWithIdentifier("com.codepath.rottentomatoes.moviecell") as MovieTableViewCell let movieDictionary = self.moviesArray![indexPath.row] as NSDictionary cell.titleLabel.text = movieDictionary["title"] as NSString cell.descriptionLabel.text = movieDictionary["synopsis"] as NSString let postersDict = movieDictionary["posters"] as NSDictionary let thumbUrl = postersDict["thumbnail"] as NSString cell.thumbnailImageView.setImageWithURL(NSURL(string: thumbUrl)) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detailsViewController = MovieDetailsViewController(nibName: "MovieDetails", bundle: nil) let movieDictionary = self.moviesArray![indexPath.row] as NSDictionary let postersDict = movieDictionary["posters"] as NSDictionary let thumbUrl = postersDict["thumbnail"] as NSString detailsViewController.fullImageUrl = thumbUrl.stringByReplacingOccurrencesOfString("tmb", withString: "ori") detailsViewController.movieDescriptionDict = movieDictionary self.navigationController?.pushViewController(detailsViewController, animated: true) } func getMovieData() { let RottenTomatoesURLString = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=" + RottenTomatoesAPIKey let manager = AFHTTPRequestOperationManager() manager.GET(RottenTomatoesURLString, parameters: nil, success: self.updateViewWithMovies, failure: self.fetchMoviesError) let request = NSMutableURLRequest(URL: NSURL.URLWithString(RottenTomatoesURLString)) } func updateViewWithMovies(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void { self.moviesArray = responseObject["movies"] as? NSArray self.movieTableView.reloadData() self.refreshControl.endRefreshing() self.hideNetworkError() } func fetchMoviesError(operation: AFHTTPRequestOperation!, error: NSError!) -> Void { self.showNetworkError() self.refreshControl.endRefreshing() } func onRefresh() { self.getMovieData() } func showNetworkError() { if (self.view.subviews.count == 1) { var networkErrorView: UILabel = UILabel (frame:CGRectMake(0, 65, 0, 0)); networkErrorView.backgroundColor = UIColor.grayColor() networkErrorView.alpha = 0.9 networkErrorView.textColor = UIColor.blackColor() networkErrorView.font = UIFont.boldSystemFontOfSize(10) networkErrorView.text = "Network Error!" UIView.animateWithDuration(0.25, animations: { networkErrorView.frame = CGRectMake(0, 65, 320, 30) }) self.view.addSubview(networkErrorView) } } func hideNetworkError() { if (self.view.subviews.count == 2) { self.view.subviews[1].removeFromSuperview() } } }
mit
Zewo/Log
Source/LocationInfo.swift
1
1446
// Appender.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. public struct LocationInfo { public let file: String public let line: Int public let column: Int public let function: String } extension LocationInfo: CustomStringConvertible { public var description: String { return "\(file):\(function):\(line):\(column)" } }
mit
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/ServiceServer.swift
4
5516
/* * Copyright 2018, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Dispatch import Foundation import SwiftProtobuf open class ServiceServer { public let address: String public let server: Server public var shouldLogRequests = true fileprivate let servicesByName: [String: ServiceProvider] /// Create a server that accepts insecure connections. public init(address: String, serviceProviders: [ServiceProvider]) { gRPC.initialize() self.address = address server = Server(address: address) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Create a server that accepts secure connections. public init(address: String, certificateString: String, keyString: String, rootCerts: String? = nil, serviceProviders: [ServiceProvider]) { gRPC.initialize() self.address = address server = Server(address: address, key: keyString, certs: certificateString, rootCerts: rootCerts) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Create a server that accepts secure connections. public init?(address: String, certificateURL: URL, keyURL: URL, rootCertsURL: URL? = nil, serviceProviders: [ServiceProvider]) { guard let certificate = try? String(contentsOf: certificateURL, encoding: .utf8), let key = try? String(contentsOf: keyURL, encoding: .utf8) else { return nil } var rootCerts: String? if let rootCertsURL = rootCertsURL { guard let rootCertsString = try? String(contentsOf: rootCertsURL, encoding: .utf8) else { return nil } rootCerts = rootCertsString } gRPC.initialize() self.address = address server = Server(address: address, key: key, certs: certificate, rootCerts: rootCerts) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Start the server. public func start() { server.run { [weak self] handler in guard let strongSelf = self else { print("ERROR: ServiceServer has been asked to handle a request even though it has already been deallocated") return } let unwrappedMethod = handler.method ?? "(nil)" if strongSelf.shouldLogRequests == true { let unwrappedHost = handler.host ?? "(nil)" let unwrappedCaller = handler.caller ?? "(nil)" print("Server received request to " + unwrappedHost + " calling " + unwrappedMethod + " from " + unwrappedCaller + " with metadata " + handler.requestMetadata.dictionaryRepresentation.description) } do { do { let methodComponents = unwrappedMethod.components(separatedBy: "/") guard methodComponents.count >= 3 && methodComponents[0].isEmpty, let providerForServiceName = strongSelf.servicesByName[methodComponents[1]] else { throw HandleMethodError.unknownMethod } if let responseStatus = try providerForServiceName.handleMethod(unwrappedMethod, handler: handler), !handler.completionQueue.hasBeenShutdown { // The handler wants us to send the status for them; do that. // But first, ensure that all outgoing messages have been enqueued, to avoid ending the stream prematurely: handler.call.messageQueueEmpty.wait() try handler.sendStatus(responseStatus) } } catch _ as HandleMethodError { print("ServiceServer call to unknown method '\(unwrappedMethod)'") if !handler.completionQueue.hasBeenShutdown { // The method is not implemented by the service - send a status saying so. try handler.call.perform(OperationGroup( call: handler.call, operations: [ .sendInitialMetadata(Metadata()), .receiveCloseOnServer, .sendStatusFromServer(.unimplemented, "unknown method " + unwrappedMethod, Metadata()) ]) { _ in handler.shutdown() }) } } } catch { // The individual sessions' `run` methods (which are called by `self.handleMethod`) only throw errors if // they encountered an error that has not also been "seen" by the actual request handler implementation. // Therefore, this error is "really unexpected" and should be logged here - there's nowhere else to log it otherwise. print("ServiceServer unexpected error handling method '\(unwrappedMethod)': \(error)") do { if !handler.completionQueue.hasBeenShutdown { try handler.sendStatus((error as? ServerStatus) ?? .processingError) } } catch { print("ServiceServer unexpected error handling method '\(unwrappedMethod)'; sending status failed as well: \(error)") handler.shutdown() } } } } }
mit
DesenvolvimentoSwift/Taster
Taster/MapViewController.swift
1
2505
// // MapViewController.swift // pt.fca.Taster // // © 2016 Luis Marcelino e Catarina Silva // Desenvolvimento em Swift para iOS // FCA - Editora de Informática // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! var food:Food? override func viewDidLoad() { map.delegate = self map.showsUserLocation = true } override func viewWillAppear(_ animated: Bool) { showFoodsOnMap() } func showFoodsOnMap () { //map.removeAnnotations(self.map.annotations) for f in FoodRepository.repository.foods { if let loc = f.location { map.setRegion(MKCoordinateRegionMake(loc, MKCoordinateSpanMake(1, 1)), animated: true) let pin = CustomPin(coordinate: loc, food:f, title: f.name, subtitle: " ") self.map.addAnnotation(pin) } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "identifier" var annotationView:MKPinAnnotationView? if annotation.isKind(of: CustomPin.self) { annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView!.canShowCallout = true annotationView!.pinTintColor = UIColor.purple let btn = UIButton(type: .detailDisclosure) annotationView!.rightCalloutAccessoryView = btn } else { annotationView!.annotation = annotation } return annotationView } return nil } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let annotation = view.annotation as! CustomPin food = annotation.food self.performSegue(withIdentifier: "mapFoodDetail", sender: annotation) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? FoodDetailViewController { controller.food = food } } }
mit
tkremenek/swift
validation-test/compiler_crashers_fixed/27432-swift-typechecker-validatetype.swift
65
485
// 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 func c{{ class b{struct B<T where h:d{class a{class A{struct c class a{var:a{ var _=c{
apache-2.0
rxwei/Parsey
Sources/Parsey/Reducible.swift
1
611
// // Reducible.swift // Funky // // Created by Richard Wei on 8/27/16. // // public protocol Reducible { associatedtype Element func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result } public extension Reducible { public func mapReduce<Result: Associable>(_ transform: (Element) -> Result) -> Result { return reduce(Result.identity) { $0 + transform($1) } } } public extension Reducible where Element : Associable { @inline(__always) public func reduced() -> Element { return mapReduce{$0} } }
mit
yeahdongcn/RSBarcodes_Swift
Source/RSCodeDataMatrixGenerator.swift
1
257
// // RSCodeDataMatrixGenerator.swift // RSBarcodes // // Created by R0CKSTAR on 15/10/26. // Copyright (c) 2015 P.D.Q. All rights reserved. // import UIKit @available(macCatalyst 14.0, *) class RSCodeDataMatrixGenerator: RSAbstractCodeGenerator { }
mit
radex/swift-compiler-crashes
crashes-duplicates/17610-no-stacktrace.swift
11
270
// 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 d { enum b { func a { if true { let a { extension NSData { func b( = [ { deinit { class case ,
mit
vnu/Flickz
Flickz/MoviePosterCell.swift
1
256
// // moviePosterCell.swift // Flickz // // Created by Vinu Charanya on 2/7/16. // Copyright © 2016 vnu. All rights reserved. // import UIKit class MoviePosterCell: UICollectionViewCell { @IBOutlet weak var moviePosterImage: UIImageView! }
mit
zerovagner/iOS-Studies
RainyShinyCloudy/RainyShinyCloudy/Weather.swift
1
3031
// // Weather.swift // RainyShinyCloudy // // Created by Vagner Oliveira on 5/15/17. // Copyright © 2017 Vagner Oliveira. All rights reserved. // import Foundation import Alamofire import CoreLocation class Weather { private(set) var cityName: String! private(set) var currentWeather: String! private var currentDate: String! private(set) var currentTemperature: String! private(set) var maxTemperature: String! private(set) var minTemperature: String! static let baseUrl = "http://api.openweathermap.org/data/2.5/" static let params = [ "lat":"\(lat)", "lon":"\(lon)", "appid":"42a1771a0b787bf12e734ada0cfc80cb" ] private static var lat = 0.0 private static var lon = 0.0 static let forecastUrl = baseUrl + "forecast/daily" var date: String! { get { if currentDate == "" { let df = DateFormatter() df.dateStyle = .long df.timeStyle = .none currentDate = df.string(from: Date()) } return currentDate } } init() { cityName = "" currentWeather = "" currentDate = "" currentTemperature = "" minTemperature = "" maxTemperature = "" } init(obj: [String:Any]) { if let temp = obj["temp"] as? [String:Any] { if let min = temp["min"] as? Double { minTemperature = "\(round(10 * (min - 273))/10)º" } if let max = temp["max"] as? Double { maxTemperature = "\(round(10 * (max - 273))/10)º" } } if let weather = obj["weather"] as? [[String:Any]] { if let main = weather[0]["main"] as? String { currentWeather = main.capitalized } } if let date = obj["dt"] as? Double { let convertedDate = Date(timeIntervalSince1970: date) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.dateFormat = "EEEE" dateFormatter.timeStyle = .none let dateIndex = Calendar.current.component(.weekday, from: convertedDate) currentDate = dateFormatter.weekdaySymbols[dateIndex-1] } } func setUp (fromJSON dict: [String:Any]) { if let name = dict["name"] as? String { cityName = name.capitalized print(cityName) } if let weather = dict["weather"] as? [[String:Any]] { if let curWeather = weather[0]["main"] as? String { currentWeather = curWeather.capitalized print(currentWeather) } } if let main = dict["main"] as? [String:Any] { if let temp = main["temp"] as? Double { currentTemperature = "\(round(10 * (temp - 273))/10)º" print(currentTemperature) } } } func downloadCurrentWeatherData (completed: @escaping DownloadComplete) { let currentWeatherUrl = Weather.baseUrl + "weather" Alamofire.request(currentWeatherUrl, parameters: Weather.params).responseJSON { response in let result = response.result if let dict = result.value as? [String:Any] { self.setUp(fromJSON: dict) } completed() } } static func setCoordinates(fromLocation location: CLLocation) { lat = round(100 * location.coordinate.latitude)/100 lon = round(100 * location.coordinate.longitude)/100 print("lat: \(lat) lon: \(lon)") } }
gpl-3.0
the-grid/Palette-iOS
Palette/UIView+ColorAtPoint.swift
1
1917
//The MIT License (MIT) // //Copyright (c) 2015 Carlos Simón // //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 extension UIView{ //returns the color data of the pixel at the currently selected point func getPixelColorAtPoint(point:CGPoint)->UIColor { let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4) var colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo) CGContextTranslateCTM(context, -point.x, -point.y) layer.renderInContext(context) var color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0) pixel.dealloc(4) return color } }
mit
devpunk/velvet_room
Source/Model/Vita/MVitaConfigurationDirectory.swift
1
121
import Foundation struct MVitaConfigurationDirectory { let associationType:UInt16 let associationDescr:UInt32 }
mit
e155707/remote
AfuRo/AfuRo/Tutorial/Turorial4/FourTutorialController.swift
1
716
// // FourTutorialController.swift // AfuRo // // Created by e155707 on 2017/11/27. // Copyright © 2017年 Ryukyu. All rights reserved. // import UIKit import SceneKit class FourTutorialController: UIViewController{ override func viewDidLoad() { super.viewDidLoad() } @IBAction func pushToMain(_ sender: Any) { //self.fromFourTutorialControllerToMain() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
lfkdsk/JustUiKit
JustUiKit/layout/JustViewManager.swift
1
1389
/// MIT License /// /// Copyright (c) 2017 JustWe /// /// 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 JustViewManager { func addView(view: UIView) func updateView(view: UIView, params: LayoutParams) func removeView(view: UIView) }
mit
sxchong/TimePods
TimePods/ViewController.swift
1
2879
// // ViewController.swift // TimePods // // Created by Sean Chong on 9/8/16. // Copyright © 2016 Sean Chong. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //MARK: Properties @IBOutlet weak var tableView: UITableView! var timer = Timer() var date = NSDate() var testPod = Pod(name: "jump rope", duration: 10) let textCellIdentifier = "TimePodTableViewCell" override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.delegate = self //tableView.register(TimePodTableViewCell.self, forCellReuseIdentifier: "TimePodTableViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* Method that is called every second. This method performs the logic of deducting time from the the active TimePod and all necessary logic associated with it. */ /* @IBAction func buttonStartPressed(sender: UIButton) { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTick), userInfo: nil, repeats: true) }*/ // MARK: Protocol required methods // MARK: UITableViewSource functions func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // UITextField Delegates func textFieldDidBeginEditing(_ textField: UITextField) { print("TextField did begin editing method called") } func textFieldDidEndEditing(_ textField: UITextField) { print("TextField did end editing method called") } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { print("TextField should begin editing method called") return true; } func textFieldShouldClear(_ textField: UITextField) -> Bool { print("TextField should clear method called") return true; } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { print("TextField should snd editing method called") return true; } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print("While entering the characters this method gets called") return true; } func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("TextField should return method called") return true; } }
gpl-3.0
gbarcena/ImageCaptureSession
ImageCaptureSession/ImageViewController.swift
1
521
// // ImageViewController.swift // ImageCaptureSession // // Created by Gustavo Barcena on 5/27/15. // Copyright (c) 2015 Gustavo Barcena. All rights reserved. // import UIKit class ImageViewController: UIViewController { @IBOutlet weak var imageView : UIImageView! var image : UIImage? override func viewDidLoad() { super.viewDidLoad() imageView.image = image } @IBAction func dismissViewPressed() { self.dismiss(animated: true, completion: nil) } }
mit
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/utils/Reflection/Construct.swift
3
2605
/// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T { if Metadata(type: T.self)?.kind == .struct { return try constructValueType(constructor) } else { throw ReflectionError.notStruct(type: T.self) } } /// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct(_ type: Any.Type, constructor: (Property.Description) throws -> Any) throws -> Any { return try extensions(of: type).construct(constructor: constructor) } private func constructValueType<T>(_ constructor: (Property.Description) throws -> Any) throws -> T { guard Metadata(type: T.self)?.kind == .struct else { throw ReflectionError.notStruct(type: T.self) } let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) defer { pointer.deallocate(capacity: 1) } var values: [Any] = [] try constructType(storage: UnsafeMutableRawPointer(pointer), values: &values, properties: properties(T.self), constructor: constructor) return pointer.move() } private func constructType(storage: UnsafeMutableRawPointer, values: inout [Any], properties: [Property.Description], constructor: (Property.Description) throws -> Any) throws { var errors = [Error]() for property in properties { do { let value = try constructor(property) values.append(value) try property.write(value, to: storage) } catch { errors.append(error) } } if errors.count > 0 { throw ConstructionErrors(errors: errors) } } /// Create a struct from a dictionary. public func construct<T>(_ type: T.Type = T.self, dictionary: [String: Any]) throws -> T { return try construct(constructor: constructorForDictionary(dictionary)) } /// Create a struct from a dictionary. public func construct(_ type: Any.Type, dictionary: [String: Any]) throws -> Any { return try extensions(of: type).construct(dictionary: dictionary) } private func constructorForDictionary(_ dictionary: [String: Any]) -> (Property.Description) throws -> Any { return { property in if let value = dictionary[property.key] { return value } else if let expressibleByNilLiteral = property.type as? ExpressibleByNilLiteral.Type { return expressibleByNilLiteral.init(nilLiteral: ()) } else { throw ReflectionError.requiredValueMissing(key: property.key) } } }
mit
NijiDigital/NetworkStack
Example/MoyaComparison/MoyaComparison/Utils/MCLogger.swift
1
1064
// // Copyright 2017 niji // // 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 SwiftyBeaver struct MCLogger { static func setup() { let console = ConsoleDestination() console.format = "$D[HH:mm:ss]$d $L - $N.$F:$l > $M" console.levelString.verbose = "📔 -- VERBOSE" console.levelString.debug = "📗 -- DEBUG" console.levelString.info = "📘 -- INFO" console.levelString.warning = "📙 -- WARNING" console.levelString.error = "📕 -- ERROR" SwiftyBeaver.addDestination(console) } }
apache-2.0
modocache/Gift
Gift/Signature/Signature.swift
1
1040
import Foundation /** A signature represents information about the creator of an object. For example, tags and commits have signatures that contain information about who created the tag or commit, and when they did so. */ public struct Signature { /** The name of the person associated with this signature. */ public let name: String /** The email of the person associated with this signature. */ public let email: String /** The date this signature was made. */ public let date: NSDate /** The time zone in which this signature was made. */ public let timeZone: NSTimeZone public init(name: String, email: String, date: NSDate = NSDate(timeIntervalSinceNow: 0), timeZone: NSTimeZone = NSTimeZone.defaultTimeZone()) { self.name = name self.email = email self.date = date self.timeZone = timeZone } } /** A signature used by Gift when updating the reflog and the user has not provided a signature of their own. */ internal let giftSignature = Signature(name: "com.libgit2.Gift", email: "")
mit
pisarm/Gojira
Carthage/Checkouts/Bond/BondTests/UISegmentedControlTests.swift
13
1025
// // UISegmentedControlTests.swift // Bond // // Created by Srđan Rašić on 08/09/15. // Copyright © 2015 Bond. All rights reserved. // import UIKit import XCTest import Bond class UISegmentedControlTests: XCTestCase { func testSegmentedControlObservable() { let observable = Observable<Int>(0) let segmentedControl = UISegmentedControl(items: ["A", "B", "C"]) XCTAssert(segmentedControl.selectedSegmentIndex == UISegmentedControlNoSegment, "Initial value") observable.bidirectionalBindTo(segmentedControl.bnd_selectedSegmentIndex) XCTAssert(segmentedControl.selectedSegmentIndex == 0, "Value after binding") observable.value = 1 XCTAssert(segmentedControl.selectedSegmentIndex == 1, "Index reflects observable value change") segmentedControl.selectedSegmentIndex = 2 segmentedControl.sendActionsForControlEvents(.ValueChanged) // simulate user input XCTAssert(observable.value == 2, "Observable value reflects segmented control value change") } }
mit
stephentyrone/swift
stdlib/public/core/StringInterpolation.swift
1
10047
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // 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 // //===----------------------------------------------------------------------===// /// Represents a string literal with interpolations while it is being built up. /// /// Do not create an instance of this type directly. It is used by the compiler /// when you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." /// /// When implementing an `ExpressibleByStringInterpolation` conformance, /// set the `StringInterpolation` associated type to /// `DefaultStringInterpolation` to get the same interpolation behavior as /// Swift's built-in `String` type and construct a `String` with the results. /// If you don't want the default behavior or don't want to construct a /// `String`, use a custom type conforming to `StringInterpolationProtocol` /// instead. /// /// Extending default string interpolation behavior /// =============================================== /// /// Code outside the standard library can extend string interpolation on /// `String` and many other common types by extending /// `DefaultStringInterpolation` and adding an `appendInterpolation(...)` /// method. For example: /// /// extension DefaultStringInterpolation { /// fileprivate mutating func appendInterpolation( /// escaped value: String, asASCII forceASCII: Bool = false) { /// for char in value.unicodeScalars { /// appendInterpolation(char.escaped(asASCII: forceASCII)) /// } /// } /// } /// /// print("Escaped string: \(escaped: string)") /// /// See `StringInterpolationProtocol` for details on `appendInterpolation` /// methods. /// /// `DefaultStringInterpolation` extensions should add only `mutating` members /// and should not copy `self` or capture it in an escaping closure. @frozen public struct DefaultStringInterpolation: StringInterpolationProtocol { /// The string contents accumulated by this instance. @usableFromInline internal var _storage: String /// Creates a string interpolation with storage pre-sized for a literal /// with the indicated attributes. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public init(literalCapacity: Int, interpolationCount: Int) { let capacityPerInterpolation = 2 let initialCapacity = literalCapacity + interpolationCount * capacityPerInterpolation _storage = String(_StringGuts(_initialCapacity: initialCapacity)) } /// Appends a literal segment of a string interpolation. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public mutating func appendLiteral(_ literal: String) { literal.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable, T: CustomStringConvertible { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: CustomStringConvertible { value.description.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) { _print_unlocked(value, &self) } @_alwaysEmitIntoClient public mutating func appendInterpolation(_ value: Any.Type) { _typeName(value, qualified: false).write(to: &self) } /// Creates a string from this instance, consuming the instance in the /// process. @inlinable internal __consuming func make() -> String { return _storage } } extension DefaultStringInterpolation: CustomStringConvertible { @inlinable public var description: String { return _storage } } extension DefaultStringInterpolation: TextOutputStream { @inlinable public mutating func write(_ string: String) { _storage.append(string) } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { _storage._guts.append(_StringGuts(buffer, isASCII: true)) } } // While not strictly necessary, declaring these is faster than using the // default implementation. extension String { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self = stringInterpolation.make() } } extension Substring { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self.init(stringInterpolation.make()) } }
apache-2.0
bmichotte/HSTracker
HSTracker/Logging/CardIds/DreamCards.swift
1
1585
/* This file is generated by https://github.com/HearthSim/HearthDb The MIT License (MIT) Copyright (c) 2016 HearthSim 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. Source: https://github.com/HearthSim/HearthDb */ import Foundation extension CardIds.NonCollectible { struct DreamCards { static let LaughingSister = "DREAM_01" static let YseraAwakens = "DREAM_02" static let EmeraldDrake = "DREAM_03" static let Dream = "DREAM_04" static let Nightmare = "DREAM_05" static let RepurposedEnchantmentTavernBrawl = "TB_MP_02e" } }
mit
conferencesapp/rubyconferences-ios
Reachability.swift
1
942
// // Reachability.swift // // // Created by Rashmi Yadav on 5/16/15. // // import Foundation import SystemConfiguration public class Reachability { public func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.ConnectionRequired) return (isReachable && !needsConnection) } }
mit
itaen/30DaysSwift
SwiftDemo/SwiftDemo/AppDelegate.swift
1
2167
// // AppDelegate.swift // SwiftDemo // // Created by itaen on 2017/11/17. // Copyright © 2017年 itaen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mrudulp/iOSSrc
autotest/appiumTest/sampleApps/UICatalogObj_Swift/Swift/UICatalog/StepperViewController.swift
3
3528
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to use UIStepper. */ import UIKit class StepperViewController: UITableViewController { // MARK: Properties @IBOutlet weak var defaultStepper: UIStepper! @IBOutlet weak var tintedStepper: UIStepper! @IBOutlet weak var customStepper: UIStepper! @IBOutlet weak var defaultStepperLabel: UILabel! @IBOutlet weak var tintedStepperLabel: UILabel! @IBOutlet weak var customStepperLabel: UILabel! // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureDefaultStepper() configureTintedStepper() configureCustomStepper() } // MARK: Configuration func configureDefaultStepper() { defaultStepper.value = 0 defaultStepper.minimumValue = 0 defaultStepper.maximumValue = 10 defaultStepper.stepValue = 1 defaultStepperLabel.text = "\(Int(defaultStepper.value))" defaultStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged) } func configureTintedStepper() { tintedStepper.tintColor = UIColor.applicationBlueColor() tintedStepperLabel.text = "\(Int(tintedStepper.value))" tintedStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged) } func configureCustomStepper() { // Set the background image. let stepperBackgroundImage = UIImage(named: "stepper_and_segment_background") customStepper.setBackgroundImage(stepperBackgroundImage, forState: .Normal) let stepperHighlightedBackgroundImage = UIImage(named: "stepper_and_segment_background_highlighted") customStepper.setBackgroundImage(stepperHighlightedBackgroundImage, forState: .Highlighted) let stepperDisabledBackgroundImage = UIImage(named: "stepper_and_segment_background_disabled") customStepper.setBackgroundImage(stepperDisabledBackgroundImage, forState: .Disabled) // Set the image which will be painted in between the two stepper segments (depends on the states of both segments). let stepperSegmentDividerImage = UIImage(named: "stepper_and_segment_divider") customStepper.setDividerImage(stepperSegmentDividerImage, forLeftSegmentState: .Normal, rightSegmentState: .Normal) // Set the image for the + button. let stepperIncrementImage = UIImage(named: "stepper_increment") customStepper.setIncrementImage(stepperIncrementImage, forState: .Normal) // Set the image for the - button. let stepperDecrementImage = UIImage(named: "stepper_decrement") customStepper.setDecrementImage(stepperDecrementImage, forState: .Normal) customStepperLabel.text = "\(Int(customStepper.value))" customStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged) } // MARK: Actions func stepperValueDidChange(stepper: UIStepper) { NSLog("A stepper changed its value: \(stepper).") // A mapping from a stepper to its associated label. let stepperMapping: [UIStepper: UILabel] = [ defaultStepper: defaultStepperLabel, tintedStepper: tintedStepperLabel, customStepper: customStepperLabel ] stepperMapping[stepper]!.text = "\(Int(stepper.value))" } }
mit
1000copy/fin
View/LogoutTableViewCell.swift
2
1154
// // LogoutTableViewCell.swift // V2ex-Swift // // Created by huangfeng on 2/12/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class LogoutTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup()->Void{ self.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor self.textLabel!.text = NSLocalizedString("logOut") self.textLabel!.textAlignment = .center self.textLabel!.textColor = V2EXColor.colors.v2_NoticePointColor let separator = UIImageView(image: createImageWithColor(V2EXColor.colors.v2_SeparatorColor)) self.contentView.addSubview(separator) separator.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.contentView) make.right.bottom.equalTo(self.contentView) make.height.equalTo(SEPARATOR_HEIGHT) } } }
mit
alreadyRight/Swift-algorithm
私人通讯录/私人通讯录/DetailViewController.swift
1
3898
// // DetailViewController.swift // 私人通讯录 // // Created by 周冰烽 on 2017/12/9. // Copyright © 2017年 周冰烽. All rights reserved. // import UIKit class DetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var status: Int = 0 private let detailCellID = "detailCellID" var name: String? var phone: String? var address: String? override func viewDidLoad() { super.viewDidLoad() if status == 0 { title = "添加联系人" }else{ title = "编辑联系人" } view.backgroundColor = UIColor.white navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(clickFinish)) setupTableView() } func setupTableView() -> Void { let tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.height - 64), style: .plain) tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 0 tableView.estimatedSectionHeaderHeight = 0 tableView.estimatedSectionFooterHeight = 0 tableView.register(DetailTableViewCell.classForCoder(), forCellReuseIdentifier: detailCellID) view.addSubview(tableView) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: DetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: detailCellID, for: indexPath) as! DetailTableViewCell switch indexPath.row { case 0: // cell.setNormalValue(titleText: "姓名", placeholder: "请填写姓名", dataText: name ?? "") cell.title = "姓名" cell.placeholder = "请填写姓名" cell.dataText = name ?? "" cell.changeText { [weak self](text) in self?.name = text } case 1: cell.title = "电话号码" cell.placeholder = "请填写电话号码" cell.dataText = phone ?? "" cell.changeText { [weak self](text) in self?.phone = text } default: cell.title = "地址" cell.placeholder = "请填写地址" cell.dataText = address ?? "" cell.changeText { [weak self](text) in self?.address = text } } return cell } @objc func clickFinish() -> Void { guard let name = name, let phone = phone, let address = address else { return } let dict = ["name":name,"phone":phone,"address":address] let ud = UserDefaults.standard var arr: Array<[String : String]> = ud.object(forKey: "addressBook") as? Array<[String:String]> ?? [] if arr.count == 0 { arr = Array<[String:String]>() } for i in 0 ..< arr.count { if dict["name"] == arr[i]["name"] { arr.remove(at: i) break }else if dict["phone"] == arr[i]["phone"]{ arr.remove(at: i) break }else if dict["address"] == arr[i]["address"]{ arr.remove(at: i) break } } arr.append(dict) ud.set(arr, forKey: "addressBook") navigationController?.popViewController(animated: true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.becomeFirstResponder() } }
mit
xremix/SwiftGS1Barcode
SwiftGS1BarcodeTests/StringTests.swift
1
2635
// // StringTests.swift // SwiftGS1Barcode // // Created by Toni Hoffmann on 26.06.17. // Copyright © 2017 Toni Hoffmann. All rights reserved. // import XCTest @testable import SwiftGS1Barcode class StringTests: XCTestCase { var testString: String = "" override func setUp() { super.setUp() testString = "Hello World" } override func tearDown() { super.tearDown() } func testLength(){ XCTAssertEqual(testString.count, 11) } func testSubstringFromLength() { XCTAssertEqual(testString.substring(0, length: 5), "Hello") XCTAssertEqual(testString.substring(1, length: 5), "ello ") XCTAssertEqual(testString, "Hello World") // Test Integration } func testSubstringFromTo() { XCTAssertEqual(testString.substring(0, to: 5), "Hello") XCTAssertEqual(testString.substring(1, to: 5), "ello") XCTAssertEqual(testString, "Hello World") // Test Integration } func testSubstringFrom() { XCTAssertEqual(testString.substring(from: 0), "Hello World") XCTAssertEqual(testString.substring(from: 1), "ello World") XCTAssertEqual(testString, "Hello World") // Test Integration } func testSubstringTo() { XCTAssertEqual(testString.substring(from: 0), testString) XCTAssertEqual(testString.substring(from: 6), "World") XCTAssertEqual(testString.substring(from: testString.count), "") XCTAssertEqual(testString, "Hello World") // Test Integration } func testStartsWith(){ XCTAssert(testString.startsWith("Hello")) XCTAssert(!testString.startsWith("World")) XCTAssertEqual(testString, "Hello World") // Test Integration } // Tests for Index Of func testIndexOf(){ XCTAssertEqual(testString.index(of: "H"), testString.startIndex) } func testIndexOfLongString(){ XCTAssertEqual(testString.index(of: "Hello"), testString.startIndex) } func testIndexOfWrongString(){ XCTAssertEqual(testString.index(of: "x"), nil) } func testIndexOfEndString(){ XCTAssertEqual(testString.index(of: "World"), testString.index(testString.startIndex, offsetBy: 6)) } func testIndexOfLowerCaseChar(){ XCTAssertEqual(testString.index(of: "h"), nil) } func testIndexOfLowerCaseString(){ XCTAssertEqual(testString.index(of: "hello"), nil) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { _ = self.testString.substring(0, to: 5) } } }
mit
larryhou/swift
CrashReport/CrashReport/ViewController.swift
1
2538
// // ViewController.swift // CrashReport // // Created by larryhou on 8/4/16. // Copyright © 2016 larryhou. All rights reserved. // import Foundation import UIKit import GameplayKit class ViewController: UIViewController { var method: TestMethod = .none var bartitle: String = "" override func viewDidLoad() { navigationItem.title = bartitle switch method { case .null: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in let rect: CGRect? = nil print(rect!.width) } break case .memory: var list: [[UInt8]] = [] Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) {_ in let bytes = [UInt8](repeating: 10, count: 1024*1024) list.append(bytes) } break case .cpu: Timer.scheduledTimer(withTimeInterval: 0.0, repeats: false) {_ in self.ruineCPU() } break case .abort: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in abort() } break case .none: break } } func ruineCPU() { let width: Int32 = 110, height: Int32 = 110 let graph = GKGridGraph(fromGridStartingAt: int2(0, 0), width: width, height: height, diagonalsAllowed: false) var obstacles: [GKGridGraphNode] = [] let random = GKRandomSource.sharedRandom() for x in 0..<width { for y in 0..<height { let densitiy = 5 if random.nextInt(upperBound: densitiy) % densitiy == 1 { let node = graph.node(atGridPosition: int2(x, y)) obstacles.append(node!) } } } graph.remove(obstacles) func get_random_node() -> GKGraphNode { let nodes = graph.nodes! return nodes[random.nextInt(upperBound: nodes.count)] } while true { let queue = DispatchQueue(label: Date().description, qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.never, target: nil) queue.async { graph.findPath(from: get_random_node(), to: get_random_node()) } } } }
mit
davidchiles/OSMKit-Swift
Source/Utilities/Error.swift
1
202
// // Error.swift // Pods // // Created by David Chiles on 2/8/16. // // import Foundation enum JSONParsingError : ErrorType { case InvalidJSONStructure case CannotDecodeKey(key:JSONKeys) }
mit
skedgo/tripkit-ios
Sources/TripKit/vendor/BetterCodable/DefaultEmptyArray.swift
1
454
public struct DefaultEmptyArrayStrategy<T: Decodable>: DefaultCodableStrategy { public static var defaultValue: [T] { return [] } } /// Decodes Arrays returning an empty array instead of nil if applicable /// /// `@DefaultEmptyArray` decodes Arrays and returns an empty array instead of nil if the Decoder is unable to decode the /// container. public typealias DefaultEmptyArray<T> = DefaultCodable<DefaultEmptyArrayStrategy<T>> where T: Decodable
apache-2.0
rodrigobell/twitter-clone
twitter-clone/AppDelegate.swift
1
3367
// // AppDelegate.swift // twitter-clone // // Created by Rodrigo Bell on 2/17/17. // Copyright © 2017 Rodrigo Bell. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let storyboard = UIStoryboard(name: "Main", bundle: nil) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if User.currentUser != nil { // Go to the logged in screen print("Current user exists: \((User.currentUser?.name)!)") let tweetsVC = storyboard.instantiateViewController(withIdentifier: "MainNavController") window?.rootViewController = tweetsVC } else { print("No current user") } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil, queue: OperationQueue.main, using: { (NSNotification) -> Void in let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateInitialViewController() self.window?.rootViewController = vc }) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { // Called when twitter-clone switches from Safari back to twitter-clone. TwitterClient.sharedInstance.handleOpenUrl(url: url) return true } }
mit
deege/deegeu-swift-share-extensions
deegeu-swift-share-extensions/AppDelegate.swift
1
2196
// // AppDelegate.swift // deegeu-swift-share-extensions // // Created by Daniel Spiess on 10/23/15. // Copyright © 2015 Daniel Spiess. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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
SHSRobotics/Estimote
Examples/nearables/TemperatureExample-Swift/TemperatureExample-Swift/MasterViewController.swift
1
2049
// // MasterViewController.swift // TemperatureExample-Swift // // Created by Grzegorz Krukiewicz-Gacek on 24.12.2014. // Copyright (c) 2014 Estimote Inc. All rights reserved. // import UIKit class MasterViewController: UITableViewController, ESTNearableManagerDelegate { var nearables:Array<ESTNearable>! var nearableManager:ESTNearableManager! override func viewDidLoad() { super.viewDidLoad() nearables = [] nearableManager = ESTNearableManager() nearableManager.delegate = self nearableManager .startRangingForType(ESTNearableType.All) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let selectedNearable = nearables[indexPath.row] as ESTNearable (segue.destinationViewController as DetailViewController).nearable = selectedNearable } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nearables.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let nearable = nearables[indexPath.row] as ESTNearable cell.textLabel!.text = nearable.nameForType(nearable.type) cell.detailTextLabel!.text = nearable.identifier return cell } // MARK: - ESTNearableManager delegate func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType) { self.nearables = nearables as Array<ESTNearable> tableView.reloadData() } }
mit
RamonGilabert/RamonGilabert
RamonGilabert/RamonGilabert/RGWebViewController.swift
1
2119
import UIKit class RGWebViewController: UIViewController, UIWebViewDelegate { let viewModel = ViewModel() let transitionManager = CustomVideoTransition() var webView = UIWebView() var loadURL = ContactWebs.Website! var backButton = UIButton() var forwardButton = UIButton() // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() self.transitioningDelegate = self.transitionManager let headerView = UIView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight/9)) headerView.backgroundColor = UIColor_WWDC.almostBlackColor() self.viewModel.setCrossButtonWebView(headerView, viewController: self) self.backButton = self.viewModel.setBackButton(headerView, viewController: self) self.forwardButton = self.viewModel.setForwardButton(headerView, viewController: self) self.webView = self.viewModel.setWebView(self.view, webViewDelegate: self) self.view.addSubview(headerView) let requestURL = NSURLRequest(URL: self.loadURL) self.webView.loadRequest(requestURL) } // MARK: WebView delegate methods func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { self.backButton.enabled = self.webView.canGoBack ? true : false self.forwardButton.enabled = self.webView.canGoForward ? true : false return true } func webViewDidFinishLoad(webView: UIWebView) { self.backButton.enabled = self.webView.canGoBack ? true : false self.forwardButton.enabled = self.webView.canGoForward ? true : false } // MARK: Button handlers func onCloseButtonPressed() { self.dismissViewControllerAnimated(true, completion: nil) } func onBackButtonPressed(sender: UIButton) { if self.webView.canGoBack { self.webView.goBack() } } func onForwardButtonPressed(sender: UIButton) { if self.webView.canGoForward { self.webView.goForward() } } }
mit
steve-holmes/music-app-2
MusicApp/Modules/Playlist/PlaylistDetailViewController.swift
1
9821
// // PlaylistDetailViewController.swift // MusicApp // // Created by Hưng Đỗ on 6/18/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources import Action import NSObject_Rx class PlaylistDetailViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var headerView: PlaylistDetailHeaderView! @IBOutlet weak var playButton: UIButton! fileprivate let headerCell = UITableViewCell(style: .default, reuseIdentifier: "HeaderCell") fileprivate var initialIndicatorView = DetailInitialActivityIndicatorView() fileprivate var loadingIndicatorView = LoadingActivityIndicatorView() var store: PlaylistDetailStore! var action: PlaylistDetailAction! // MARK: Properties var playlist: Playlist { get { return store.info.value } set { store.info.value = newValue } } var playlistDetailInfoInput: PlaylistDetailInfo? // MARK: Output Properties lazy var playlistDetailInfoOutput: Observable<PlaylistDetailInfo> = { return self.playlistDetailInfoSubject.asObservable() }() fileprivate var playlistDetailInfoSubject = PublishSubject<PlaylistDetailInfo>() // MARK: Target Actions @IBAction func backButonTapped(_ backButton: UIButton) { navigationController?.popViewController(animated: true) } // MARK: Life Cycles override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = [] tableView.delegate = self headerView.configureAnimation(with: tableView) bindStore() bindAction() } private var headerViewNeedsToUpdate = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() if headerViewNeedsToUpdate { headerView.frame.size.height = tableView.bounds.size.height / 3 headerViewNeedsToUpdate = false } } // MARK: Data Source fileprivate let HeaderRow = 0 fileprivate let MenuRow = 1 fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<PlaylistDetailItemSection> = { let dataSource = RxTableViewSectionedReloadDataSource<PlaylistDetailItemSection>() dataSource.configureCell = { dataSource, tableView, indexPath, detailItem in if indexPath.row == self.HeaderRow { return self.headerCell } if indexPath.row == self.MenuRow { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistMenuCell.self), for: indexPath) if let cell = cell as? PlaylistMenuCell { cell.state = self.store.state.value cell.action = self.action.onPlaylistDetailStateChange() } return cell } switch detailItem { case let .song(song): let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SongCell.self), for: indexPath) if let songCell = cell as? SongCell { let contextAction = CocoaAction { [weak self] _ in guard let this = self else { return .empty() } return this.action.onContextMenuOpen.execute((song, this)).map { _ in } } songCell.configure(name: song.name, singer: song.singer, contextAction: contextAction) } return cell case let .playlist(playlist): let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistDetailCell.self), for: indexPath) if let playlistCell = cell as? PlaylistDetailCell { playlistCell.configure(name: playlist.name, singer: playlist.singer, image: playlist.avatar) } return cell } } return dataSource }() } // MARK: UITableViewDelegate extension PlaylistDetailViewController: UITableViewDelegate { private var headerHeight: CGFloat { return tableView.bounds.height / 3 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == self.HeaderRow { return headerHeight } if indexPath.row == self.MenuRow { return 44 } if self.store.state.value == .song { return 44 } else { return 60 } } } // MARK: Activity Indicator extension PlaylistDetailViewController { func beginInitialLoading() { initialIndicatorView.startAnimating(in: self.view) } func endInitialLoading() { initialIndicatorView.stopAnimating() } func beginLoading() { loadingIndicatorView.startAnimation(in: self.view) } func endLoading() { loadingIndicatorView.stopAnimation() } } // MARK: Store extension PlaylistDetailViewController { func bindStore() { store.info.asObservable() .subscribe(onNext: { [weak self] playlist in self?.headerView.setImage(playlist.avatar) self?.headerView.setPlaylist(playlist.name) self?.headerView.setSinger(playlist.singer) }) .addDisposableTo(rx_disposeBag) let state = store.state.asObservable() .filter { [weak self] _ in self != nil } .shareReplay(1) state .subscribe(onNext: { [weak self] state in let indexPath = IndexPath(row: 1, section: 0) let cell = self?.tableView.cellForRow(at: indexPath) as? PlaylistMenuCell cell?.state = state }) .addDisposableTo(rx_disposeBag) bindDataSource(state: state) store.loading.asObservable() .skip(1) .subscribe(onNext: { [weak self] loading in if loading { self?.beginLoading() } else { self?.endLoading() } }) .addDisposableTo(rx_disposeBag) } private func bindDataSource(state: Observable<PlaylistDetailState>) { let fakeSong = Song(id: "", name: "", singer: "") let fakeSongs = [fakeSong, fakeSong] let song = state .filter { $0 == .song } .map { [weak self] _ in fakeSongs + self!.store.songs.value } .shareReplay(1) let fakePlaylist = Playlist(id: "", name: "'", singer: "", avatar: "") let fakePlaylists = [fakePlaylist, fakePlaylist] let playlist = state .filter { $0 == .playlist } .map { [weak self] _ in fakePlaylists + self!.store.playlists.value } .shareReplay(1) let songDataSource = song .map { songs in songs.map { PlaylistDetailItem.song($0) } } .map { [SectionModel(model: "Song", items: $0)] } let playlistDataSource = playlist .map { playlists in playlists.map { PlaylistDetailItem.playlist($0) } } .map { [SectionModel(model: "Playlist", items: $0)] } Observable.from([songDataSource, playlistDataSource]) .merge() .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(rx_disposeBag) song .map { song in song.count } .filter { count in count == 2 } .take(1) .subscribe(onNext: { [weak self] _ in self?.beginInitialLoading() }) .addDisposableTo(rx_disposeBag) song .map { song in song.count } .filter { count in count > 2 } .take(1) .subscribe(onNext: { [weak self] _ in self?.endInitialLoading() }) .addDisposableTo(rx_disposeBag) } } // MARK: Action extension PlaylistDetailViewController { func bindAction() { if let detailInfo = playlistDetailInfoInput { store.tracks.value = detailInfo.tracks store.songs.value = detailInfo.songs store.playlists.value = detailInfo.playlists store.state.value = .song } else { action.onLoad.execute(()) .subscribe(playlistDetailInfoSubject) .addDisposableTo(rx_disposeBag) } let detailItem = tableView.rx.modelSelected(PlaylistDetailItem.self) .shareReplay(1) detailItem .map { item -> Playlist? in switch item { case .song(_): return nil case let .playlist(playlist): return playlist } } .filter { $0 != nil } .map { $0! } .filter { playlist in !playlist.id.isEmpty } .subscribe(action.onPlaylistDidSelect.inputs) .addDisposableTo(rx_disposeBag) detailItem .map { item -> Song? in switch item { case let .song(song): return song case .playlist(_): return nil } } .filter { $0 != nil } .map { $0! } .filter { song in !song.id.isEmpty } .subscribe(action.onSongDidSelect.inputs) .addDisposableTo(rx_disposeBag) playButton.rx.action = action.onPlayButtonPress() } }
mit
Zewo/HTTPFile
Sources/HTTPFile/HTTPFile.swift
4
46
@_exported import HTTP @_exported import File
mit
codergaolf/DouYuTV
DouYuTV/DouYuTV/Classes/Main/View/PageTitleView.swift
1
6482
// // PageTitleView.swift // DouYuTV // // Created by 高立发 on 2016/11/12. // Copyright © 2016年 GG. All rights reserved. // import UIKit // MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selected index : Int) } // MARK:- 定义常量 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255, 128, 0) // MARK:- 定义PageTitleView类 class PageTitleView: UIView { // MARK:- 定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles : [String] weak var delegate : PageTitleViewDelegate? // MARK:- 懒加载属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() // MARK:- 自定义构造函数 init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI extension PageTitleView { fileprivate func setupUI() { //1,添加UIScrollView addSubview(scrollView) scrollView.frame = bounds //2,添加Title对应的label setTitleLabels() //3,设置底线和滚动的滑块 setupBottomMenuAndScrollLine() } fileprivate func setTitleLabels() { for (index, title) in titles.enumerated() { //0,确定label的一些frame值 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0 //1,创建UILabel let label = UILabel() //2,设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center //3,设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4,将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) //5,给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomMenuAndScrollLine() { //1,添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) //2,添加scrollLine //2.1获取第一个label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //2.2设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK:- 监听label的点击 extension PageTitleView { @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer) { //0,获取当前label guard let currentLabel = tapGes.view as? UILabel else { return } //1,如果是重复点击同一个title,直接返回 if currentLabel.tag == currentIndex { return } //2,获取之前的label let oldLabel = titleLabels[currentIndex] //3,切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) //4,保存最新label的下标值 currentIndex = currentLabel.tag //5,滚动条位置发生该表 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15, animations: { self.scrollLine.frame.origin.x = scrollLineX }) //6,通知代理 delegate?.pageTitleView(titleView: self, selected: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { //1,取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2,处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //3,处理颜色的渐变 //3.1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) //3.2变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) //3.2变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4,记录最新的index currentIndex = targetIndex } }
mit
Tinkertanker/intro-coding-swift
2-4 While loops.playground/Contents.swift
1
1342
/*: # Intro to Programming in Swift Worksheet 2 In this set of exercises, you'll use Swift to make functions that do basic operations using loops. Remember to turn on the *Assistant Editor* before you start. */ func printHeader(title: String){ println("") println(title); println("------------") println("") } /*: ## Exercise 4A: Fibonacci sequence The fibonacci sequence is defined as a sequence of numbers where every number, from the third number onwards, is the sum of the previous two numbers: 0 1 1 2 3 5 8 13... Write a function, genFibonacci, that generates the first n fibonacci numbers Hint: You need to store additional values in variables outside of the loop */ printHeader("Exercise 4A") func genFibonacci(n: Int){ } genFibonacci(200); /*: ## Demo 1: While loops While loops run until its condition evaluates to false. */ var i=0 while(i<20){ print("\(i) "); i++ } /*: ## Exercise 4B: Wow Squares Using a while loop, write a function smallestSquare() that gets the smallest square number larger than a given x */ func smallestSquare(x: Int){ } smallestSquare(1000); /*: ## Exercise 4C: While-y Fibonacci Using a while loop, write a function that gets the first fibonacci number larger than x. */ printHeader("Exercise 4B") func getFirstFibonacci(x: Int){ } getFirstFibonacci(10000);
mit
domenicosolazzo/practice-swift
BackgroundProcessing/SlowWorker/SlowWorker/ViewController.swift
1
2847
// // ViewController.swift // SlowWorker // // Created by Domenico on 29/04/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var startButton: UIButton! @IBOutlet weak var resultsTextView: UITextView! @IBOutlet weak var spinner: UIActivityIndicatorView! 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. } func fetchSomethingFromServer() -> String { NSThread.sleepForTimeInterval(1) return "Hi there" } func processData(data: String) -> String { NSThread.sleepForTimeInterval(2) return data.uppercaseString } func calculateFirstResult(data: String) -> String { NSThread.sleepForTimeInterval(3) return "Number of chars: \(data.characters.count)" } func calculateSecondResult(data: String) -> String { NSThread.sleepForTimeInterval(4) return data.stringByReplacingOccurrencesOfString("E", withString: "e") } @IBAction func doWork(sender: AnyObject) { let startTime = NSDate() self.resultsTextView.text = "" startButton.enabled = false spinner.startAnimating() let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue){ let fetchedData = self.fetchSomethingFromServer() let processedData = self.processData(fetchedData) var firstResult: String! var secondResult: String! let group = dispatch_group_create() dispatch_group_async(group, queue) { firstResult = self.calculateFirstResult(processedData) } dispatch_group_async(group, queue) { secondResult = self.calculateSecondResult(processedData) } dispatch_group_notify(group, queue){ let resultsSummary = "First: [\(firstResult)]\nSecond: [\(secondResult)]" dispatch_async(dispatch_get_main_queue()){ // Dispatch the result to the main queue self.resultsTextView.text = resultsSummary self.spinner.stopAnimating() self.startButton.enabled = false } let endTime = NSDate() print( "Completed in \(endTime.timeIntervalSinceDate(startTime)) seconds") } } } }
mit
vincentherrmann/multilinear-math
Sources/WaveletPlots.swift
1
3943
// // WaveletPlots.swift // MultilinearMath // // Created by Vincent Herrmann on 07.11.16. // Copyright © 2016 Vincent Herrmann. All rights reserved. // import Cocoa public struct FastWaveletPlot: CustomPlaygroundQuickLookable { public var waveletView: WaveletView public var customPlaygroundQuickLook: PlaygroundQuickLook { get { return PlaygroundQuickLook.view(waveletView) } } public init(packets: [WaveletPacket]) { waveletView = WaveletView(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) var bounds: CGRect? = nil for i in 0..<packets.count { let thisPacket = packets[i] let plot = WaveletPacketPlot(packet: thisPacket) waveletView.addPlottable(plot) if bounds == nil { bounds = plot.plotBounds } else { bounds = bounds!.join(with: plot.plotBounds) } } waveletView.setPlottingBounds(bounds!) waveletView.updatePlotting() } } public class WaveletView: PlotView2D { override public var screenBounds: CGRect { get { return CGRect(origin: CGPoint(x: 0, y: 0), size: frame.size) } } var maxValue: CGFloat = CGFloat.leastNormalMagnitude public override init(frame frameRect: NSRect) { super.init(frame: frameRect) plottingBounds = NSRect(x: 0, y: 0, width: 32, height: 1) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) for thisPlot in plots { thisPlot.draw() } } public func updatePlotting() { maxValue = CGFloat.leastNormalMagnitude for thisPlot in plots { if let w = thisPlot as? WaveletPacketPlot { if let m = w.packet.values.max() { if CGFloat(m) > maxValue {maxValue = CGFloat(m)} } } } super.updatePlotting() } } public class WaveletPacketPlot: PlottableIn2D { public var packet: WaveletPacket var tiles: [CGRect] = [] var maxValue: CGFloat = 1 public var plotBounds: CGRect { get { let yMinP = CGFloat(packet.position) / CGFloat(packet.length) let height = 1 / CGFloat(packet.length) let width = CGFloat(packet.length * packet.values.count) let bounds = CGRect(x: 0, y: yMinP, width: width, height: height) return bounds } } public init(packet: WaveletPacket) { self.packet = packet } public func draw() { for i in 0..<packet.values.count { if let color = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).blended(withFraction: CGFloat(packet.values[i]) / maxValue, of: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)) { color.setFill() } else { #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).setFill() } let path = NSBezierPath(rect: tiles[i]) path.fill() } } public func fitTo(_ plotting: Plotting2D) { let t = plotting.transformFromPlotToScreen let yMin = (plotBounds.minY + t.translateY) * t.scaleY let height = plotBounds.height * t.scaleY let xStart = t.translateX * t.scaleX let width = CGFloat(packet.length) * t.scaleX var p = xStart tiles = [] for _ in 0..<packet.values.count { tiles.append(CGRect(x: p, y: yMin, width: width, height: height)) p += width } if let view = plotting as? WaveletView { maxValue = view.maxValue } else { maxValue = 1 } } }
apache-2.0
eladb/nodeswift
nodeswift-sample/events.swift
1
3240
// // events.swift // nodeswift-sample // // Created by Elad Ben-Israel on 7/28/15. // Copyright © 2015 Citylifeapps Inc. All rights reserved. // import Foundation class EventHandler: Hashable, Equatable { // allocate 1-byte and use it's hashValue (address) as the hashValue of the EventHandler let ptr = UnsafeMutablePointer<Int8>.alloc(1) var hashValue: Int { return ptr.hashValue } deinit { self.ptr.dealloc(1) } var callback: (([AnyObject]) -> ())? init(_ callback: (([AnyObject]) -> ())?) { self.callback = callback } } func ==(lhs: EventHandler, rhs: EventHandler) -> Bool { return lhs.hashValue == rhs.hashValue } class EventEmitter { private var handlers = Set<EventHandler>(); func emit(args: [AnyObject]) -> Int { var calls = 0 for handler in self.handlers { if let callback = handler.callback { callback(args) calls++ } } return calls } func addListener(listener: (([AnyObject]) -> ())?) -> EventHandler { let handler = EventHandler(listener) self.handlers.insert(handler) return handler } func removeListener(handler: EventHandler) { self.handlers.remove(handler) } func once(listener: ([AnyObject]) -> ()) -> EventHandler { let handler = self.addListener(nil) handler.callback = { args in listener(args) self.removeListener(handler) } return handler } func on(listener: ([AnyObject]) -> ()) -> EventHandler { return self.addListener(listener) } } class EventEmitter2<A: AnyObject, B: AnyObject> { private let emitter = EventEmitter() func emit(a: A, b: B) -> Int { return self.emitter.emit([ a, b ]) } func on(callback: (A, B) -> ()) -> EventHandler { return self.emitter.on { args in callback(args[0] as! A, args[1] as! B) } } func once(callback: (A, B) -> ()) -> EventHandler { return self.emitter.once { args in callback(args[0] as! A, args[1] as! B) } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class EventEmitter1<A: AnyObject> { private let emitter = EventEmitter() func emit(a: A) -> Int { return self.emitter.emit([a]) } func on(callback: (A) -> ()) -> EventHandler { return self.emitter.on { args in callback(args[0] as! A) } } func once(callback: (A) -> ()) -> EventHandler { return self.emitter.once { args in callback(args[0] as! A) } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class EventEmitter0 { private let emitter = EventEmitter() func emit() -> Int { return self.emitter.emit([]) } func on(callback: () -> ()) -> EventHandler { return self.emitter.on { _ in callback() } } func once(callback: () -> ()) -> EventHandler { return self.emitter.once { _ in callback() } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class ErrorEventEmitter: EventEmitter1<Error> { override func emit(error: Error) -> Int { let calls = super.emit(error) assert(calls > 0, "Unhandled 'error' event: \(error)") return calls } }
apache-2.0
xwu/NumericAnnex
Tests/NumericAnnexTests/RootExtractionTests.swift
1
2434
import XCTest @testable import NumericAnnex class RootExtractionTests : XCTestCase { func testSqrt() { XCTAssertEqual(Int.sqrt(0), 0) XCTAssertEqual(Int.sqrt(25), 5) XCTAssertEqual(Int.sqrt(27), 5) XCTAssertEqual(Int.sqrt(256), 16) XCTAssertEqual(Int.sqrt(512), 22) XCTAssertEqual(Int.sqrt(1 << 32) * .sqrt(1 << 32), 1 << 32) XCTAssertEqual(Int.sqrt(1 << 48) * .sqrt(1 << 48), 1 << 48) XCTAssertEqual(Int.sqrt(1 << 50) * .sqrt(1 << 50), 1 << 50) XCTAssertEqual(Int.sqrt(1 << 60) * .sqrt(1 << 60), 1 << 60) XCTAssertEqual(Int.sqrt(1 << 62) * .sqrt(1 << 62), 1 << 62) XCTAssertLessThanOrEqual(Int.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int8.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int16.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int32.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int64.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt8.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt16.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt32.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt64.sqrt(.max) * .sqrt(.max), .max) } func testCbrt() { XCTAssertEqual(UInt.cbrt(0), 0) XCTAssertEqual(UInt.cbrt(25), 2) XCTAssertEqual(UInt.cbrt(27), 3) XCTAssertEqual(UInt.cbrt(256), 6) XCTAssertEqual(UInt.cbrt(512), 8) XCTAssertLessThanOrEqual(UInt.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt8.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt16.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt32.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt64.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertEqual(Int.cbrt(-27), -3) XCTAssertLessThanOrEqual(Int.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int8.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int16.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int32.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int64.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) } static var allTests = [ ("testSqrt", testSqrt), ("testCbrt", testCbrt), ] }
mit
hhyyg/Miso.Gistan
Gistan/AppDelegate.swift
1
2496
// // AppDelegate.swift // Gistan // // Created by Hiroka Yago on 2017/09/30. // Copyright © 2017 miso. All rights reserved. // import UIKit import OAuthSwift import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { // when test do nothing return true } FirebaseApp.configure() try! loadSettings() return true } func loadSettings() throws { //load settings.plist let settingURL: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "settings", ofType: "plist")!) let data = try Data(contentsOf: settingURL) let decoder = PropertyListDecoder() SettingsContainer.settings = try decoder.decode(Settings.self, from: data) } func applicationWillResignActive(_ application: UIApplication) { // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate { func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if (url.host == "oauth-callback") { OAuthSwift.handle(url: url) } return true } }
mit
onekiloparsec/SwiftAA
Sources/SwiftAA/Angles.swift
2
6794
// // Angles.swift // SwiftAA // // Created by Cédric Foellmi on 17/12/2016. // MIT Licence. See LICENCE file. // import Foundation import ObjCAA /// The Degree is a unit of angle. public struct Degree: NumericType, CustomStringConvertible { /// The Degree value public let value: Double /// Returns a new Degree object. /// /// - Parameter value: The value of Degree. public init(_ value: Double) { self.value = value } /// Creates a new Degree instance, from sexagesimal components. /// /// - Parameters: /// - sign: The sign of the final value. /// - degrees: The integral degree component of the value. Sign is ignored. /// - arcminutes: The integral arcminute component of the value. Sign is ignored. /// - arcseconds: The fractional arcsecond component of the value. Sign is ignored. public init(_ sign: FloatingPointSign = .plus, _ degrees: Int, _ arcminutes: Int, _ arcseconds: Double) { let absDegree = abs(Double(degrees)) let absMinutes = abs(Double(arcminutes))/60.0 let absSeconds = abs(arcseconds)/3600.0 self.init(Double(sign) * (absDegree + absMinutes + absSeconds)) } /// Transform the current Degree in ArcMinutes public var inArcMinutes: ArcMinute { return ArcMinute(value * 60.0) } /// Transform the current Degree in ArcSeconds public var inArcSeconds: ArcSecond { return ArcSecond(value * 3600.0) } /// Transform the current Degree in Radians public var inRadians: Radian { return Radian(value * deg2rad) } /// Transform the current Degree in Hours public var inHours: Hour { return Hour(value / 15.0) } /// The sexagesimal notation of the Degree. public var sexagesimal: SexagesimalNotation { get { let deg = abs(value.rounded(.towardZero)) let min = ((abs(value) - deg) * 60.0).rounded(.towardZero) let sec = ((abs(value) - deg) * 60.0 - min) * 60.0 return (value > 0.0 ? .plus : .minus, Int(deg), Int(min), Double(sec)) } } /// Returns `self` reduced to 0..<360 range public var reduced: Degree { return Degree(value.positiveTruncatingRemainder(dividingBy: 360.0)) } /// Returns `self` reduced to -180..<180 range (around 0) public var reduced0: Degree { return Degree(value.zeroCenteredTruncatingRemainder(dividingBy: 360.0)) } /// Returns true if self is within circular [from,to] interval. Interval is opened by default. All values reduced to 0..<360 range. public func isWithinCircularInterval(from: Degree, to: Degree, isIntervalOpen: Bool = true) -> Bool { let isIntervalIntersectsZero = from.reduced < to.reduced let isFromLessThenSelf = isIntervalOpen ? from.reduced < self.reduced : from.reduced <= self.reduced let isSelfLessThenTo = isIntervalOpen ? self.reduced < to.reduced : self.reduced <= to.reduced switch (isIntervalIntersectsZero, isFromLessThenSelf, isSelfLessThenTo) { case (true, true, true): return true case (false, true, false), (false, false, true): return true default: return false } } public var description: String { let (sign, deg, min, sec) = self.sexagesimal return sign.string + String(format: "%i°%i'%06.3f\"", deg, min, sec) } } // MARK: - /// The ArcMinute is a unit of angle. public struct ArcMinute: NumericType, CustomStringConvertible { /// The ArcMinute value public let value: Double /// Creates a new ArcMinute instance. /// /// - Parameter value: The value of ArcMinute. public init(_ value: Double) { self.value = value } /// Transform the current ArcMinute in Degree public var inDegrees: Degree { return Degree(value / 60.0) } /// Transform the current ArcMinute in ArcSeconds public var inArcSeconds: ArcSecond { return ArcSecond(value * 60.0) } /// Transform the current ArcMinute in Hours public var inHours: Hour { return inDegrees.inHours } public var description: String { return String(format: "%.2f arcmin", value) } } // MARK: - /// The ArcSecond is a unit of angle. public struct ArcSecond: NumericType, CustomStringConvertible { /// The ArcSecond value public let value: Double /// Creates a new ArcSecond instance. /// /// - Parameter value: The value of ArcSecond. public init(_ value: Double) { self.value = value } /// Transform the current ArcSecond in Degrees public var inDegrees: Degree { return Degree(value / 3600.0) } /// Transform the current ArcSecond in ArcMinutes public var inArcMinutes: ArcMinute { return ArcMinute(value / 60.0) } /// Transform the current ArcSecond in Hours public var inHours: Hour { return inDegrees.inHours } /// Returns a new distance in Astronomical Units, the arcsecond being understood as a /// geometrical parallax. /// /// - Returns: The distance of the object. public func distance() -> Parsec { guard self.value > 0 else { fatalError("Value most be positive and above 0") } return Parsec(1.0/value) } /// Returns a new distance in Astronomical Units, the arcsecond being understood as a /// equatorial horizontal parallax, that is the difference between the topocentric and /// the geocentric coordinates of a solar system body (Sun, planet or comets). /// /// - Returns: The distance of the object. public func distanceFromEquatorialHorizontalParallax() -> AstronomicalUnit { return AstronomicalUnit(KPCAAParallax_ParallaxToDistance(inDegrees.value)) } public var description: String { return String(format: "%.2f arcsec", value) } } // MARK: - /// The Radian is a unit of angle. public struct Radian: NumericType, CustomStringConvertible { /// The Radian value public let value: Double /// Creates a new Radian instance. /// /// - Parameter value: The value of Radian. public init(_ value: Double) { self.value = value } /// Transform the current Radian in Degrees public var inDegrees: Degree { return Degree(value * rad2deg) } /// Transform the current Radian in Hours public var inHours: Hour { return Hour(value * rad2hour) } /// Returns self reduced to 0..<2PI range public var reduced: Radian { return Radian(value.positiveTruncatingRemainder(dividingBy: 2*Double.pi)) } /// Returns self reduced to -pi..<pi range (around 0) public var reduced0: Radian { return Radian(value.zeroCenteredTruncatingRemainder(dividingBy: 2*Double.pi)) } public var description: String { return String(format: "%.3f rad", value) } }
mit
onevcat/CotEditor
Tests/StringCollectionTests.swift
2
2608
// // StringCollectionTests.swift // Tests // // CotEditor // https://coteditor.com // // Created by 1024jp on 2017-03-19. // // --------------------------------------------------------------------------- // // © 2017-2020 1024jp // // 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 // // https://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 XCTest @testable import CotEditor final class StringCollectionTests: XCTestCase { func testAvailableNameCreation() { let names = ["foo", "foo 3", "foo copy 3", "foo 4", "foo 7"] let copy = "copy" XCTAssertEqual(names.createAvailableName(for: "foo"), "foo 2") XCTAssertEqual(names.createAvailableName(for: "foo 3"), "foo 5") XCTAssertEqual(names.createAvailableName(for: "foo", suffix: copy), "foo copy") XCTAssertEqual(names.createAvailableName(for: "foo 3", suffix: copy), "foo 3 copy") XCTAssertEqual(names.createAvailableName(for: "foo copy 3", suffix: copy), "foo copy 4") } func testRangeDiff() { let string1 = "family 👨‍👨‍👦 with 🐕" let string2 = "family 👨‍👨‍👦 and 🐕" XCTAssertEqual(string2.equivalentRanges(to: [NSRange(7..<15)], in: string1), [NSRange(7..<15)]) // 👨‍👨‍👦 XCTAssertEqual(string2.equivalentRanges(to: [NSRange(16..<20)], in: string1), [NSRange(16..<19)]) // with -> and XCTAssertEqual(string2.equivalentRanges(to: [NSRange(16..<18)], in: string1), [NSRange(16..<18)]) // wi -> an XCTAssertEqual(string2.equivalentRanges(to: [NSRange(21..<23)], in: string1), [NSRange(20..<22)]) // 🐕 XCTAssertEqual("".equivalentRanges(to: [NSRange(16..<20)], in: string1), [NSRange(0..<0)]) // with XCTAssertEqual(string1.equivalentRanges(to: [NSRange(0..<0)], in: string2), [NSRange(0..<0)]) XCTAssertEqual(string1.equivalentRanges(to: [NSRange(16..<19)], in: string2), [NSRange(16..<19)]) // and XCTAssertEqual(string1.equivalentRanges(to: [NSRange(16..<20)], in: string2), [NSRange(16..<21)]) // and_ } }
apache-2.0