repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
exoplatform/exo-ios
eXo/eXoAppDelegate.swift
1
16155
// // eXoAppDelegate.swift // eXo // // Created by Nguyen Manh Toan on 10/15/15. // Copyright © 2015 eXo. All rights reserved. // import UIKit import Firebase import FirebaseCrashlytics import FirebaseMessaging import UserNotifications import WebKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } @UIApplicationMain class eXoAppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate { var window: UIWindow? var quitTimestamp:Double? // Store the timestamps when user quit the app & Enter on Background var navigationVC:UINavigationController? var orientationLock = UIInterfaceOrientationMask.all var badgeCount:Int = 0 static let sessionTimeout:Double = 30*60 //To be verify this number, we are setting at 30mins. let defaults = UserDefaults.standard func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self // Quick launch if UserDefaults.standard.bool(forKey: "wasConnectedBefore") { let url = UserDefaults.standard.value(forKey: "serverURL") as! String // Memorise the last connection if UserDefaults.standard.bool(forKey: "isGoogleAuth") { let urlarry = url.components(separatedBy:"/portal/login") let updatedUrl = urlarry[0] + "/portal/login" setRootToHome(updatedUrl) }else{ setRootToHome(url) } }else{ handleRootConnect() } tryToRegisterForRemoteNotifications(application: application) 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) { quitTimestamp = Date().timeIntervalSince1970 // 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) { /* Verification of session timeout on server. When the session is timeout, go back to On-Boarding (Loggin) screen */ setRootSessionTimeout() // 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:. } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Reveived token: \(token)") Messaging.messaging().apnsToken = deviceToken } /* MARK: App Shortcut Handle */ @available(iOS 9.0, *) func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { completionHandler (handleShortcut(shortcutItem)) } @available(iOS 9.0, *) /* Handle all kinds of shortcuts - Add a new server: visible when no server has been configured. Using this shortcut, the app will open directly the InputServerViewController where user can enter the URL of the server - Open a recent server: Direct link to a configured Server (Maxi 4 most recent servers are availabel). The App will open a HomePageViewController configured with the selected server. */ func handleShortcut (_ shortcutItem: UIApplicationShortcutItem) -> Bool { var succeeded = false if (shortcutItem.type == ShortcutType.addNewServer) { succeeded = true if (navigationVC != nil) { if (navigationVC?.viewControllers.count > 0) { navigationVC?.popToRootViewController(animated: false) let inputServer = AddDomainViewController(nibName: "AddDomainViewController", bundle: nil) navigationVC?.pushViewController(inputServer as UIViewController, animated: false) } } } else if (shortcutItem.type == ShortcutType.connectRecentServer) { succeeded = true let serverDictionary = shortcutItem.userInfo if (serverDictionary != nil) { let server:Server = Server(serverDictionary: serverDictionary! as NSDictionary) ServerManager.sharedInstance.addEditServer(server) self.quickActionOpenHomePageForURL(server.serverURL) } } return succeeded } /* Open home page after push notif. */ func quickActionOpenHomePageForURL (_ stringURL:String) { if (navigationVC != nil) { if (navigationVC?.viewControllers.count > 0) { navigationVC?.popToRootViewController(animated: false) if let homepage = navigationVC?.viewControllers.last?.storyboard?.instantiateViewController(withIdentifier: "HomePageViewController"){ print(String(describing: navigationVC?.viewControllers.last)) (homepage as! HomePageViewController).serverURL = stringURL navigationVC?.navigationBar.isHidden = false navigationVC?.pushViewController(homepage as UIViewController, animated: false) }else{ navigationVC?.viewControllers.removeAll() setRootToHome(stringURL) } } } } /* MARK: Firebase messaging */ func application(_ application: UIApplication,performFetchWithCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) { // Check for new data. completionHandler(UIBackgroundFetchResult.newData) } func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { if let _fcmToken = fcmToken { print("Reveived fcmToken: \(_fcmToken)") } PushTokenSynchronizer.shared.token = fcmToken let tokenDict = ["token": fcmToken ?? ""] postNotificationWith(key: Notification.Name("FCMToken"), info: tokenDict) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { handleNotification(userInfo: userInfo); } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { handleNotification(userInfo: userInfo); print("UIBackgroundFetchResult =====> \(userInfo)") completionHandler(UIBackgroundFetchResult.newData) } func application(_ application: UIApplication,didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return self.orientationLock } } extension eXoAppDelegate: UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // Print full message. // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) center.requestAuthorization(options: [.alert, .sound, .badge]) { (isSucc, error) in if isSucc { print(userInfo.description) if let aps = userInfo["aps"] as? NSDictionary { if let badge = aps["badge"] as? Int { self.setBadgeNumber(badge: badge) if let url = userInfo["url"] as? String { let server:Server = Server(serverURL: Tool.extractServerUrl(sourceUrl: url)) var dic:Dictionary = [String:Int]() for ser in ServerManager.sharedInstance.serverList { if let serverURL = (ser as? Server)?.serverURL { if serverURL.stringURLWithoutProtocol() == server.serverURL.stringURLWithoutProtocol() { dic[server.serverURL.stringURLWithoutProtocol()] = badge } } } self.defaults.setValue(dic, forKey: "badgeNumber") self.postNotificationWith(key: .reloadTableView) } } } } } // Change this to your preferred presentation option completionHandler([.badge, .alert, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print full message. handleNotification(userInfo: userInfo) completionHandler() } } extension eXoAppDelegate { func setRootToHome(_ serverURL:String){ let sb = UIStoryboard(name: "Main", bundle: nil) let homepageVC = sb.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController let server = Server(serverURL: serverURL.serverDomainWithProtocolAndPort!) ServerManager.sharedInstance.addEditServer(server) homepageVC.serverURL = serverURL navigationVC = UINavigationController(rootViewController: homepageVC) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = navigationVC window?.makeKeyAndVisible() } func setRootToConnect(){ let connectVC = ConnectToExoViewController(nibName: "ConnectToExoViewController", bundle: nil) navigationVC = UINavigationController(rootViewController: connectVC) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = navigationVC window?.makeKeyAndVisible() } func setRootOnboarding(){ let rootVC = OnboardingViewController(nibName: "OnboardingViewController", bundle: nil) navigationVC = UINavigationController(rootViewController: rootVC) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = navigationVC window?.makeKeyAndVisible() } func handleRootConnect(){ if ServerManager.sharedInstance.serverList.count != 0 { setRootToConnect() }else{ setBadgeNumber(badge: 0) setRootOnboarding() } } func handleNotification(userInfo: [AnyHashable: Any]) { if let url = userInfo["url"] as? String { let server:Server = Server(serverURL: Tool.extractServerUrl(sourceUrl: url)) ServerManager.sharedInstance.addEditServer(server) self.quickActionOpenHomePageForURL(url) } if let aps = userInfo["aps"] as? NSDictionary { print(aps) if let badge = aps["badge"] as? Int { self.setBadgeNumber(badge: badge) } } } func tryToRegisterForRemoteNotifications(application: UIApplication) { let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, _ in guard granted else { return } DispatchQueue.main.async { application.registerForRemoteNotifications() } } } // Set the badge number of the app icon. func setBadgeNumber(badge:Int){ DispatchQueue.main.async { UIApplication.shared.applicationIconBadgeNumber = badge } } func setRootSessionTimeout() { if PushTokenSynchronizer.shared.isSessionExpired(delegate: (self.window?.rootViewController)!, inWeb: false) { /// old API cookies for cookie in HTTPCookieStorage.shared.cookies ?? [] { HTTPCookieStorage.shared.deleteCookie(cookie) } /// URL cache URLCache.shared.removeAllCachedResponses() WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0), completionHandler: {}) handleRootConnect() } } func postNotificationWith(key:Notification.Name,info:[AnyHashable:Any]){ NotificationCenter.default.post(name: key, object: nil, userInfo: info) } func postNotificationWith(key:Notification.Name){ NotificationCenter.default.post(name: key, object: nil) } } struct AppUtility { static func lockOrientation(_ orientation: UIInterfaceOrientationMask) { if let delegate = UIApplication.shared.delegate as? eXoAppDelegate { delegate.orientationLock = orientation } } /// OPTIONAL Added method to adjust lock and rotate to the desired orientation static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) { self.lockOrientation(orientation) UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") UINavigationController.attemptRotationToDeviceOrientation() } }
lgpl-3.0
05157947babc6c71e70f02c8308a2979
43.379121
285
0.652346
5.616829
false
false
false
false
frootloops/swift
stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
2
9947
//===--- Subprocess.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #endif #if !os(Windows) // posix_spawn is not available on Windows. // posix_spawn is not available on Android. // posix_spawn is not available on Haiku. #if !os(Android) && !os(Haiku) // posix_spawn isn't available in the public watchOS SDK, we sneak by the // unavailable attribute declaration here of the APIs that we need. // FIXME: Come up with a better way to deal with APIs that are pointers on some // platforms but not others. #if os(Linux) typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t #else typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #endif @_silgen_name("_stdlib_posix_spawn_file_actions_init") internal func _stdlib_posix_spawn_file_actions_init( _ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("_stdlib_posix_spawn_file_actions_destroy") internal func _stdlib_posix_spawn_file_actions_destroy( _ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("_stdlib_posix_spawn_file_actions_addclose") internal func _stdlib_posix_spawn_file_actions_addclose( _ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>, _ filedes: CInt) -> CInt @_silgen_name("_stdlib_posix_spawn_file_actions_adddup2") internal func _stdlib_posix_spawn_file_actions_adddup2( _ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>, _ filedes: CInt, _ newfiledes: CInt) -> CInt @_silgen_name("_stdlib_posix_spawn") internal func _stdlib_posix_spawn( _ pid: UnsafeMutablePointer<pid_t>?, _ file: UnsafePointer<Int8>, _ file_actions: UnsafePointer<_stdlib_posix_spawn_file_actions_t>?, _ attrp: UnsafePointer<posix_spawnattr_t>?, _ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>, _ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt #endif /// Calls POSIX `pipe()`. func posixPipe() -> (readFD: CInt, writeFD: CInt) { var fds: [CInt] = [ -1, -1 ] if pipe(&fds) != 0 { preconditionFailure("pipe() failed") } return (fds[0], fds[1]) } /// Start the same executable as a child process, redirecting its stdout and /// stderr. public func spawnChild(_ args: [String]) -> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) { // The stdout, stdin, and stderr from the child process will be redirected // to these pipes. let childStdout = posixPipe() let childStdin = posixPipe() let childStderr = posixPipe() #if os(Android) || os(Haiku) // posix_spawn isn't available on Android. Instead, we fork and exec. // To correctly communicate the exit status of the child process to this // (parent) process, we'll use this pipe. let childToParentPipe = posixPipe() let pid = fork() precondition(pid >= 0, "fork() failed") if pid == 0 { // pid of 0 means we are now in the child process. // Capture the output before executing the program. dup2(childStdout.writeFD, STDOUT_FILENO) dup2(childStdin.readFD, STDIN_FILENO) dup2(childStderr.writeFD, STDERR_FILENO) // Set the "close on exec" flag on the parent write pipe. This will // close the pipe if the execve() below successfully executes a child // process. let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC) let closeErrno = errno precondition( closeResult == 0, "Could not set the close behavior of the child-to-parent pipe; " + "errno: \(closeErrno)") // Start the executable. If execve() does not encounter an error, the // code after this block will never be executed, and the parent write pipe // will be closed. withArrayOfCStrings([CommandLine.arguments[0]] + args) { execve(CommandLine.arguments[0], $0, environ) } // If execve() encountered an error, we write the errno encountered to the // parent write pipe. let errnoSize = MemoryLayout.size(ofValue: errno) var execveErrno = errno let writtenBytes = withUnsafePointer(to: &execveErrno) { write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize) } let writeErrno = errno if writtenBytes > 0 && writtenBytes < errnoSize { // We were able to write some of our error, but not all of it. // FIXME: Retry in this case. preconditionFailure("Unable to write entire error to child-to-parent " + "pipe.") } else if writtenBytes == 0 { preconditionFailure("Unable to write error to child-to-parent pipe.") } else if writtenBytes < 0 { preconditionFailure("An error occurred when writing error to " + "child-to-parent pipe; errno: \(writeErrno)") } // Close the pipe when we're done writing the error. close(childToParentPipe.writeFD) } #else var fileActions = _make_posix_spawn_file_actions_t() if _stdlib_posix_spawn_file_actions_init(&fileActions) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_init() failed") } // Close the write end of the pipe on the child side. if _stdlib_posix_spawn_file_actions_addclose( &fileActions, childStdin.writeFD) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed") } // Remap child's stdin. if _stdlib_posix_spawn_file_actions_adddup2( &fileActions, childStdin.readFD, STDIN_FILENO) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if _stdlib_posix_spawn_file_actions_addclose( &fileActions, childStdout.readFD) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed") } // Remap child's stdout. if _stdlib_posix_spawn_file_actions_adddup2( &fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if _stdlib_posix_spawn_file_actions_addclose( &fileActions, childStderr.readFD) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed") } // Remap child's stderr. if _stdlib_posix_spawn_file_actions_adddup2( &fileActions, childStderr.writeFD, STDERR_FILENO) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed") } var pid: pid_t = -1 var childArgs = args childArgs.insert(CommandLine.arguments[0], at: 0) let interpreter = getenv("SWIFT_INTERPRETER") if interpreter != nil { if let invocation = String(validatingUTF8: interpreter!) { childArgs.insert(invocation, at: 0) } } let spawnResult = withArrayOfCStrings(childArgs) { _stdlib_posix_spawn( &pid, childArgs[0], &fileActions, nil, $0, environ) } if spawnResult != 0 { print(String(cString: strerror(spawnResult))) preconditionFailure("_stdlib_posix_spawn() failed") } if _stdlib_posix_spawn_file_actions_destroy(&fileActions) != 0 { preconditionFailure("_stdlib_posix_spawn_file_actions_destroy() failed") } #endif // Close the read end of the pipe on the parent side. if close(childStdin.readFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStdout.writeFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStderr.writeFD) != 0 { preconditionFailure("close() failed") } return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD) } #if !os(Android) && !os(Haiku) #if os(Linux) internal func _make_posix_spawn_file_actions_t() -> _stdlib_posix_spawn_file_actions_t { return posix_spawn_file_actions_t() } #else internal func _make_posix_spawn_file_actions_t() -> _stdlib_posix_spawn_file_actions_t { return nil } #endif #endif internal func _signalToString(_ signal: Int) -> String { switch CInt(signal) { case SIGILL: return "SIGILL" case SIGTRAP: return "SIGTRAP" case SIGABRT: return "SIGABRT" case SIGFPE: return "SIGFPE" case SIGBUS: return "SIGBUS" case SIGSEGV: return "SIGSEGV" case SIGSYS: return "SIGSYS" default: return "SIG???? (\(signal))" } } public enum ProcessTerminationStatus : CustomStringConvertible { case exit(Int) case signal(Int) public var description: String { switch self { case .exit(let status): return "Exit(\(status))" case .signal(let signal): return "Signal(\(_signalToString(signal)))" } } } public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus { var status: CInt = 0 #if os(Cygwin) withUnsafeMutablePointer(to: &status) { statusPtr in let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr) while waitpid(pid, statusPtrWrapper, 0) < 0 { if errno != EINTR { preconditionFailure("waitpid() failed") } } } #else while waitpid(pid, &status, 0) < 0 { if errno != EINTR { preconditionFailure("waitpid() failed") } } #endif if WIFEXITED(status) { return .exit(Int(WEXITSTATUS(status))) } if WIFSIGNALED(status) { return .signal(Int(WTERMSIG(status))) } preconditionFailure("did not understand what happened to child process") } // !os(Windows) #endif
apache-2.0
593b3012e7d6ac6c4b28edfe33e94dfc
32.491582
85
0.680808
3.783568
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/WebViewController.swift
1
3973
// // WebViewController.swift // Wuakup // // Created by Guillermo Gutiérrez on 13/02/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import UIKit import WebKit open class WebViewController: LoadingPresenterViewController, WKNavigationDelegate, WKUIDelegate { open var url: URL? open var showRefreshButton = false var isModal: Bool { guard let navigationController = navigationController else { return false } return navigationController.presentingViewController != nil && navigationController.viewControllers.first == self } @IBOutlet var webView: WKWebView! open func loadUrl(_ url: URL, animated: Bool = true) { self.url = url showLoadingView() webView?.load(URLRequest(url: url)) } // MARK: View lifecycle open override func viewDidLoad() { super.viewDidLoad() setupLoadingView() webView?.uiDelegate = self webView?.navigationDelegate = self } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.presentedViewController == nil { if let url = self.url { loadUrl(url, animated: false) } } // Auto-detect modal and add close button if isModal && navigationItem.leftBarButtonItem == nil { let closeButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(WebViewController.dismissAction(_:))) navigationItem.leftBarButtonItem = closeButton } if showRefreshButton && navigationItem.rightBarButtonItem == nil { let refreshButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(WebViewController.refreshAction(_:))) navigationItem.rightBarButtonItem = refreshButton } } open func openInSafari() -> Bool { guard let url = url else { return false } if (UIApplication.shared.canOpenURL(url)) { UIApplication.shared.open(url, options: [:], completionHandler: nil) return true } return false; } open func closeController(_ animated: Bool = true) { if let navigationController = navigationController { navigationController.popViewController(animated: animated) } if let presentingViewController = presentingViewController { presentingViewController.dismiss(animated: animated, completion: nil) } } // MARK: Actions @objc func dismissAction(_ sender: NSObject!) { dismiss(animated: true, completion: nil) } @objc func refreshAction(_ sender: NSObject!) { webView.reload() } // MARK: WKNavigationDelegate open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { dismissLoadingView() let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 204 { return } if #available(iOS 9.0, *) { if error.domain == NSURLErrorDomain && error.code == NSURLErrorAppTransportSecurityRequiresSecureConnection { if openInSafari() { closeController() return } } } let alert = UIAlertController(title: "WebViewError".i18n(), message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "CloseDialogButton".i18n(), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { showLoadingView() } open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { dismissLoadingView() } }
mit
d4e5a237797f036b76729bd4cafa16fd
33.842105
148
0.630916
5.509015
false
false
false
false
Kgiberson/zen-doodle
ZenDoodle/ZenDoodle/ViewController.swift
1
1914
// // ViewController.swift // ZenDoodle // // Created by Apprentice on 5/13/16. // Copyright © 2016 ZenDoodle. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var pauseButtonOutlet: UIButton! @IBOutlet weak var playButtonOutlet: UIButton! var player = AVAudioPlayer() let url:NSURL = NSBundle.mainBundle().URLForResource("KatyZenDoodle2", withExtension: "aiff")! func sound() { do { player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) } catch let error as NSError { print(error.description) } player.prepareToPlay() player.play() } func pausePlayer() { if !player.playing { player.play() pauseButtonOutlet.setImage(UIImage(named: "PauseButton.png"), forState: UIControlState.Normal) } else { player.numberOfLoops = 0 player.pause() pauseButtonOutlet.setImage(UIImage(named: "PlayButton.png"), forState: UIControlState.Normal) } } override func viewDidLoad() { self.view.backgroundColor = UIColor(red: 0.922, green: 0.898, blue: 0.898, alpha: 1) super.viewDidLoad() pauseButtonOutlet.hidden = true // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } @IBAction func playButton(sender: AnyObject) { playButtonOutlet.hidden = true pauseButtonOutlet.hidden = false sound() } @IBAction func pauseButton(sender: AnyObject) { pausePlayer() } }
mit
4c988f22a42f0a045573cd6f8b090746
27.984848
106
0.646628
4.81864
false
false
false
false
khizkhiz/swift
test/attr/attributes.swift
4
8153
// RUN: %target-parse-verify-swift @unknown func f0() {} // expected-error{{unknown attribute 'unknown'}} enum binary { case Zero case One init() { self = .Zero } } func f5(x: inout binary) {} //===--- //===--- IB attributes //===--- @IBDesignable class IBDesignableClassTy { @IBDesignable func foo() {} // expected-error {{@IBDesignable cannot be applied to this declaration}} {{3-17=}} } @IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}} struct IBDesignableStructTy {} @IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}} protocol IBDesignableProtTy {} @IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}} extension IBDesignableStructTy {} class IBDesignableClassExtensionTy {} @IBDesignable // okay extension IBDesignableClassExtensionTy {} class Inspect { @IBInspectable var value : Int = 0 @IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}} @IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}} } @IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}} @objc_block // expected-error {{attribute can only be applied to types, not declarations}} func foo() {} func foo(x: @convention(block) Int) {} // expected-error {{attribute only applies to syntactic function types}} func foo(x: @convention(block) (Int) -> Int) {} @_transparent func zim() {} @_transparent func zung<T>(_: T) {} @_transparent // expected-error{{@_transparent cannot be applied to stored properties}} {{1-15=}} var zippity : Int func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}} protocol ProtoWithTransparent { @_transparent// expected-error{{@_transparent is not supported on declarations within protocols}} {{3-16=}} func transInProto() } class TestTranspClass : ProtoWithTransparent { @_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}} init () {} @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{3-17=}} deinit {} @_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}} class func transStatic() {} @_transparent// expected-error{{@_transparent is not supported on declarations within classes}} {{3-16=}} func transInProto() {} } struct TestTranspStruct : ProtoWithTransparent{ @_transparent init () {} @_transparent init <T> (x : T) { } @_transparent static func transStatic() {} @_transparent func transInProto() {} } @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}} struct CannotHaveTransparentStruct { func m1() {} } @_transparent // expected-error{{@_transparent is only supported on struct and enum extensions}} {{1-15=}} extension TestTranspClass { func tr1() {} } @_transparent extension TestTranspStruct { func tr1() {} } @_transparent extension binary { func tr1() {} } class transparentOnCalssVar { @_transparent var max: Int { return 0xFF }; // expected-error {{@_transparent is not supported on declarations within classes}} {{3-17=}} func blah () { var _: Int = max } }; class transparentOnCalssVar2 { var max: Int { @_transparent // expected-error {{@_transparent is not supported on declarations within classes}} {{5-19=}} get { return 0xFF } } func blah () { var _: Int = max } }; @thin // expected-error {{attribute can only be applied to types, not declarations}} func testThinDecl() -> () {} protocol Class : class {} protocol NonClass {} @objc class Ty0 : Class, NonClass { init() { } } // Attributes that should be reported by parser as unknown // See rdar://19533915 @__accessibility struct S__accessibility {} // expected-error{{unknown attribute '__accessibility'}} @__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}} @__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}} weak var weak0 : Ty0? weak var weak0x : Ty0? weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned var weak3 : Ty0 unowned var weak3a : Ty0 unowned(safe) var weak3b : Ty0 unowned(unsafe) var weak3c : Ty0 unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak var weak6 : Int // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} unowned var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}} weak var weak8 : Class? = Ty0() unowned var weak9 : Class = Ty0() weak var weak10 : NonClass = Ty0() // expected-error {{'weak' may not be applied to non-class-bound protocol 'NonClass'; consider adding a class bound}} unowned var weak11 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound protocol 'NonClass'; consider adding a class bound}} unowned var weak12 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound protocol 'NonClass'; consider adding a class bound}} unowned var weak13 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound protocol 'NonClass'; consider adding a class bound}} weak var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}} weak var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}} weak var weak16 : Class! @weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}} @_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} // Function result type attributes. var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}} func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}} return 4 } // @thin is not supported except in SIL. var thinFunc : @thin () -> () // expected-error {{attribute is not supported}} @inline(never) func nolineFunc() {} @inline(never) var noinlineVar : Int // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}} @inline(never) class FooClass { // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}} } @inline(__always) func AlwaysInlineFunc() {} @inline(__always) var alwaysInlineVar : Int // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}} @inline(__always) class FooClass2 { // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}} } class A { @inline(never) init(a : Int) {} var b : Int { @inline(never) get { return 42 } @inline(never) set { } } } class B { @inline(__always) init(a : Int) {} var b : Int { @inline(__always) get { return 42 } @inline(__always) set { } } } class SILStored { @sil_stored var x : Int = 42 // expected-error {{'sil_stored' only allowed in SIL modules}} } @_show_in_interface protocol _underscored {} @_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
apache-2.0
96deed4e7e70ba8337371375f801a592
34.294372
152
0.692261
3.893505
false
false
false
false
czj1127292580/weibo_swift
WeiBo_Swift/WeiBo_Swift/Class/OAuth/OAuthViewController.swift
1
4944
// // OAuthViewController.swift // WeiBo_Swift // // Created by 岑志军 on 16/8/25. // Copyright © 2016年 cen. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController { let WB_App_key = "1684485375" let WB_App_Secret = "62de959eb4a3d4c74c250220350bea47" let WB_redirect_uri = "http://www.baidu.com" override func loadView() { view = webView } override func viewDidLoad() { super.viewDidLoad() // 初始化导航条 navigationItem.title = "军哥的战斗机" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(close)) // 1、获取未授权的RequestToken let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_key)&redirect_uri=\(WB_redirect_uri)" let url = NSURL(string: urlStr) let request = NSURLRequest(URL: url!) webView.loadRequest(request) } func close() { dismissViewControllerAnimated(true, completion: nil) } // MARK: - 懒加载 private lazy var webView: UIWebView = { let wv = UIWebView() wv.delegate = self return wv }() } extension OAuthViewController: UIWebViewDelegate{ func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{ // 判断是否是授权回调页,如果不是继续加载 let urlStr = request.URL!.absoluteString if !urlStr!.hasPrefix(WB_redirect_uri) { return true } // 判断是否授权成功 let codeStr = "code=" if request.URL!.query!.hasPrefix(codeStr) { // 代表授权成功 // 取出已经授权的RequestToken let code = request.URL!.query!.substringFromIndex(codeStr.endIndex) // 利用已经授权的RequestToken换取AccessToken loadAccessToken(code) } else { // 授权失败 close() } return false } func webViewDidStartLoad(webView: UIWebView) { // 提示用户正在加载 // SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black) SVProgressHUD.showInfoWithStatus("正在加载...") SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black) } func webViewDidFinishLoad(webView: UIWebView) { // 关闭提示 SVProgressHUD.dismiss() } private func loadAccessToken(code: String) { // 定义路径h let path = "oauth2/access_token" // 封装参数 let params = ["client_id":WB_App_key, "client_secret":WB_App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_redirect_uri] // 发送post请求 // NetWorkTools.shareNetWorkTools().POST(path, parameters: params, success: { (_, JSON) in // print(JSON) // }) { (_, error) in // print(error) // } NetWorkTools.shareNetWorkTools().POST(path, parameters: params, progress: nil, success: { (_, JSON) in /** * 同一个用户对同一个应用程序授权多次access_token是一样的 每个access_token都是有过期时间的: 1、如果自己对自己的应用程序进行授权,有效时间是5年差一天 2、如果是其他人对你的应用程序进行授权,有效期是3天 */ // "access_token" = "2.001s2jaDxavzpBbf04ba92e6Fk8irC"; // "expires_in" = 157679999; // "remind_in" = 157679999; // uid = 3291155444; // print(JSON) let account = UserAccount(dict: JSON as! [String : AnyObject]) // 获取用户信息 // account.loadUserInfo() account.loadUserInfo({ (account, error) in if account != nil{ account?.saveAccount() NSNotificationCenter.defaultCenter().postNotificationName(ZJSwitchRootViewControllerKey, object: false) return } SVProgressHUD.showInfoWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black) }) // 由于加载数据是异步的,所以不能在这里保存用户信息 // // 归档模型 // account.saveAccount() }) { (_, error) in print(error) } } }
mit
839cbac936f64c0f5441ebe2b79f9c28
26.782609
147
0.541695
4.52275
false
false
false
false
dleonard00/firebase-user-signup
Pods/Material/Sources/MaterialLabel.swift
1
3411
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public class MaterialLabel : UILabel { /** :name: layerClass */ public override class func layerClass() -> AnyClass { return MaterialTextLayer.self } /** :name: textLayer */ public var textLayer: MaterialTextLayer { return layer as! MaterialTextLayer } /** :name: text */ public override var text: String? { didSet { textLayer.text = text } } /** :name: textColor */ public override var textColor: UIColor? { didSet { textLayer.textColor = textColor } } /** :name: font */ public override var font: UIFont! { didSet { textLayer.fontType = font } } /** :name: textAlignment */ public override var textAlignment: NSTextAlignment { didSet { textLayer.textAlignment = textAlignment } } /** :name: wrapped */ public var wrapped: Bool { didSet { textLayer.wrapped = wrapped } } /** :name: contentsScale */ public var contentsScale: CGFloat { didSet { textLayer.contentsScale = contentsScale } } /** :name: lineBreakMode */ public override var lineBreakMode: NSLineBreakMode { didSet { textLayer.lineBreakMode = lineBreakMode } } /** :name: init */ public required init?(coder aDecoder: NSCoder) { wrapped = true contentsScale = MaterialDevice.scale super.init(coder: aDecoder) } /** :name: init */ public override init(frame: CGRect) { wrapped = true contentsScale = MaterialDevice.scale super.init(frame: frame) prepareView() } /** :name: init */ public convenience init() { self.init(frame: CGRectNull) prepareView() } /** :name: stringSize */ public func stringSize(constrainedToWidth width: Double) -> CGSize { return textLayer.stringSize(constrainedToWidth: width) } /** :name: prepareView */ public func prepareView() { textAlignment = .Left } }
mit
bcb648a086352d03a4ad7e8b3d0da569
21.596026
86
0.716212
3.707609
false
false
false
false
cuappdev/podcast-ios
old/Podcast/DownloadManager.swift
1
7431
// // DownloadManager.swift // Podcast // // Created by Drew Dunne on 2/17/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit import Alamofire enum DownloadStatus { case waiting case downloading(Double) case finished case failed case removed case cancelled } // To receive updates set yourself as delegate. Only one can receive at a time. protocol EpisodeDownloader: class { func didReceive(statusUpdate: DownloadStatus, for episode: Episode) } class DownloadManager: NSObject { static let shared = DownloadManager() private var filePath: String { let manager = FileManager.default let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first return (url!.appendingPathComponent("SaveData").path) } var downloaded: [String: Episode] var downloadRequests: [String: DownloadRequest] var resumeData: [String: Data] // QUESTION: delegate or NSNotification or custom KVO? // Hopefully only temporary, we'll see what realm does. // This kind of an abuse of delegates but honestly it's // kind of nice. Basically any view that wants updates // sets itself as the delegate on viewDidAppear. // Doesn't have to worry about removing itself because // it's a weak reference, and only one view at a time // gets updates. weak var delegate: EpisodeDownloader? private override init() { downloaded = [:] downloadRequests = [:] resumeData = [:] super.init() if !saveAllData() { print("Error loading download data.") } } // Cannot return download progress func status(for episode: String) -> DownloadStatus { if isDownloading(episode) { return .waiting } else if isDownloaded(episode) { return .finished } else { return .removed } } func isDownloaded(_ episode: String) -> Bool { return downloaded.contains(where: { (k, v) in k == episode}) } func isDownloading(_ episode: String) -> Bool { return downloadRequests.contains(where: { (k, v) in k == episode}) } func actionSheetType(for episode: String) -> ActionSheetOptionType { if isDownloaded(episode) { return .download(selected: true) } else if isDownloading(episode) { return .cancelDownload } else { return .download(selected: false) } } func fileUrl(for episode: Episode) -> URL { if let url = episode.audioURL { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let pathURL = documentsURL.appendingPathComponent("downloaded").appendingPathComponent("\(episode.id)_\(episode.seriesTitle)") return pathURL.appendingPathComponent(episode.id + "_" + url.lastPathComponent) } else { // This path should never be used let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let pathURL = documentsURL.appendingPathComponent("downloaded").appendingPathComponent("\(episode.id)_\(episode.seriesTitle)") return pathURL.appendingPathComponent(episode.id) } } // Requires: episode is not downloaded or paused func download(_ episode: Episode) { guard let audioUrl = episode.audioURL else { return } let destination: DownloadRequest.DownloadFileDestination = { _, _ in // This can't fail if audioURL is defined return (self.fileUrl(for: episode), [.removePreviousFile, .createIntermediateDirectories]) } let request: DownloadRequest if let data = resumeData[episode.id] { request = Alamofire.download(resumingWith: data, to: destination) } else { request = Alamofire.download(audioUrl, to: destination) } downloadRequests[episode.id] = request delegate?.didReceive(statusUpdate: .waiting, for: episode) request // Leave comment // .downloadProgress { progress in // self.delegate?.didReceive(statusUpdate: .downloading(progress.fractionCompleted), for: episode) // } .responseData { response in switch response.result { case .success(_): self.registerDownload(for: episode) self.delegate?.didReceive(statusUpdate: .finished, for: episode) case .failure: self.delegate?.didReceive(statusUpdate: .failed, for: episode) } } } func deleteDownload(of episode: Episode) { do { let fileManager = FileManager.default try fileManager.removeItem(atPath: fileUrl(for: episode).path) clearDownloadData(for: episode) delegate?.didReceive(statusUpdate: .removed, for: episode) } catch let error as NSError { // Couldn't remove (probably not there), so remove from downloaded state clearDownloadData(for: episode) delegate?.didReceive(statusUpdate: .removed, for: episode) print("Couldn't delete the file because of: \(error). Removing record of download. ") } } func cancelDownload(of episode: Episode) { if let request = downloadRequests[episode.id] { request.cancel() clearDownloadData(for: episode) delegate?.didReceive(statusUpdate: .cancelled, for: episode) } } func handle(_ episode: Episode) { if isDownloaded(episode.id) { deleteDownload(of: episode) } else if isDownloading(episode.id) { cancelDownload(of: episode) } else { download(episode) } } // Returns if successfully registered private func registerDownload(for episode: Episode) { downloaded[episode.id] = episode downloadRequests.removeValue(forKey: episode.id) resumeData.removeValue(forKey: episode.id) if !saveAllData() { print("Error saving. ") } } // Returns if successfully removed private func clearDownloadData(for episode: Episode) { downloaded.removeValue(forKey: episode.id) downloadRequests.removeValue(forKey: episode.id) resumeData.removeValue(forKey: episode.id) if !saveAllData() { print("Error saving. ") } } // Returns true if successful func saveAllData() -> Bool { return NSKeyedArchiver.archiveRootObject(downloaded, toFile: filePath) } // Returns true if successful func loadAllData() -> Bool { if let data = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [String: Episode] { downloaded = data // Update list with Cache items if exist // otherwise add to Cache downloaded.forEach { (id, episode) in if let e = Cache.sharedInstance.get(episode: id) { downloaded[id] = e } else { Cache.sharedInstance.add(episode) } } return true } return false } }
mit
082eb6646a25bef7e84169c3568805d6
34.550239
138
0.607537
4.99328
false
false
false
false
tectijuana/iOS
PáramoAimeé/Practicas Libro/3 Ejercicio.swift
2
210
import Fundation let MAX : UInt32 = 9 let MIN : UInt32 = 1 func randomNumber() { var random_number = Int(arc4random_uniform(MAX) + MIN) print ("Dado 1 = ", random_number); print ("Dado 2 = ") }
mit
b2f4eff5b55f2a0443826e64467313eb
18.181818
57
0.619048
2.957746
false
false
false
false
radex/swift-compiler-crashes
crashes-fuzzing/21372-llvm-basicblock-removepredecessor.swift
11
633
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ) } e? { } class d<T where g: b: d: NSManagedObject { let : Any, : where H.f == [0x31 ] = nil t: { class B ( Int = B T) { case a protocol b { func g T where S<T where g: { _ = } } import let : (b func : ((a } struct Q<T B e? } class class { <T A<T Type { } class } func b: : c { typealias e Int = { let d B { func i<b Q< ) { } B<T : N enum S T where g: A { func ) ( { Q<T where B class import class A (", let String { let end = [Void{ class <T where B : { protoco
mit
b2299d0307a761df21984feddbfae354
10.943396
87
0.612954
2.501976
false
false
false
false
CocoaHeadsBrasil/SwiftMagazine
SwiftMagazine/LibraryTableViewController.swift
1
6605
// // LibraryTableViewController.swift // SwiftMagazine // // Created by Heberti Almeida on 18/09/14. // Copyright (c) 2014 CocoaHeads Brasil. All rights reserved. // import UIKit let reuseFeatured = "CellFeatured" let reuseMagazines = "CellMagazines" let reuseCollectionItem = "CollectionReuse" let collectionTag = 123 class LibraryTableViewController: UITableViewController, UICollectionViewDelegate, UICollectionViewDataSource { override func viewDidLoad() { super.viewDidLoad() self.title = "Swift Magazine" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 4 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return 1 } //MARK: - UICollectionView Data Source func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch collectionView { case is FeaturedCollectionView: return 4 default: return 10 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var reuseIdentifier: String! switch indexPath.section { case 0: reuseIdentifier = reuseFeatured default: reuseIdentifier = reuseMagazines } var reusableCell: AnyObject = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) switch indexPath.section { case 0: // Magazines collection var cell = reusableCell as FeaturedTableViewCell // CollectionView Frame var collectionFrame = cell.contentView.frame // CollectionView if cell.contentView.viewWithTag(collectionTag) == nil { cell.collectionView = FeaturedCollectionView(frame: collectionFrame, index: indexPath.section) as FeaturedCollectionView cell.collectionView.tag = collectionTag cell.collectionView.dataSource = self cell.collectionView.delegate = self cell.collectionView.pagingEnabled = true cell.contentView.addSubview(cell.collectionView) } // Configure the cell... cell.contentView.backgroundColor = UIColor(red: 1/255, green: 140/255, blue: 185/255, alpha: 1) cell.backgroundColor = UIColor.clearColor() return cell default: // Featured cell slider var cell = reusableCell as MagazineTableViewCell cell.title.text = "Category #\(indexPath.section)" // CollectionView Frame var gap: CGFloat = 52 var collectionFrame = cell.contentView.frame collectionFrame.size.height -= gap collectionFrame.origin.y = gap // CollectionView if cell.contentView.viewWithTag(collectionTag) == nil { cell.collectionView = MagazineCollectionView(frame: collectionFrame, index: indexPath.section) as MagazineCollectionView cell.collectionView.tag = collectionTag cell.collectionView.dataSource = self cell.collectionView.delegate = self cell.contentView.addSubview(cell.collectionView) } // Configure the cell... var floatIndex = CGFloat(indexPath.section) cell.contentView.backgroundColor = UIColor(white: floatIndex/255, alpha: floatIndex*0.02) cell.backgroundColor = UIColor.clearColor() return cell } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.section { case 0: return 320 default: return 430 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if collectionView is FeaturedCollectionView { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionItem, forIndexPath: indexPath) as FeaturedCollectionViewCell cell.backgroundColor = getRandomColor() return cell } else { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionItem, forIndexPath: indexPath) as MagazineCollectionViewCell cell.title.text = "Magazine name" cell.subTitle.text = "January 2015" return cell } } //MARK: - UICollectionView Delegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { switch collectionView { case is FeaturedCollectionView: var collectionView = collectionView as FeaturedCollectionView println("Featured: \(collectionView.index) Item: \(indexPath.item)") default: var collectionView = collectionView as MagazineCollectionView println("Magazine: \(collectionView.index) Item: \(indexPath.item)") } } //MARK: - Random Golor func getRandomColor() -> UIColor { var randomRed:CGFloat = CGFloat(drand48()) var randomGreen:CGFloat = CGFloat(drand48()) var randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
164e2435a28d76b2f5381f45bd4c8826
37.179191
152
0.615746
6.161381
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
EnjoyUniversity/EnjoyUniversity/Classes/Tools/Extension/UITableView+Extension.swift
1
787
// // UITableView+Extension.swift // EnjoyUniversity // // Created by lip on 17/5/9. // Copyright © 2017年 lip. All rights reserved. // extension UITableView{ func showPlaceHolderView(){ let noneImage = UIImageView(image: UIImage(named: "eu_nothing")) noneImage.center.x = center.x noneImage.center.y = center.y - 64 addSubview(noneImage) } func removePlaceHolderView(){ for subview in subviews{ if let subview = subview as? UIImageView { if let image = subview.image{ if image == UIImage(named: "eu_nothing")!{ subview.removeFromSuperview() } } } } } }
mit
7f619c6338bb066986132789a8c6c0bb
22.757576
72
0.515306
4.666667
false
false
false
false
jdfergason/swift-toml
Sources/Toml/Toml.swift
1
12491
/* * Copyright 2016-2018 JD Fergason * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /** Error thrown when a TOML syntax error is encountered - DuplicateKey: Document contains a duplicate key - InvalidDateFormat: Date string is not a supported format - InvalidEscapeSequence: Unsupported escape sequence used in string - InvalidUnicodeCharacter: Non-existant unicode character specified - MixedArrayType: Array is composed of multiple types, members must all be the same type - SyntaxError: Document cannot be parsed due to a syntax error */ public enum TomlError: Error { case DuplicateKey(String) case InvalidDateFormat(String) case InvalidEscapeSequence(String) case InvalidUnicodeCharacter(Int) case MixedArrayType(String) case SyntaxError(String) } protocol SetValueProtocol { mutating func set(value: Any, for key: [String]) } /** Data parsed from a TOML document */ public class Toml: CustomStringConvertible, SetValueProtocol { private var data: [Path: Any] private(set) public var keyNames: Set<Path> private(set) public var prefixPath: Path? private(set) public var tableNames: Set<Path> public init() { data = [Path: Any]() keyNames = Set<Path>() tableNames = Set<Path>() } /** Read the specified TOML file from disk. - Parameter contentsOfFile: Path of file to read - Parameter encoding: Encoding of file - Throws: `TomlError.SyntaxError` if the file is invalid - Throws: `NSError` if the file does not exist - Returns: A dictionary with parsed results */ public convenience init(contentsOfFile path: String, encoding: String.Encoding = String.Encoding.utf8) throws { self.init() let source = try String(contentsOfFile: path, encoding: encoding) let parser = Parser(toml: self) try parser.parse(string: source) } /** Parse the string `withString` as TOML. - Parameter withString: A string with TOML document - Throws: `TomlError.SyntaxError` if the file is invalid - Returns: A dictionary with parsed results */ public convenience init(withString string: String) throws { self.init() let parser = Parser(toml: self) try parser.parse(string: string) } /** Create an empty Toml object with the specified prefix path - Parameter prefixPath: The path to prefix all tables with */ private convenience init(prefixPath: Path) { self.init() self.prefixPath = prefixPath } /** Set the value for the the given key path - Parameter key: Array of strings - Parameter value: Value to set */ public func set(value: Any, for key: [String]) { let path = Path(key) keyNames.insert(path) data[path] = value } /** Add a sub-table - Parameter key: Array of strings indicating table path */ public func setTable(key: [String]) { tableNames.insert(Path(key)) } /** Check if the TOML document contains the specified key. - Parameter key: Key path to check - Parameter includeTables: Include tables and inline tables in key path check - Returns: True if key exists; false otherwise */ public func hasKey(key: [String], includeTables: Bool = true) -> Bool { var keyExists = data[Path(key)] != nil if includeTables { keyExists = keyExists || hasTable(key) } return keyExists } /** Check if the TOML document contains the specified key. - Parameter key: Key path to check - Returns: True if key exists; false otherwise */ public func hasKey(_ key: String...) -> Bool { return hasKey(key: key) } /** Check if the TOML document contains the specified table. - Parameter key: Key path to check - Returns: True if table exists; false otherwise */ public func hasTable(_ key: [String]) -> Bool { return tableNames.contains(Path(key)) } /** Check if the TOML document contains the specified table. - Parameter key: Key path to check - Returns: True if key exists; false otherwise */ public func hasTable(_ key: String...) -> Bool { return hasTable(key) } /** Get an array of type T from the TOML document - Parameter path: Key path of array - Returns: An array of type [T] */ public func array<T>(_ path: [String]) -> [T]? { if let val = data[Path(path)] { return val as? [T] } return nil } /** Get an array of type T from the TOML document - Parameter path: Key path of array - Returns: An array of type [T] */ public func array<T>(_ path: String...) -> [T]? { return array(path) } /** Get a boolean value from the specified key path. - Parameter path: Key path of value - Returns: boolean value of key path */ public func bool(_ path: [String]) -> Bool? { return value(path) } /** Get a boolean value from the specified key path. - Parameter path: Key path of value - Returns: boolean value of key path */ public func bool(_ path: String...) -> Bool? { return value(path) } /** Get a date value from the specified key path. - Parameter path: Key path of value - Returns: date value of key path */ public func date(_ path: [String]) -> Date? { return value(path) } /** Get a date value from the specified key path. - Parameter path: Key path of value - Returns: date value of key path */ public func date(_ path: String...) -> Date? { return value(path) } /** Get a double value from the specified key path. - Parameter path: Key path of value - Returns: double value of key path */ public func double(_ path: [String]) -> Double? { return value(path) } /** Get a double value from the specified key path. - Parameter path: Key path of value - Returns: double value of key path */ public func double(_ path: String...) -> Double? { return double(path) } /** Get a int value from the specified key path. - Parameter path: Key path of value - Returns: int value of key path */ public func int(_ path: [String]) -> Int? { return value(path) } /** Get a int value from the specified key path. - Parameter path: Key path of value - Returns: int value of key path */ public func int(_ path: String...) -> Int? { return value(path) } /** Get a string value from the specified key path. - Parameter path: Key path of value - Returns: string value of key path */ public func string(_ path: [String]) -> String? { return value(path) } /** Get a string value from the specified key path. - Parameter path: Key path of value - Returns: string value of key path */ public func string(_ path: String...) -> String? { return value(path) } /** Get a dictionary of all tables 1-level down from the given key path. To get all tables at the root level call with no parameters. - Parameter parent: Root key path - Returns: Dictionary of key names and tables */ public func tables(_ parent: [String]) -> [String: Toml] { var result = [String: Toml]() for tableName in tableNames { var tableParent = tableName var myTableName = tableName if let tablePrefix = prefixPath { myTableName = tablePrefix + tableName } tableParent.components.removeLast() if parent == tableParent.components { // this is a table to include result[myTableName.components.map(quoted).joined(separator: ".")] = table(from: tableName.components) } } return result } /** Get a dictionary of all tables 1-level down from the given key path. To get all tables at the root level call with no parameters. - Parameter parent: Root key path - Returns: Dictionary of key names and tables */ public func tables(_ parent: String...) -> [String: Toml] { return tables(parent) } /** Return a TOML table that contains everything beneath the specified path. - Parameter from: Key path to create table from - Returns: `Toml` table of all keys beneath the specified path */ public func table(from path: [String]) -> Toml { var fullTablePrefix = Path(path) if let tablePrefix = prefixPath { fullTablePrefix = tablePrefix + Path(path) } let constructedTable = Toml(prefixPath: fullTablePrefix) // add values for keyName in keyNames { var keyArray = keyName.components if keyName.begins(with: path) { keyArray.removeSubrange(0..<path.count) constructedTable.set(value: self.value(keyName.components)!, for: keyArray) } } // add tables for tableName in tableNames { var tableArray = tableName.components if tableName.begins(with: path) { tableArray.removeSubrange(0..<path.count) if !tableArray.isEmpty { constructedTable.setTable(key: tableArray) } } } return constructedTable } /** Get a TOML table from the document - Parameter path: Key path of value - Returns: Table of name `path` */ public func table(_ path: String...) -> Toml? { return table(from: path) } /** Get a value of type T from the specified key path. - Parameter path: Key path of value - Returns: value of key path */ public func value<T>(_ path: [String]) -> T? { if let val = data[Path(path)] { return val as? T } return nil } /** Get a value of type T from the specified key path. - Parameter path: Key path of value - Returns: value of key path */ public func value<T>(_ path: String...) throws -> T? { return value(path) } /** Get the value specified by path as a string - Parameter path: Key path of value - Returns: value of key path as a string */ public func valueDescription(_ path: [String]) -> String? { if let check = data[Path(path)] { if let intVal = check as? Int { return String(describing: intVal) } else if let doubleVal = check as? Double { return String(describing: doubleVal) } else if let stringVal = check as? String { return "\"\(escape(string: stringVal))\"" } else if let boolVal = check as? Bool { return String(describing: boolVal) } else if let dateVal = check as? Date { return dateVal.rfc3339String() } else if let tableArray = check as? [Toml] { return serializeArrayOfTables(tables: tableArray) } return String(describing: check) } return nil } /** Get a string representation of the TOML document - Returns: String version of TOML document */ public var description: String { return serialize(toml: self) } }
apache-2.0
3d9c0e2899e2085b948dcc4d5d3f1c94
26.272926
117
0.588824
4.567093
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/RuleConfigurations/UnusedDeclarationConfiguration.swift
1
2116
private enum ConfigurationKey: String { case severity = "severity" case includePublicAndOpen = "include_public_and_open" case relatedUSRsToSkip = "related_usrs_to_skip" } struct UnusedDeclarationConfiguration: RuleConfiguration, Equatable { private(set) var includePublicAndOpen: Bool private(set) var severityConfiguration: SeverityConfiguration private(set) var relatedUSRsToSkip: Set<String> var consoleDescription: String { return "\(ConfigurationKey.severity.rawValue): \(severityConfiguration.severity.rawValue), " + "\(ConfigurationKey.includePublicAndOpen.rawValue): \(includePublicAndOpen), " + "\(ConfigurationKey.relatedUSRsToSkip.rawValue): \(relatedUSRsToSkip.sorted())" } init(severity: ViolationSeverity, includePublicAndOpen: Bool, relatedUSRsToSkip: Set<String>) { self.includePublicAndOpen = includePublicAndOpen self.severityConfiguration = SeverityConfiguration(severity) self.relatedUSRsToSkip = relatedUSRsToSkip } mutating func apply(configuration: Any) throws { guard let configDict = configuration as? [String: Any], configDict.isNotEmpty else { throw ConfigurationError.unknownConfiguration } for (string, value) in configDict { guard let key = ConfigurationKey(rawValue: string) else { throw ConfigurationError.unknownConfiguration } switch (key, value) { case (.severity, let stringValue as String): try severityConfiguration.apply(configuration: [key: stringValue]) case (.includePublicAndOpen, let boolValue as Bool): includePublicAndOpen = boolValue case (.relatedUSRsToSkip, let value): if let usrs = [String].array(of: value) { relatedUSRsToSkip.formUnion(usrs) } else { throw ConfigurationError.unknownConfiguration } default: throw ConfigurationError.unknownConfiguration } } } }
mit
e2a56179dbe5acf9f3661c406ce8b45a
42.183673
102
0.658318
5.329975
false
true
false
false
antonio081014/LeeCode-CodeBase
Swift/letter-combinations-of-a-phone-number.swift
2
1016
/** * Problem Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ * * */ class Solution { let dict = [ 1:["1"], 2:["a", "b", "c"], 3:["d", "e", "f"], 4:["g", "h", "i"], 5:["j", "k", "l"], 6:["m", "n", "o"], 7:["p", "q", "r", "s"], 8:["t", "u", "v"], 9:["w", "x", "y", "z"], 0:["0"] ] func letterCombinations(_ digits: String) -> [String] { return Array(comb(digits.characters.map({Int(String($0))!}))) } private func comb(_ digits: [Int]) -> Set<String> { var rSet = Set<String>() if digits.count == 0 { return rSet } if digits.count == 1 { rSet = Set<String>(dict[digits[0]]!) return rSet } let subSet = comb(Array(digits.dropFirst(1))) for c in dict[digits[0]]! { for s in subSet { rSet.insert(c + s) } } return rSet } }
mit
69253a69eb0af46262e1dd4f126be20f
23.780488
85
0.408465
3.298701
false
false
false
false
germc/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Models/Product.swift
2
2210
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit import Realm class Product: RLMObject { dynamic var id : NSString = "" dynamic var imageUrl : NSString = "" dynamic var price : Double = -1 dynamic var salePrice : Double = 0 dynamic var name : NSString = "" dynamic var type : NSString = "" dynamic var rev : NSString = "" dynamic var aisle : Int = 0 dynamic var departmentName : NSString = "" dynamic var departmentId : NSString = "" dynamic var proximity : NSString = "1" //far proximity initially dynamic var checkedOff : Bool = false /** Method to convert Realm object to a more primitive type, useful in transferring data to iOS extensions :returns: Dictionary of Product data */ func encodeToDictionary() -> Dictionary<String, AnyObject> { var encodedDictionary = Dictionary<String, AnyObject>() encodedDictionary["id"] = self.id encodedDictionary["imageUrl"] = self.imageUrl encodedDictionary["price"] = self.price encodedDictionary["salePrice"] = self.salePrice encodedDictionary["name"] = self.name encodedDictionary["type"] = self.type encodedDictionary["rev"] = self.rev encodedDictionary["aisle"] = self.aisle encodedDictionary["departmentName"] = self.departmentName encodedDictionary["departmentId"] = self.departmentId encodedDictionary["checkedOff"] = self.checkedOff return encodedDictionary } /** This method sets the imageUrl of the product. It first checks to see if the passed in parameter has "http" already in it. If it does it means the path is already a full imageUrl. Else if it doesn't have "http" then it calls MILWLHelper's createImageUrl method to create the full imageUrl of the product image. :param: path */ func determineImageUrl(path : NSString){ if(path.rangeOfString("http").location != NSNotFound){ self.imageUrl = path }else{ self.imageUrl = WLProcedureCaller.createImageUrl(path) } } }
epl-1.0
b2653ee07906031c7b223cc15883d5e4
33.515625
313
0.652784
4.865639
false
false
false
false
dbsystel/DBNetworkStack
Source/NetworkService.swift
1
5524
// // Copyright (C) 2017 DB Systel GmbH. // DB Systel GmbH; Jürgen-Ponto-Platz 1; D-60329 Frankfurt am Main; Germany; http://www.dbsystel.de/ // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation import Dispatch /** `NetworkService` provides access to remote resources. - seealso: `BasicNetworkService` - seealso: `NetworkServiceMock` */ public protocol NetworkService { /** Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. Execution happens on no specific queue. It dependes on the network access which queue is used. Once execution is finished either the completion block or the error block gets called. You decide on which queue these blocks get executed. **Example**: ```swift let networkService: NetworkService = // let resource: Resource<String> = // networkService.request(queue: .main, resource: resource, onCompletionWithResponse: { htmlText, response in print(htmlText, response) }, onError: { error in // Handle errors }) ``` - parameter queue: The `DispatchQueue` to execute the completion and error block on. - parameter resource: The resource you want to fetch. - parameter onCompletionWithResponse: Callback which gets called when fetching and transforming into model succeeds. - parameter onError: Callback which gets called when fetching or transforming fails. - returns: a running network task */ @discardableResult func request<Result>(queue: DispatchQueue, resource: Resource<Result>, onCompletionWithResponse: @escaping (Result, HTTPURLResponse) -> Void, onError: @escaping (NetworkError) -> Void) -> NetworkTask } public extension NetworkService { /** Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. Execution happens on no specific queue. It dependes on the network access which queue is used. Once execution is finished either the completion block or the error block gets called. These blocks are called on the main queue. **Example**: ```swift let networkService: NetworkService = // let resource: Resource<String> = // networkService.request(resource, onCompletion: { htmlText in print(htmlText) }, onError: { error in // Handle errors }) ``` - parameter resource: The resource you want to fetch. - parameter onComplition: Callback which gets called when fetching and transforming into model succeeds. - parameter onError: Callback which gets called when fetching or transforming fails. - returns: a running network task */ @discardableResult func request<Result>(_ resource: Resource<Result>, onCompletion: @escaping (Result) -> Void, onError: @escaping (NetworkError) -> Void) -> NetworkTask { return request(queue: .main, resource: resource, onCompletionWithResponse: { model, _ in onCompletion(model) }, onError: onError) } /** Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. Execution happens on no specific queue. It dependes on the network access which queue is used. Once execution is finished either the completion block or the error block gets called. These blocks are called on the main queue. **Example**: ```swift let networkService: NetworkService = // let resource: Resource<String> = // networkService.request(resource, onCompletionWithResponse: { htmlText, httpResponse in print(htmlText, httpResponse) }, onError: { error in // Handle errors }) ``` - parameter resource: The resource you want to fetch. - parameter onCompletion: Callback which gets called when fetching and transforming into model succeeds. - parameter onError: Callback which gets called when fetching or transforming fails. - returns: a running network task */ @discardableResult func request<Result>(_ resource: Resource<Result>, onCompletionWithResponse: @escaping (Result, HTTPURLResponse) -> Void, onError: @escaping (NetworkError) -> Void) -> NetworkTask { return request(queue: .main, resource: resource, onCompletionWithResponse: onCompletionWithResponse, onError: onError) } }
mit
8907e5b1ed5d4a9cb281e16495b9d739
43.540323
145
0.705414
4.980162
false
false
false
false
J-Mendes/Weather
Weather/Weather/Constants.swift
1
549
// // Constants.swift // Weather // // Created by Jorge Mendes on 06/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import Foundation class Constants { internal enum UnitsType: Int { case Imperial = 1, Metric } struct UserDefaultsKeys { static let location: String = "location" static let units: String = "units" } struct DefaultValues { static let defaultLocation: String = "Lisbon, PT" static let defaultUnit: Int = UnitsType.Metric.rawValue } }
gpl-3.0
8ca868697f0a13e728896f7b18555b88
19.296296
63
0.627737
4.120301
false
false
false
false
sovereignshare/fly-smuthe
Fly Smuthe/Fly Smuthe/QuickSettingsViewController.swift
1
5541
// // QuickSettingsViewController.swift // Fly Smuthe // // Created by Adam M Rivera on 9/7/15. // Copyright (c) 2015 Adam M Rivera. All rights reserved. // import Foundation import UIKit class QuickSettingsViewController : UIViewController { let standardUserDefaults = NSUserDefaults.standardUserDefaults(); var delegate: QuickSettingsViewControllerDelegate!; @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var includeInaccurateResultsToggle: UISwitch! @IBOutlet weak var lookbackSelector: UISegmentedControl! @IBOutlet weak var radiusSelector: UISegmentedControl! @IBOutlet weak var intervalSelector: UISegmentedControl! @IBAction func radiusChanged(sender: UISegmentedControl) { if let strongDelegate = delegate { switch sender.selectedSegmentIndex { case 0: //1 strongDelegate.radius = 1; break; case 1: //3 strongDelegate.radius = 3; break; case 2: //5 strongDelegate.radius = 5; break; case 3: //10 strongDelegate.radius = 10; break; default: strongDelegate.radius = 3; break; } } standardUserDefaults.setInteger(sender.selectedSegmentIndex, forKey: SettingsConstants.RadiusKey); standardUserDefaults.synchronize(); } @IBAction func lookbackChanged(sender: UISegmentedControl) { if let strongDelegate = delegate { switch sender.selectedSegmentIndex { case 0: //1 strongDelegate.hoursUntilStale = 1; break; case 1: //3 strongDelegate.hoursUntilStale = 3; break; case 2: //5 strongDelegate.hoursUntilStale = 5; break; case 3: //10 strongDelegate.hoursUntilStale = 10; break; default: strongDelegate.hoursUntilStale = 3; break; } } standardUserDefaults.setInteger(sender.selectedSegmentIndex, forKey: SettingsConstants.HoursUntilStaleKey); standardUserDefaults.synchronize(); } @IBAction func intervalChanged(sender: UISegmentedControl) { if let strongDelegate = delegate { switch sender.selectedSegmentIndex { case 0: //1 strongDelegate.intervalMin = 5; break; case 1: //3 strongDelegate.intervalMin = 10; break; case 2: //5 strongDelegate.intervalMin = 15; break; default: strongDelegate.intervalMin = 5; break; } } standardUserDefaults.setInteger(sender.selectedSegmentIndex, forKey: SettingsConstants.IntervalMinKey); standardUserDefaults.synchronize(); } @IBAction func includeInaccurateChanged(sender: UISwitch) { if let strongDelegate = delegate { strongDelegate.includeInaccurateResults = sender.on; } standardUserDefaults.setBool(sender.on, forKey: SettingsConstants.IncludeInaccurateResultsKey); standardUserDefaults.synchronize(); } override func viewDidLoad() { super.viewDidLoad(); if(standardUserDefaults.objectForKey(SettingsConstants.IncludeInaccurateResultsKey) == nil){ standardUserDefaults.setBool(true, forKey: SettingsConstants.IncludeInaccurateResultsKey); } if(standardUserDefaults.objectForKey(SettingsConstants.RadiusKey) == nil){ standardUserDefaults.setInteger(1, forKey: SettingsConstants.RadiusKey); } if(standardUserDefaults.objectForKey(SettingsConstants.HoursUntilStaleKey) == nil){ standardUserDefaults.setInteger(1, forKey: SettingsConstants.HoursUntilStaleKey); } if(standardUserDefaults.objectForKey(SettingsConstants.IntervalMinKey) == nil){ standardUserDefaults.setInteger(0, forKey: SettingsConstants.IntervalMinKey); } standardUserDefaults.synchronize(); includeInaccurateResultsToggle.on = standardUserDefaults.valueForKey(SettingsConstants.IncludeInaccurateResultsKey) as! Bool; includeInaccurateChanged(includeInaccurateResultsToggle); radiusSelector.selectedSegmentIndex = standardUserDefaults.valueForKey(SettingsConstants.RadiusKey) as! Int; radiusChanged(radiusSelector); lookbackSelector.selectedSegmentIndex = standardUserDefaults.valueForKey(SettingsConstants.HoursUntilStaleKey) as! Int; lookbackChanged(lookbackSelector); intervalSelector.selectedSegmentIndex = standardUserDefaults.valueForKey(SettingsConstants.IntervalMinKey) as! Int; intervalChanged(intervalSelector); } } protocol QuickSettingsViewControllerDelegate : class { var includeInaccurateResults: Bool { get set } var radius: Int { get set } var hoursUntilStale: Int { get set } var intervalMin: Int { get set } func settingsButtonPressed(); func settingsDismissed(); }
gpl-3.0
d32a1836de4efe2c825816e3853d7029
33.42236
133
0.610901
5.747925
false
false
false
false
arvedviehweger/swift
test/Constraints/diagnostics.swift
1
42829
// 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) { } 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, i) // expected-error{{extra argument in call}} // Position mismatch f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}} // 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.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type '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 {{type 'A' does not conform to protocol 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { return (c: 0, i: g()) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { return A() } 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) {} f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '(Int, Double) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}} // <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 {{argument type 'Int' does not conform to expected type '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{{unexpected non-void return value in void function}} } 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>( _ 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> // FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to // make sure that it doesn't crash. func rdar20142523() { myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}} () 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" if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}} } // <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 {{unexpected non-void return value in void function}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}} // expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} 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 {{'Int' is not convertible to 'Bool'}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{'Int' is not convertible to 'Bool'}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} } // <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 index of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{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> {} _ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{use of undeclared type 'Nail'}} 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 closure type 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'}} } // <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 } func f7(_ a: Int) -> (_ b: Int) -> Int { return { b in a+b } } _ = f7(1)(1) f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}} let f8 = f7(2) _ = f8(1) f8(10) // expected-warning {{result of call is unused, but produces 'Int'}} f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}} class CurriedClass { func method1() {} func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } } func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}} } let c = CurriedClass() _ = c.method1 c.method1(1) // expected-error {{argument passed to call that takes no arguments}} _ = c.method2(1) _ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1)(2) c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}} c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}} c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method1(c)() _ = CurriedClass.method1(c) CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}} CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}} _ = CurriedClass.method2(c) _ = CurriedClass.method2(c)(32) _ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}} CurriedClass.method3(c)(32, b: 1) _ = CurriedClass.method3(c) _ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }} _ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}} _ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}} CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}} extension CurriedClass { func f() { method3(1, b: 2) method3() // expected-error {{missing argument for parameter #1 in call}} method3(42) // expected-error {{missing argument for parameter 'b' in call}} method3(self) // expected-error {{missing argument for parameter 'b' in call}} } } extension CurriedClass { func m1(_ a : Int, b : Int) {} func m2(_ a : Int) {} } // <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} // <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} // <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 {} static func overload(b : Int) -> Color {} static func frob(_ a : Int, b : inout Int) -> Color {} } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }} 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' expects argument of type '(description: String)'}} let _: Color = .Unknown(42) // expected-error {{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' to specified type 'Int'}} let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; 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 {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{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 '&'}} let _: Color = .frob(1, &d) // expected-error {{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'}} 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), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}} //expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} } // <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 '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) {} } 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}} a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} } // <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; operands here have types '_' and '([Int]) -> Bool'}} } // <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}} {{7-7=(}} {{8-8= != nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{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.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2.1)// 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) _ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} } // 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 2 {{'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 {{'unavail' is unavailable: calling this is unwise}} } } // <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) {} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}} // expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}} 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)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}} } // <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?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}} 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: (Float), (Double)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}} } // <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 'CountableClosedRange<Int>' to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')}} _ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}} } // <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 {{extra argument in call}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}} // 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-warning {{deprecated}} a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}} b } 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 as inout argument: '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}} } func secondArgumentNotLabeled(a: Int, _ b: Int) { } secondArgumentNotLabeled(10, 20) // expected-error@-1 {{missing argument label 'a' in call}} // <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 {{argument labels '(_:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: 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) } } // <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 = withUnsafePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtractInPlace(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 {{unexpected non-void return value in void function}} } // 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 // <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try' struct rdar27891805 { init(contentsOf: String, encoding: String) throws {} init(contentsOf: String, usedEncoding: inout String) throws {} init<T>(_ t: T) {} } try rdar27891805(contentsOfURL: nil, usedEncoding: nil) // expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}} // expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}} // 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 this candidate}} func value(y: String) -> String {} // expected-note {{found this candidate}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}} } // SR-2242: poor diagnostic when argument label is omitted func r27212391(x: Int, _ y: Int) { let _: Int = x + y } func r27212391(a: Int, x: Int, _ y: Int) { let _: Int = a + x + y } r27212391(3, 5) // expected-error {{missing argument label 'x' in call}} r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}} r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}} r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}} r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}} r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}} r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} // SR-1255 func foo1255_1() { return true || false // expected-error {{unexpected non-void return value in void function}} } func foo1255_2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // SR-2505: "Call arguments did not match up" assertion // Here we're simulating the busted Swift 3 behavior -- see // test/Constraints/diagnostics_swift4.swift for the correct // behavior. func sr_2505(_ a: Any) {} // expected-note {{}} sr_2505() // expected-error {{missing argument for parameter #1 in call}} sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4 sr_2505(1, 2) // expected-error {{extra argument in call}} sr_2505(a: 1, 2) // expected-error {{extra argument in call}} struct C_2505 { init(_ arg: Any) { } } protocol P_2505 { } extension C_2505 { init<T>(from: [T]) where T: P_2505 { } } class C2_2505: P_2505 { } // FIXME: emit a warning saying this becomes an error in Swift 4 let c_2505 = C_2505(arg: [C2_2505()]) // 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 3 {{'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 {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} 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), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} 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), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} 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), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} 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), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
apache-2.0
5a33c5753ac1eae7b5cbd7fcdaa12164
44.953863
210
0.673165
3.623741
false
false
false
false
xedin/swift
test/DebugInfo/inlined-generics-basic.swift
7
5199
// SIL. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: -Xllvm -sil-print-debuginfo %s -g -O -o - -emit-sil \ // RUN: | %FileCheck %s --check-prefix=SIL // IR. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: %s -g -O -o - -emit-ir \ // RUN: | %FileCheck %s --check-prefix=IR import StdlibUnittest @inline(never) func yes() -> Bool { return true } #sourceLocation(file: "use.swift", line: 1) @inline(never) func use<V>(_ v: V) { _blackHole(v) } #sourceLocation(file: "h.swift", line: 1) @inline(__always) func h<U>(_ u: U) { yes() use(u) } #sourceLocation(file: "g.swift", line: 1) @inline(__always) func g<T>(_ t: T) { if (yes()) { h(t) } } // SIL: sil_scope [[F:.*]] { {{.*}}parent @$s1A1CC1fyyqd__lF // SIL: sil_scope [[F1:.*]] { loc "f.swift":1:28 parent [[F]] } // SIL: sil_scope [[F1G:.*]] { loc "f.swift":2:5 parent [[F1]] } // SIL: sil_scope [[F1G1:.*]] { loc "g.swift":2:3 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3:.*]] { loc "g.swift":3:5 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3H:.*]] { loc "h.swift":1:24 // SIL-SAME: parent @{{.*}}1h{{.*}} inlined_at [[F1G3]] } // SIL: sil_scope [[F1G3H1:.*]] { loc "h.swift":1:37 // SIL-SAME: parent [[F1G3H]] inlined_at [[F1G3]] } #sourceLocation(file: "C.swift", line: 1) public class C<R> { let r : R init(_ _r: R) { r = _r } // SIL: // C.f<A>(_:) // IR: define {{.*}} @"$s1A1CC1fyyqd__lF" #sourceLocation(file: "f.swift", line: 1) public func f<S>(_ s: S) { // SIL: debug_value_addr %0 : $*S, let, name "s", argno 1,{{.*}} scope [[F]] // SIL: function_ref {{.*}}yes{{.*}} scope [[F1G1]] // SIL: function_ref {{.*}}use{{.*}} scope [[F1G3H1]] // IR: dbg.value(metadata %swift.type* %S, metadata ![[MD_1_0:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[S:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_T:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 2) g(s) // IR: dbg.value({{.*}}, metadata ![[GR_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GR_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 3) g(r) // IR: dbg.value({{.*}}, metadata ![[GRS_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GRS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 4) g((r, s)) // IR: dbg.value // IR: dbg.value({{.*}}, metadata ![[GI_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GI_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 5) g(Int(0)) // IR: dbg.value // IR: dbg.value({{.*}}, metadata ![[GB_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GB_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 6) g(false) } } // IR: ![[BOOL:[0-9]+]] = !DICompositeType({{.*}}name: "Bool" // IR: ![[INT:[0-9]+]] = !DICompositeType({{.*}}name: "Int" // IR: ![[TAU_0_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sxD", // IR: ![[TAU_1_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sqd__D", // IR: ![[MD_1_0]] = !DILocalVariable(name: "$\CF\84_1_0" // IR: ![[S]] = !DILocalVariable(name: "s", {{.*}} type: ![[TAU_1_0]] // IR: ![[GS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GS_T:[0-9]+]], {{.*}} type: ![[TAU_1_0]]) // IR: ![[SP_GS_T]] = {{.*}}linkageName: "$s1A1gyyxlFqd___Ti5" // IR: ![[GS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GS_U:[0-9]+]], {{.*}} type: ![[TAU_1_0]]) // IR: ![[SP_GS_U]] = {{.*}}linkageName: "$s1A1hyyxlFqd___Ti5" // IR: ![[GR_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GR_T:[0-9]+]], {{.*}}type: ![[TAU_0_0]]) // S has the same generic parameter numbering s T and U. // IR: ![[SP_GR_T]] = {{.*}}linkageName: "$s1A1gyyxlF" // IR: ![[GR_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GR_U:[0-9]+]], {{.*}}type: ![[TAU_0_0]]) // IR: ![[SP_GR_U]] = {{.*}}linkageName: "$s1A1hyyxlF" // IR: ![[GRS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GRS_T:[0-9]+]], {{.*}}type: ![[TUPLE:[0-9]+]] // IR: ![[SP_GRS_T]] = {{.*}}linkageName: "$s1A1gyyxlFx_qd__t_Ti5" // IR: ![[TUPLE]] = {{.*}}DW_TAG_structure_type, name: "$sx_qd__tD" // IR: ![[GRS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GRS_U:[0-9]+]], {{.*}}type: ![[TUPLE]] // IR: ![[SP_GRS_U]] = {{.*}}linkageName: "$s1A1hyyxlFx_qd__t_Ti5" // IR-DAG: ![[GI_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GI_G:[0-9]+]], {{.*}}type: ![[INT]]) // IR-DAG: ![[SP_GI_G]] = {{.*}}linkageName: "$s1A1gyyxlFSi_Tg5" // IR-DAG: ![[GI_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GI_U:[0-9]+]], {{.*}}type: ![[INT]]) // IR-DAG: ![[SP_GI_U]] = {{.*}}linkageName: "$s1A1hyyxlFSi_TG5" // IR-DAG: ![[GB_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GB_G:[0-9]+]], {{.*}}type: ![[BOOL]]) // IR-DAG: ![[SP_GB_G]] = {{.*}}linkageName: "$s1A1gyyxlFSb_Tg5" // IR-DAG: ![[GB_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GB_U:[0-9]+]], {{.*}}type: ![[BOOL]]) // IR-DAG: ![[SP_GB_U]] = {{.*}}linkageName: "$s1A1hyyxlFSb_TG5"
apache-2.0
185d88e3d686cceb056aed89b115606a
45.419643
113
0.500481
2.6008
false
false
false
false
sheepy1/SelectionOfZhihu
SelectionOfZhihu/AnswerListViewController.swift
1
2024
// // AnswerListViewController.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/10. // Copyright © 2016年 Sheepy. All rights reserved. // import UIKit class AnswerListViewController: UITableViewController, Refreshable { let cellHeight = 150 as CGFloat var url: String! { didSet { getData() tableView.rowHeight = cellHeight refreshControl = simpleRefreshControl } } var answerList = [AnswerModel]() { didSet { tableView.reloadData() } } var cellCount = 0 func getData() { getDataFromUrl(url, method: .GET, parameter: nil) { data in if let d = data, jsonModel = d => AnswerListModel.self { self.cellCount = jsonModel.count self.answerList = jsonModel.answers.flatMap { $0 => AnswerModel.self } } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let articleController = segue.destinationViewController as? ArticleViewController, index = tableView.indexPathForSelectedRow?.row { let model = answerList[index] articleController.urlString = API.Article + model.questionid + "/answer/" + model.answerid } } } // MARK: - TableView Data Source extension AnswerListViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellCount } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(CellReuseIdentifier.Answer) as! AnswerCell let index = indexPath.row cell.bindModel((answerList[index], index)) return cell } }
mit
0a336285f20ece88cf4a005eed214343
27.013889
142
0.62122
5.225389
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Card/Detail/View/CardDetailRelatedCardsCell.swift
1
4471
// // CardDetailRelatedCardsCell.swift // DereGuide // // Created by zzk on 2017/6/26. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import TTGTagCollectionView protocol CardDetailRelatedCardsCellDelegate: class { func didClickRightDetail(_ cardDetailRelatedCardsCell: CardDetailRelatedCardsCell) } class CardDetailRelatedCardsCell: UITableViewCell { var leftLabel: UILabel! var rightLabel: UILabel! var collectionView: TTGTagCollectionView! var tagViews = NSCache<NSNumber, CGSSCardIconView>() weak var delegate: (CardDetailRelatedCardsCellDelegate & CGSSIconViewDelegate)? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel = UILabel() leftLabel.font = UIFont.systemFont(ofSize: 16) leftLabel.text = NSLocalizedString("角色所有卡片", comment: "卡片详情页") contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(10) } rightLabel = UILabel() rightLabel.text = NSLocalizedString("查看角色详情", comment: "卡片详情页") + " >" rightLabel.font = UIFont.systemFont(ofSize: 16) rightLabel.textColor = UIColor.lightGray let tap = UITapGestureRecognizer.init(target: self, action: #selector(handleTapGesture(_:))) rightLabel.addGestureRecognizer(tap) rightLabel.isUserInteractionEnabled = true contentView.addSubview(rightLabel) rightLabel.snp.makeConstraints { (make) in make.top.equalTo(10) make.right.equalTo(-10) } collectionView = TTGTagCollectionView() collectionView.contentInset = .zero collectionView.verticalSpacing = 5 collectionView.horizontalSpacing = 5 contentView.addSubview(collectionView) collectionView.dataSource = self collectionView.delegate = self collectionView.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(rightLabel.snp.bottom).offset(5) make.bottom.equalTo(-10) } selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func handleTapGesture(_ tap: UITapGestureRecognizer) { delegate?.didClickRightDetail(self) } var cards = [CGSSCard]() { didSet { collectionView.reload() } } override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { layoutIfNeeded() collectionView.invalidateIntrinsicContentSize() return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } } extension CardDetailRelatedCardsCell: TTGTagCollectionViewDelegate, TTGTagCollectionViewDataSource { func numberOfTags(in tagCollectionView: TTGTagCollectionView!) -> UInt { return UInt(cards.count) } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, tagViewFor index: UInt) -> UIView! { let icon: CGSSCardIconView if let view = tagViews.object(forKey: NSNumber.init(value: index)) { icon = view } else { icon = CGSSCardIconView() icon.isUserInteractionEnabled = false tagViews.setObject(icon, forKey: NSNumber.init(value: index)) } icon.cardID = cards[Int(index)].id return icon } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, sizeForTagAt index: UInt) -> CGSize { return CGSize(width: 48, height: 48) } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, didSelectTag tagView: UIView!, at index: UInt) { let icon = tagView as! CGSSCardIconView delegate?.iconClick(icon) } } extension CardDetailRelatedCardsCell: CardDetailSetable { func setup(with card: CGSSCard) { cards = CGSSDAO.shared.findCardsByCharId(card.charaId).sorted { $0.albumId > $1.albumId } } }
mit
b317af54d08d132b830d877167d6395f
34.392
193
0.673825
5.004525
false
false
false
false
roambotics/swift
test/Constraints/dynamic_lookup.swift
4
14824
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/PrivateObjC.swift -o %t // RUN: %target-typecheck-verify-swift -swift-version 4 -I %t -verify-ignore-unknown // RUN: %target-typecheck-verify-swift -swift-version 5 -I %t -verify-ignore-unknown // REQUIRES: objc_interop import Foundation import PrivateObjC @objc class A { init() {} } @objc class B : A { override init() { super.init() } } @objc class C { init() {} } class X { init() {} @objc func foo(_ i: Int) { } @objc func bar() { } @objc func ovl2() -> A { } // expected-note{{found this candidate}} @objc func ovl4() -> B { } @objc func ovl5() -> B { } // expected-note{{found this candidate}} @objc class func staticFoo(_ i : Int) { } @objc func prop3() -> Int { return 5 } } class Y : P { init() {} @objc func foo(_ s: String) { } @objc func wibble() { } // expected-note 2 {{did you mean 'wibble'?}} @objc func ovl1() -> A { } @objc func ovl4() -> B { } @objc func ovl5() -> C { } // expected-note{{found this candidate}} @objc var prop1 : Int { get { return 5 } } var _prop2 : String @objc var prop2 : String { get { return _prop2 } set(value) { _prop2 = value } } @objc var prop3 : Int { get { return 5 } } @objc subscript (idx : Int) -> String { get { return "hello" } set {} } } class Z : Y { @objc override func ovl1() -> B { } @objc func ovl2() -> C { } // expected-note{{found this candidate}} @objc(ovl3_A) func ovl3() -> A { } @objc func ovl3() -> B { } func generic4<T>(_ x : T) { } } @objc protocol P { func wibble() } @objc protocol P2 { func wonka() var protoProp : Int { get } static func staticWibble() subscript (idx : A) -> Int { get set } } struct S { func wobble() { } } class D<T> { func generic1(_ x : T) { } } extension Z { @objc func ext1() -> A { } } // Find methods via dynamic method lookup. typealias Id = AnyObject var obj : Id = X() obj.bar!() obj.foo!(5) obj.foo!("hello") obj.wibble!() obj.wobble!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}} obj.ext1!() // expected-warning {{result of call to function returning 'A' is unused}} obj.wonka!() // Same as above but without the '!' obj.bar() obj.foo(5) obj.foo("hello") obj.wibble() obj.wobble() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}} obj.ext1() // expected-warning {{result of call to function returning 'A' is unused}} obj.wonka() // Find class methods via dynamic method lookup. type(of: obj).staticFoo!(5) type(of: obj).staticWibble!() // Same as above but without the '!' type(of: obj).staticFoo(5) type(of: obj).staticWibble() // Overloading and ambiguity resolution // When we have overriding, pick the least restrictive declaration. var ovl1Result = obj.ovl1!() ovl1Result = A() // verify that we got an A, not a B // Same as above but without the '!' obj.ovl1() // expected-warning {{result of call to function returning 'A' is unused}} // Don't allow overload resolution between declarations from different // classes. var ovl2ResultA = obj.ovl2!() // expected-error{{ambiguous use of 'ovl2()'}} // ... but it's okay to allow overload resolution between declarations // from the same class. var ovl3Result = obj.ovl3!() ovl3Result = B() // For [objc] declarations, we can ignore declarations with the same // selector and type. var ovl4Result = obj.ovl4!() // ... but not when the types are different. var ovl5Result = obj.ovl5!() // expected-error{{ambiguous use of 'ovl5()'}} // Same as above but without the '!' obj.ovl4() // expected-warning {{result of call to function returning 'B' is unused}} // Generics // Dynamic lookup cannot find members of a generic class (or a class // that's a member of anything generic), because we wouldn't be able // to figure out the generic arguments. var generic1Result = obj.generic1!(17) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic1'}} obj.generic2!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic2'}} obj.generic3!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic3'}} // Dynamic method lookup can't find non-[objc] members obj.generic4!(5) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic4'}} // Find properties via dynamic lookup. var prop1Result : Int = obj.prop1! var prop2Result : String = obj.prop2! obj.prop2 = "hello" // expected-error{{cannot assign to property: 'obj' is immutable}} var protoPropResult : Int = obj.protoProp! // Find subscripts via dynamic lookup var sub1Result : String = obj[5]! var sub2Result : Int = obj[A()]! // Subscript then call without the '!' var sub1ResultNE = obj[5].hasPrefix("foo") var sub2ResultNE = obj[A()].hashValue // Property/function ambiguities. var prop3ResultA : Int? = obj.prop3 var prop3ResultB : (() -> Int)? = obj.prop3 var prop3ResultC = obj.prop3 let prop3ResultCChecked: Int? = prop3ResultC var obj2 : AnyObject & P = Y() class Z2 { } class Z3<T : AnyObject> { } class Z4<T> where T : AnyObject { } // Don't allow one to call instance methods on the Type via // dynamic method lookup. type(of: obj).foo!(obj)(5) // expected-error@-1 {{instance member 'foo' cannot be used on type 'Id' (aka 'AnyObject')}} // expected-error@-2 {{cannot force unwrap value of non-optional type '(Id) -> ((Int) -> ())?' (aka '(AnyObject) -> Optional<(Int) -> ()>')}} // expected-error@-3 {{value of optional type '((Int) -> ())?' must be unwrapped to a value of type '(Int) -> ()'}} // expected-note@-4 {{coalesce using '??'}} // expected-note@-5 {{force-unwrap using '!'}} // Checked casts to AnyObject var p: P = Y() var obj3 : AnyObject = (p as! AnyObject)! // expected-error{{cannot force unwrap value of non-optional type 'AnyObject'}} {{41-42=}} // expected-warning@-1{{forced cast from 'any P' to 'AnyObject' always succeeds; did you mean to use 'as'?}} {{27-30=as}} // Implicit force of an implicitly unwrapped optional let uopt : AnyObject! = nil uopt.wibble!() // Should not be able to see private or internal @objc methods. uopt.privateFoo!() // expected-error{{'privateFoo' is inaccessible due to 'private' protection level}} uopt.internalFoo!() // expected-error{{'internalFoo' is inaccessible due to 'internal' protection level}} let anyValue: Any = X() _ = anyValue.bar() // expected-error {{value of type 'Any' has no member 'bar'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}{{5-5=(}}{{13-13= as AnyObject)}} _ = (anyValue as AnyObject).bar() (anyValue as! X).bar() var anyDict: [String : Any] = Dictionary<String, Any>() anyDict["test"] = anyValue _ = anyDict["test"]!.bar() // expected-error {{value of type 'Any' has no member 'bar'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}{{5-5=(}}{{21-21= as AnyObject)}} // Test that overload resolution during constraint solving of values // looked-up dynamically through AnyObject are treated as conforming // to the protocols they are supposed to conform to. class NSObjDerived1 : NSObject { @objc var everything: [Any] = [] } class NSObjDerived2 : NSObject { var everything: Any = 1 } func rdar29960565(_ o: AnyObject) { for i in o.everything { _ = i } } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: 'privateFoo' declared here // <unknown>:0: error: unexpected note produced: 'internalFoo' declared here @objc protocol Q {} @objc class Dynamic : NSObject, Q { @objc var s: String = "" @objc func foo() -> String {} @objc subscript(_: String) -> String { get { return "hi" } set {} } } @objc class DynamicIUO : NSObject, Q { @objc var t: String! = "" @objc func baz() -> String! {} @objc subscript(_: DynamicIUO) -> DynamicIUO! { get { return self } set {} } } var dyn = Dynamic() var dyn_iuo = DynamicIUO() let s = "hi" var o: AnyObject = dyn let _: String = o.s let _: String = o.s! let _: String? = o.s let _: String = o.foo() let _: String = o.foo!() let _: String? = o.foo() let _: String = o[s] let _: String = o[s]! let _: String? = o[s] // FIXME: These should all produce lvalues that we can write through o.s = s // expected-error {{cannot assign to property: 'o' is immutable}} o.s! = s // expected-error {{cannot assign through '!': 'o' is immutable}} o[s] = s // expected-error {{cannot assign through subscript: 'o' is immutable}} o[s]! = s // expected-error {{cannot assign through '!': 'o' is immutable}} let _: String = o.t let _: String = o.t! let _: String = o.t!! let _: String? = o.t let _: String = o.baz() let _: String = o.baz!() let _: String = o.baz()! let _: String = o.baz!()! let _: String? = o.baz() let _: DynamicIUO = o[dyn_iuo] let _: DynamicIUO = o[dyn_iuo]! let _: DynamicIUO = o[dyn_iuo]!! let _: DynamicIUO? = o[dyn_iuo] // FIXME: These should all produce lvalues that we can write through o.t = s // expected-error {{cannot assign to property: 'o' is immutable}} o.t! = s // expected-error {{cannot assign through '!': 'o' is immutable}} o.t!! = s // expected-error {{cannot assign through '!': 'o' is immutable}} o[dyn_iuo] = dyn_iuo // expected-error {{cannot assign through subscript: 'o' is immutable}} o[dyn_iuo]! = dyn_iuo // expected-error {{cannot assign through '!': 'o' is immutable}} o[dyn_iuo]!! = dyn_iuo // expected-error {{cannot assign through '!': 'o' is immutable}} // Check that we avoid picking an unavailable overload if there's an // alternative. class OverloadedWithUnavailable1 { @objc func overloadedWithUnavailableA() { } @objc @available(swift, obsoleted: 3) func overloadedWithUnavailableB() { } } class OverloadedWithUnavailable2 { @available(swift, obsoleted: 3) @objc func overloadedWithUnavailableA() { } @objc func overloadedWithUnavailableB() { } } func testOverloadedWithUnavailable(ao: AnyObject) { ao.overloadedWithUnavailableA() ao.overloadedWithUnavailableB() } func dynamicInitCrash(ao: AnyObject.Type) { // This is going to produce difference results on macOS/iOS due to // different availability of `init(...)` overloads attached to `AnyObject` let sdk = ao.init(blahblah: ()) // expected-error@-1 {{}} } // Test that we correctly diagnose ambiguity for different typed members available // through dynamic lookup. @objc protocol P3 { var ambiguousProperty: String { get } // expected-note {{found this candidate}} var unambiguousProperty: Int { get } func ambiguousMethod() -> String // expected-note 2{{found this candidate}} func unambiguousMethod() -> Int func ambiguousMethodParam(_ x: String) // expected-note {{found this candidate}} func unambiguousMethodParam(_ x: Int) subscript(ambiguousSubscript _: Int) -> String { get } // expected-note {{found this candidate}} subscript(unambiguousSubscript _: String) -> Int { get } subscript(differentSelectors _: Int) -> Int { // expected-note {{found this candidate}} @objc(differentSelector1:) get } } class C1 { @objc var ambiguousProperty: Int { return 0 } // expected-note {{found this candidate}} @objc var unambiguousProperty: Int { return 0 } @objc func ambiguousMethod() -> Int { return 0 } // expected-note 2{{found this candidate}} @objc func unambiguousMethod() -> Int { return 0 } @objc func ambiguousMethodParam(_ x: Int) {} // expected-note {{found this candidate}} @objc func unambiguousMethodParam(_ x: Int) {} @objc subscript(ambiguousSubscript _: Int) -> Int { return 0 } // expected-note {{found this candidate}} @objc subscript(unambiguousSubscript _: String) -> Int { return 0 } @objc subscript(differentSelectors _: Int) -> Int { // expected-note {{found this candidate}} @objc(differentSelector2:) get { return 0 } } } class C2 { @objc subscript(singleCandidate _: Int) -> Int { return 0 } } func testAnyObjectAmbiguity(_ x: AnyObject) { _ = x.ambiguousProperty // expected-error {{ambiguous use of 'ambiguousProperty'}} _ = x.unambiguousProperty _ = x.ambiguousMethod() // expected-error {{ambiguous use of 'ambiguousMethod()'}} _ = x.unambiguousMethod() _ = x.ambiguousMethod // expected-error {{ambiguous use of 'ambiguousMethod()'}} _ = x.unambiguousMethod _ = x.ambiguousMethodParam // expected-error {{ambiguous use of 'ambiguousMethodParam'}} _ = x.unambiguousMethodParam // https://github.com/apple/swift/issues/55244 // Don't emit a single-element tuple error. _ = x[singleCandidate: 0] _ = x[ambiguousSubscript: 0] // expected-error {{ambiguous use of 'subscript(ambiguousSubscript:)'}} _ = x[ambiguousSubscript: 0] as Int _ = x[ambiguousSubscript: 0] as String // https://github.com/apple/swift/issues/51126 // Make sure we can coalesce subscripts with the same types and selectors // through AnyObject lookup. _ = x[unambiguousSubscript: ""] // But not if they have different selectors. _ = x[differentSelectors: 0] // expected-error {{ambiguous use of 'subscript(differentSelectors:)}} } // https://github.com/apple/swift/issues/54059 class HasMethodWithDefault { @objc func hasDefaultParam(_ x: Int = 0) {} } func testAnyObjectWithDefault(_ x: AnyObject) { x.hasDefaultParam() } /// https://github.com/apple/swift/issues/54241 /// Don't perform dynamic lookup for `callAsFunction`. class ClassWithObjcCallAsFunction { @objc func callAsFunction() {} } func testCallAsFunctionAnyObject(_ x: AnyObject) { x() // expected-error {{cannot call value of non-function type 'AnyObject'}} x.callAsFunction() // Okay. } // Note: In Swift >= 6 mode this would become an error. func test_dynamic_subscript_accepts_type_name_argument() { @objc class A { @objc subscript(a: A.Type) -> Int { get { 42 } } } func test(a: AnyObject, optA: AnyObject?) { let _ = a[A] // expected-warning {{expected member name or constructor call after type name}} // expected-note@-1 {{add arguments after the type to construct a value of the type}} {{16-16=()}} // expected-note@-2 {{use '.self' to reference the type object}} {{16-16=.self}} let _ = optA?[A] // expected-warning {{expected member name or constructor call after type name}} // expected-note@-1 {{add arguments after the type to construct a value of the type}} {{20-20=()}} // expected-note@-2 {{use '.self' to reference the type object}} {{20-20=.self}} } } func testAnyObjectConstruction(_ x: AnyObject) { AnyObject() // expected-error {{type 'AnyObject' cannot be instantiated}} // https://github.com/apple/swift/issues/57532 // FIXME: This should also be rejected. _ = type(of: x).init() }
apache-2.0
6bc648d90d781adb52bccacf95403d67
30.340381
155
0.665273
3.504492
false
false
false
false
LuckyResistor/FontToBytes
FontToBytes/ResultViewController.swift
1
1787
// // Lucky Resistor's Font to Byte // --------------------------------------------------------------------------- // (c)2015 by Lucky Resistor. See LICENSE for details. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // import Cocoa class ResultViewController: NSViewController { /// The text view /// @IBOutlet var textView: NSTextView! override func viewDidLoad() { super.viewDidLoad() // Copy the formatted text into the text view. let code = self.representedObject as! String var font = NSFont(name: "Menlo", size: 12.0) if font == nil { font = NSFont.systemFontOfSize(12.0) } let attributes: [String: AnyObject] = [NSFontAttributeName: font!] let text = NSMutableAttributedString(string: code, attributes: attributes) textView.textContainerInset = NSSize(width: 32.0, height: 32.0) textView.textStorage!.setAttributedString(text) } @IBAction func copyToPasteboard(sender: AnyObject) { textView.selectAll(self) textView.copy(self) } }
gpl-2.0
32492adfcc772c282520305a06872b73
32.716981
82
0.649133
4.740053
false
false
false
false
nathawes/swift
stdlib/public/core/VarArgs.swift
2
23407
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type whose instances can be encoded, and appropriately passed, as /// elements of a C `va_list`. /// /// You use this protocol to present a native Swift interface to a C "varargs" /// API. For example, a program can import a C API like the one defined here: /// /// ~~~c /// int c_api(int, va_list arguments) /// ~~~ /// /// To create a wrapper for the `c_api` function, write a function that takes /// `CVarArg` arguments, and then call the imported C function using the /// `withVaList(_:_:)` function: /// /// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int { /// return withVaList(arguments) { c_api(x, $0) } /// } /// /// Swift only imports C variadic functions that use a `va_list` for their /// arguments. C functions that use the `...` syntax for variadic arguments /// are not imported, and therefore can't be called using `CVarArg` arguments. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Note: Declaring conformance to the `CVarArg` protocol for types defined /// outside the standard library is not supported. public protocol CVarArg { // Note: the protocol is public, but its requirement is stdlib-private. // That's because there are APIs operating on CVarArg instances, but // defining conformances to CVarArg outside of the standard library is // not supported. /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. var _cVarArgEncoding: [Int] { get } } /// Floating point types need to be passed differently on x86_64 /// systems. CoreGraphics uses this to make CGFloat work properly. public // SPI(CoreGraphics) protocol _CVarArgPassedAsDouble: CVarArg {} /// Some types require alignment greater than Int on some architectures. public // SPI(CoreGraphics) protocol _CVarArgAligned: CVarArg { /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. var _cVarArgAlignment: Int { get } } #if !_runtime(_ObjC) /// Some pointers require an alternate object to be retained. The object /// that is returned will be used with _cVarArgEncoding and held until /// the closure is complete. This is required since autoreleased storage /// is not available on all platforms. public protocol _CVarArgObject: CVarArg { /// Returns the alternate object that should be encoded. var _cVarArgObject: CVarArg { get } } #endif #if arch(x86_64) @usableFromInline internal let _countGPRegisters = 6 // Note to future visitors concerning the following SSE register count. // // AMD64-ABI section 3.5.7 says -- as recently as v0.99.7, Nov 2014 -- to make // room in the va_list register-save area for 16 SSE registers (XMM0..15). This // may seem surprising, because the calling convention of that ABI only uses the // first 8 SSE registers for argument-passing; why save the other 8? // // According to a comment in X86_64ABIInfo::EmitVAArg, in clang's TargetInfo, // the AMD64-ABI spec is itself in error on this point ("NOTE: 304 is a typo"). // This comment (and calculation) in clang has been there since varargs support // was added in 2009, in rev be9eb093; so if you're about to change this value // from 8 to 16 based on reading the spec, probably the bug you're looking for // is elsewhere. @usableFromInline internal let _countFPRegisters = 8 @usableFromInline internal let _fpRegisterWords = 2 @usableFromInline internal let _registerSaveWords = _countGPRegisters + _countFPRegisters * _fpRegisterWords #elseif arch(s390x) @usableFromInline internal let _countGPRegisters = 16 @usableFromInline internal let _registerSaveWords = _countGPRegisters #elseif arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows)) // ARM Procedure Call Standard for aarch64. (IHI0055B) // The va_list type may refer to any parameter in a parameter list may be in one // of three memory locations depending on its type and position in the argument // list : // 1. GP register save area x0 - x7 // 2. 128-bit FP/SIMD register save area q0 - q7 // 3. Stack argument area @usableFromInline internal let _countGPRegisters = 8 @usableFromInline internal let _countFPRegisters = 8 @usableFromInline internal let _fpRegisterWords = 16 / MemoryLayout<Int>.size @usableFromInline internal let _registerSaveWords = _countGPRegisters + (_countFPRegisters * _fpRegisterWords) #endif #if arch(s390x) @usableFromInline internal typealias _VAUInt = CUnsignedLongLong @usableFromInline internal typealias _VAInt = Int64 #else @usableFromInline internal typealias _VAUInt = CUnsignedInt @usableFromInline internal typealias _VAInt = Int32 #endif /// Invokes the given closure with a C `va_list` argument derived from the /// given array of arguments. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withVaList(_:_:)`. Do not store or return the pointer for /// later use. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Parameters: /// - args: An array of arguments to convert to a C `va_list` pointer. /// - body: A closure with a `CVaListPointer` parameter that references the /// arguments passed as `args`. If `body` has a return value, that value /// is also used as the return value for the `withVaList(_:)` function. /// The pointer argument is valid only for the duration of the function's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // c-abi public func withVaList<R>(_ args: [CVarArg], _ body: (CVaListPointer) -> R) -> R { let builder = __VaListBuilder() for a in args { builder.append(a) } return _withVaList(builder, body) } /// Invoke `body` with a C `va_list` argument derived from `builder`. @inlinable // c-abi internal func _withVaList<R>( _ builder: __VaListBuilder, _ body: (CVaListPointer) -> R ) -> R { let result = body(builder.va_list()) _fixLifetime(builder) return result } #if _runtime(_ObjC) // Excluded due to use of dynamic casting and Builtin.autorelease, neither // of which correctly work without the ObjC Runtime right now. // See rdar://problem/18801510 /// Returns a `CVaListPointer` that is backed by autoreleased storage, built /// from the given array of arguments. /// /// You should prefer `withVaList(_:_:)` instead of this function. In some /// uses, such as in a `class` initializer, you may find that the language /// rules do not allow you to use `withVaList(_:_:)` as intended. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Parameter args: An array of arguments to convert to a C `va_list` /// pointer. /// - Returns: A pointer that can be used with C functions that take a /// `va_list` argument. @inlinable // c-abi public func getVaList(_ args: [CVarArg]) -> CVaListPointer { let builder = __VaListBuilder() for a in args { builder.append(a) } // FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one. Builtin.retain(builder) Builtin.autorelease(builder) return builder.va_list() } #endif @inlinable // c-abi public func _encodeBitsAsWords<T>(_ x: T) -> [Int] { let result = [Int]( repeating: 0, count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size) _internalInvariant(!result.isEmpty) var tmp = x // FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy. _memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!), src: UnsafeMutablePointer(Builtin.addressof(&tmp)), size: UInt(MemoryLayout<T>.size)) return result } // CVarArg conformances for the integer types. Everything smaller // than an Int32 must be promoted to Int32 or CUnsignedInt before // encoding. // Signed types extension Int: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension Bool: CVarArg { public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self ? 1:0)) } } extension Int64: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } extension Int32: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } extension Int16: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } extension Int8: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } // Unsigned types extension UInt: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UInt64: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } extension UInt32: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension UInt16: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension UInt8: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension OpaquePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UnsafePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UnsafeMutablePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } #if _runtime(_ObjC) extension AutoreleasingUnsafeMutablePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } #endif extension Float: _CVarArgPassedAsDouble, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(Double(self)) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: Double(self)) } } extension Double: _CVarArgPassedAsDouble, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) extension Float80: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // FIXME(sil-serialize-all) public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // FIXME(sil-serialize-all) public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } #endif #if (arch(x86_64) && !os(Windows)) || arch(s390x) || (arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))) /// An object that can manage the lifetime of storage backing a /// `CVaListPointer`. // NOTE: older runtimes called this _VaListBuilder. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. @_fixed_layout @usableFromInline // c-abi final internal class __VaListBuilder { #if arch(x86_64) || arch(s390x) @frozen // c-abi @usableFromInline internal struct Header { @inlinable // c-abi internal init() {} @usableFromInline // c-abi internal var gp_offset = CUnsignedInt(0) @usableFromInline // c-abi internal var fp_offset = CUnsignedInt(_countGPRegisters * MemoryLayout<Int>.stride) @usableFromInline // c-abi internal var overflow_arg_area: UnsafeMutablePointer<Int>? @usableFromInline // c-abi internal var reg_save_area: UnsafeMutablePointer<Int>? } #endif @usableFromInline // c-abi internal var gpRegistersUsed = 0 @usableFromInline // c-abi internal var fpRegistersUsed = 0 #if arch(x86_64) || arch(s390x) @usableFromInline // c-abi final // Property must be final since it is used by Builtin.addressof. internal var header = Header() #endif @usableFromInline // c-abi internal var storage: ContiguousArray<Int> #if !_runtime(_ObjC) @usableFromInline // c-abi internal var retainer = [CVarArg]() #endif @inlinable // c-abi internal init() { // prepare the register save area storage = ContiguousArray(repeating: 0, count: _registerSaveWords) } @inlinable // c-abi deinit {} @inlinable // c-abi internal func append(_ arg: CVarArg) { #if !_runtime(_ObjC) var arg = arg // We may need to retain an object that provides a pointer value. if let obj = arg as? _CVarArgObject { arg = obj._cVarArgObject retainer.append(arg) } #endif var encoded = arg._cVarArgEncoding #if arch(x86_64) || arch(arm64) let isDouble = arg is _CVarArgPassedAsDouble if isDouble && fpRegistersUsed < _countFPRegisters { #if arch(arm64) var startIndex = fpRegistersUsed * _fpRegisterWords #else var startIndex = _countGPRegisters + (fpRegistersUsed * _fpRegisterWords) #endif for w in encoded { storage[startIndex] = w startIndex += 1 } fpRegistersUsed += 1 } else if encoded.count == 1 && !isDouble && gpRegistersUsed < _countGPRegisters { #if arch(arm64) let startIndex = ( _fpRegisterWords * _countFPRegisters) + gpRegistersUsed #else let startIndex = gpRegistersUsed #endif storage[startIndex] = encoded[0] gpRegistersUsed += 1 } else { for w in encoded { storage.append(w) } } #elseif arch(s390x) if gpRegistersUsed < _countGPRegisters { for w in encoded { storage[gpRegistersUsed] = w gpRegistersUsed += 1 } } else { for w in encoded { storage.append(w) } } #endif } @inlinable // c-abi internal func va_list() -> CVaListPointer { #if arch(x86_64) || arch(s390x) header.reg_save_area = storage._baseAddress header.overflow_arg_area = storage._baseAddress + _registerSaveWords return CVaListPointer( _fromUnsafeMutablePointer: UnsafeMutableRawPointer( Builtin.addressof(&self.header))) #elseif arch(arm64) let vr_top = storage._baseAddress + (_fpRegisterWords * _countFPRegisters) let gr_top = vr_top + _countGPRegisters return CVaListPointer(__stack: gr_top, __gr_top: gr_top, __vr_top: vr_top, __gr_off: -64, __vr_off: -128) #endif } } #else /// An object that can manage the lifetime of storage backing a /// `CVaListPointer`. // NOTE: older runtimes called this _VaListBuilder. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. @_fixed_layout @usableFromInline // c-abi final internal class __VaListBuilder { @inlinable // c-abi internal init() {} @inlinable // c-abi internal func append(_ arg: CVarArg) { #if !_runtime(_ObjC) var arg = arg // We may need to retain an object that provides a pointer value. if let obj = arg as? _CVarArgObject { arg = obj._cVarArgObject retainer.append(arg) } #endif // Write alignment padding if necessary. // This is needed on architectures where the ABI alignment of some // supported vararg type is greater than the alignment of Int, such // as non-iOS ARM. Note that we can't use alignof because it // differs from ABI alignment on some architectures. #if arch(arm) && !os(iOS) if let arg = arg as? _CVarArgAligned { let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size let misalignmentInWords = count % alignmentInWords if misalignmentInWords != 0 { let paddingInWords = alignmentInWords - misalignmentInWords appendWords([Int](repeating: -1, count: paddingInWords)) } } #endif // Write the argument's value itself. appendWords(arg._cVarArgEncoding) } // NB: This function *cannot* be @inlinable because it expects to project // and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`. // Marking it inlinable will cause it to resiliently use accessors to // project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed // property. @usableFromInline // c-abi internal func va_list() -> CVaListPointer { // Use Builtin.addressof to emphasize that we are deliberately escaping this // pointer and assuming it is safe to do so. let emptyAddr = UnsafeMutablePointer<Int>( Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists)) return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr) } // Manage storage that is accessed as Words // but possibly more aligned than that. // FIXME: this should be packaged into a better storage type @inlinable // c-abi internal func appendWords(_ words: [Int]) { let newCount = count + words.count if newCount > allocated { let oldAllocated = allocated let oldStorage = storage let oldCount = count allocated = max(newCount, allocated * 2) let newStorage = allocStorage(wordCount: allocated) storage = newStorage // count is updated below if let allocatedOldStorage = oldStorage { newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount) deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage) } } let allocatedStorage = storage! for word in words { allocatedStorage[count] = word count += 1 } } @inlinable // c-abi internal func rawSizeAndAlignment( _ wordCount: Int ) -> (Builtin.Word, Builtin.Word) { return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue, requiredAlignmentInBytes._builtinWordValue) } @inlinable // c-abi internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> { let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount) let rawStorage = Builtin.allocRaw(rawSize, rawAlignment) return UnsafeMutablePointer<Int>(rawStorage) } @usableFromInline // c-abi internal func deallocStorage( wordCount: Int, storage: UnsafeMutablePointer<Int> ) { let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount) Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment) } @inlinable // c-abi deinit { if let allocatedStorage = storage { deallocStorage(wordCount: allocated, storage: allocatedStorage) } } // FIXME: alignof differs from the ABI alignment on some architectures @usableFromInline // c-abi internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment @usableFromInline // c-abi internal var count = 0 @usableFromInline // c-abi internal var allocated = 0 @usableFromInline // c-abi internal var storage: UnsafeMutablePointer<Int>? #if !_runtime(_ObjC) @usableFromInline // c-abi internal var retainer = [CVarArg]() #endif internal static var alignedStorageForEmptyVaLists: Double = 0 } #endif
apache-2.0
56c3b737082f997ff2175c4df3d9de3c
31.875
135
0.691332
4.100736
false
false
false
false
sleifer/SKLBits
bits/FocusedTouchWindow.swift
1
2024
// // FocusedTouchWindow.swift // SKLBits // // Created by Simeon Leifer on 10/18/16. // Copyright © 2016 droolingcat.com. All rights reserved. // #if os(iOS) import UIKit public class FocusedTouchWindow: UIWindow { private var touchableView: UIView? private var focusMissHandler: ((Void) -> (Void))? public func focusTouch(to view: UIView, missHandler: @escaping (Void) -> (Void)) { self.touchableView = view self.focusMissHandler = missHandler } public func unfocusTouch() { self.touchableView = nil self.focusMissHandler = nil } override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let nominalView = super.hitTest(point, with: event) if let touchableView = touchableView, let nominalView = nominalView { if touchableView.isParent(of: nominalView) { return nominalView } else { return self } } return nominalView } func haveLiveTouches(_ touches: Set<UITouch>) -> Bool { for oneTouch in touches { if oneTouch.view == nil || touchableView?.isParent(of: oneTouch.view!) == false { if oneTouch.phase != .ended && oneTouch.phase != .cancelled { return true } } } return false } func processTouches(_ touches: Set<UITouch>) { if let focusMissHandler = focusMissHandler, touchableView != nil, haveLiveTouches(touches) == true { focusMissHandler() } } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let ours = event?.touches(for: self) { processTouches(ours) } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let ours = event?.touches(for: self) { processTouches(ours) } } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let ours = event?.touches(for: self) { processTouches(ours) } } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if let ours = event?.touches(for: self) { processTouches(ours) } } } #endif
mit
44626023f4786f2e6e30168cc63252cc
22.8
102
0.687593
3.321839
false
false
false
false
hmily-xinxiang/BBSwiftFramework
BBSwiftFramework/Service/Network/BBHTTPExcutor.swift
1
7832
// // BBHTTPExcutor.swift // BBSwiftFramework // // Created by Bei Wang on 10/22/15. // Copyright © 2015 BooYah. All rights reserved. // import UIKit typealias HTTPCallback = (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void // HTTP回调 struct File { let name: String! let url: NSURL! init(name: String, url: NSURL) { self.name = name self.url = url } } class BBHTTPExcutor: NSObject, NSURLSessionDelegate { let boundary = "PitayaUGl0YXlh" let method: String! let params: Dictionary<String, AnyObject> let callback: HTTPCallback var files: Array<File> var session: NSURLSession! let url: String! var request: NSMutableURLRequest! var task: NSURLSessionTask! var localCerData: NSData! var sslValidateErrorCallBack: (() -> Void)? // MARK: - --------------------System-------------------- init(url: String, method: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), files: Array<File> = Array<File>(), callback: HTTPCallback) { self.url = url self.request = NSMutableURLRequest(URL: NSURL(string: url)!) self.method = method self.params = params self.callback = callback self.files = files self.localCerData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("BBServiceTest", ofType: "cer")!)! super.init() self.session = NSURLSession(configuration: NSURLSession.sharedSession().configuration, delegate: self, delegateQueue: NSURLSession.sharedSession().delegateQueue) } // MARK: - --------------------功能函数-------------------- private func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return (components.map{"\($0)=\($1)"} as [String]).joinWithSeparator("&") } private func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.appendContentsOf([(escape(key), escape("\(value)"))]) } return components } private func escape(string: String) -> String { // let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" // return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String return string.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! } func addSSLPinning(SSLValidateErrorCallBack: (()->Void)? = nil) { self.sslValidateErrorCallBack = SSLValidateErrorCallBack } // MARK: - --------------------代理方法-------------------- // MARK: - NSURLSessionDelegate @objc func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if let localCertificateData = self.localCerData { if let serverTrust = challenge.protectionSpace.serverTrust, certificate = SecTrustGetCertificateAtIndex(serverTrust, 0), remoteCertificateData: NSData = SecCertificateCopyData(certificate) { if localCertificateData.isEqualToData(remoteCertificateData) { let credential = NSURLCredential(forTrust: serverTrust) challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge) completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential) } else { challenge.sender?.cancelAuthenticationChallenge(challenge) completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil) self.sslValidateErrorCallBack?() } } else { debugPrint("Get RemoteCertificateData or LocalCertificateData error!") } } else { completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, nil) } } // MARK: - --------------------属性相关-------------------- private func fireTask() { self.addSSLPinning() { () -> Void in debugPrint("SSL证书错误,遭受中间人攻击!") } task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let _ = error { NSLog(error!.description) } else { debugPrint("服务发送HTTP请求或是发送HTTPS请求验证证书正确!") } self.callback(data: data, response: response, error: error) }) task.resume() } private func configHTTPHeader() { if self.method == BBServiceConfig().kHTTP_GET && !self.params.isEmpty { self.request = NSMutableURLRequest(URL: NSURL(string: url + "?" + buildParams(self.params))!) } request.HTTPMethod = self.method if !self.files.isEmpty { request.addValue("multipart/form-data; boundary=" + self.boundary, forHTTPHeaderField: "Content-Type") } else if !self.params.isEmpty { request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } } private func configHTTPBody() { let data = NSMutableData() if !self.files.isEmpty { if self.method == BBServiceConfig().kHTTP_GET { log.info("The remote server may not accept GET method with HTTP body. But Pitaya will send it anyway.") } for (key, value) in self.params { data.appendData("--\(self.boundary)\r\n".encodingdata) data.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".encodingdata) data.appendData("\(value.description)\r\n".encodingdata) } for file in self.files { data.appendData("--\(self.boundary)\r\n".encodingdata) data.appendData("Content-Disposition: form-data; name=\"\(file.name)\"; filename=\"\(NSString(string: file.url.description).lastPathComponent)\"\r\n\r\n".encodingdata) if let a = NSData(contentsOfURL: file.url) { data.appendData(a) data.appendData("\r\n".encodingdata) } } data.appendData("--\(self.boundary)--\r\n".encodingdata) } else if !self.params.isEmpty && self.method != BBServiceConfig().kHTTP_GET { data.appendData(buildParams(self.params).encodingdata) } request.HTTPBody = data } // MARK: - --------------------接口API-------------------- // MARK: 分块内接口函数注释 func fire() { configHTTPHeader() configHTTPBody() fireTask() } }
mit
24a41d1e27a59e554c3e87b13dddf634
38.372449
196
0.579629
5.107214
false
false
false
false
piscoTech/Workout
Workout Core/Model/Workout/Additional Data/WorkoutRoute.swift
1
6679
// // WorkoutRoute.swift // Workout Core // // Created by Marco Boschi on 20/12/2019. // Copyright © 2019 Marco Boschi. All rights reserved. // import UIKit import HealthKit import MBLibrary import MapKit @available(iOS 11.0, *) public class WorkoutRoute: NSObject, AdditionalDataExtractor, AdditionalDataProvider, MKMapViewDelegate { private static let routePadding: CGFloat = 20 private weak var preferences: Preferences? private(set) weak var owner: Workout? private var route: [[CLLocation]]? { didSet { if route == nil { routeBounds = nil routeSegments = nil routeStart = nil routeEnd = nil } } } private var routeBounds: MKMapRect? private var routeSegments: [MKPolyline]? private var routeStart: MKPointAnnotation? private var routeEnd: MKPointAnnotation? init(with preferences: Preferences) { self.preferences = preferences } // MARK: - Extract Data func set(workout: Workout) { owner = workout } func extract(from healthStore: HKHealthStore, completion: @escaping (Bool) -> Void) { guard let raw = owner?.raw else { route = nil completion(false) return } let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let filter = HKQuery.predicateForObjects(from: raw) let routeQuery = HKSampleQuery(sampleType: HKSeriesType.workoutRoute(), predicate: filter, limit: 1, sortDescriptors: [sortDescriptor]) { (_, r, err) in guard let route = r?.first as? HKWorkoutRoute else { self.route = nil // If no result is returned it's fine, the workout simply has no route attached completion(r?.isEmpty ?? false) return } var positions: [CLLocation] = [] let locQuery = HKWorkoutRouteQuery(route: route) { (q, loc, isDone, _) in guard let locations = loc else { self.route = nil completion(false) healthStore.stop(q) return } positions.append(contentsOf: locations) if isDone { self.route = [] self.routeSegments = [] self.routeBounds = nil // Isolate positions on active intervals for i in raw.activeSegments { let startPos = positions.lastIndex { $0.timestamp <= i.start } ?? 0 var track = positions.suffix(from: startPos) if let afterEndPos = track.firstIndex(where: { $0.timestamp > i.end }) { track = track.prefix(upTo: afterEndPos) } // Trim the start to exclude samples assigned to the previous segment if let prev = self.route?.last?.last, let newSample = track.firstIndex(where: { $0.timestamp > prev.timestamp }) { track = track.suffix(from: newSample) } if !track.isEmpty { let pl = MKPolyline(coordinates: track.map { $0.coordinate }, count: track.count) let bounds = pl.boundingMapRect self.routeBounds = self.routeBounds?.union(bounds) ?? bounds self.route?.append(Array(track)) self.routeSegments?.append(pl) } } if self.route?.isEmpty ?? true { self.route = nil } else { if let s = self.route?.first?.first { self.routeStart = MKPointAnnotation() self.routeStart?.coordinate = s.coordinate self.routeStart?.title = NSLocalizedString("WRKT_ROUTE_START", comment: "Start") } if let e = self.route?.last?.last { self.routeEnd = MKPointAnnotation() self.routeEnd?.coordinate = e.coordinate self.routeEnd?.title = NSLocalizedString("WRKT_ROUTE_END", comment: "End") } } completion(true) } } healthStore.execute(locQuery) } healthStore.execute(routeQuery) } // MARK: - Display Data public let sectionHeader: String? = NSLocalizedString("WRKT_ROUTE_TITLE", comment: "Route") public let sectionFooter: String? = nil public var numberOfRows: Int { route != nil ? 1 : 0 } public func heightForRowAt(_: IndexPath, in _: UITableView) -> CGFloat? { return UITableView.automaticDimension } public func cellForRowAt(_ indexPath: IndexPath, for tableView: UITableView) -> UITableViewCell { guard let routeBounds = self.routeBounds, let routeSegments = self.routeSegments else { fatalError("The cell should not be displayed when no route is available") } let c = tableView.dequeueReusableCell(withIdentifier: "map", for: indexPath) as! WorkoutRouteTVCell c.mapView.removeOverlays(c.mapView.overlays) c.mapView.removeAnnotations(c.mapView.annotations) c.mapView.delegate = self c.mapView.addOverlays(routeSegments, level: .aboveRoads) if let s = self.routeStart { c.mapView.addAnnotation(s) } if let e = self.routeEnd { c.mapView.addAnnotation(e) } DispatchQueue.main.async { // Let the cell be added to the table before moving the map c.mapView.setVisibleMapRect(routeBounds, edgePadding: UIEdgeInsets(top: Self.routePadding * 2, left: Self.routePadding, bottom: Self.routePadding, right: Self.routePadding), animated: false) } return c } public func export(for preferences: Preferences, withPrefix prefix: String, _ callback: @escaping ([URL]?) -> Void) { guard prefix.range(of: "/") == nil else { fatalError("Prefix must not contain '/'") } guard let route = self.route else { callback([]) return } guard let owner = self.owner else { callback(nil) return } DispatchQueue.background.async { let exporter: WorkoutRouteExporter.Type switch preferences.routeType { case .csv: exporter = CSVWorkoutRouteExporter.self case .gpx: exporter = GPXWorkoutRouteExporter.self } if let file = exporter.init(for: owner).export(route, withPrefix: prefix) { callback([file]) } else { callback(nil) } } } // MARK: - Map Delegate public func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolyline { let polylineRenderer = MKPolylineRenderer(overlay: overlay) polylineRenderer.strokeColor = #colorLiteral(red: 0.7807273327, green: 0, blue: 0.1517053111, alpha: 1) polylineRenderer.lineWidth = 6.0 return polylineRenderer } return MKPolylineRenderer() } public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var view: MKMarkerAnnotationView? if let start = routeStart, start === annotation { let ann = MKMarkerAnnotationView() ann.markerTintColor = MKPinAnnotationView.greenPinColor() view = ann } if let end = routeEnd, end === annotation { let ann = MKMarkerAnnotationView() ann.markerTintColor = MKPinAnnotationView.redPinColor() view = ann } view?.titleVisibility = .adaptive return view } }
mit
ad68e842bf1bf3171722f0a1cf3e3fdd
27.058824
154
0.684037
3.749579
false
false
false
false
practicalswift/swift
stdlib/public/core/BidirectionalCollection.swift
13
15540
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A collection that supports backward as well as forward traversal. /// /// Bidirectional collections offer traversal backward from any valid index, /// not including a collection's `startIndex`. Bidirectional collections can /// therefore offer additional operations, such as a `last` property that /// provides efficient access to the last element and a `reversed()` method /// that presents the elements in reverse order. In addition, bidirectional /// collections have more efficient implementations of some sequence and /// collection methods, such as `suffix(_:)`. /// /// Conforming to the BidirectionalCollection Protocol /// ================================================== /// /// To add `BidirectionalProtocol` conformance to your custom types, implement /// the `index(before:)` method in addition to the requirements of the /// `Collection` protocol. /// /// Indices that are moved forward and backward in a bidirectional collection /// move by the same amount in each direction. That is, for any index `i` into /// a bidirectional collection `c`: /// /// - If `i >= c.startIndex && i < c.endIndex`, /// `c.index(before: c.index(after: i)) == i`. /// - If `i > c.startIndex && i <= c.endIndex` /// `c.index(after: c.index(before: i)) == i`. public protocol BidirectionalCollection: Collection where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection { // FIXME: Only needed for associated type inference. override associatedtype Element override associatedtype Index override associatedtype SubSequence override associatedtype Indices /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. override func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. override func formIndex(after i: inout Index) /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the /// resulting distance. @_nonoverride func distance(from start: Index, to end: Index) -> Int /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) override var indices: Indices { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) override subscript(bounds: Range<Index>) -> SubSequence { get } // FIXME: Only needed for associated type inference. @_borrowed override subscript(position: Index) -> Element { get } override var startIndex: Index { get } override var endIndex: Index { get } } /// Default implementation for bidirectional collections. extension BidirectionalCollection { @inlinable // protocol-only @inline(__always) public func formIndex(before i: inout Index) { i = index(before: i) } @inlinable // protocol-only public func index(_ i: Index, offsetBy distance: Int) -> Index { return _index(i, offsetBy: distance) } @inlinable // protocol-only internal func _index(_ i: Index, offsetBy distance: Int) -> Index { if distance >= 0 { return _advanceForward(i, by: distance) } var i = i for _ in stride(from: 0, to: distance, by: -1) { formIndex(before: &i) } return i } @inlinable // protocol-only public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { return _index(i, offsetBy: distance, limitedBy: limit) } @inlinable // protocol-only internal func _index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { if distance >= 0 { return _advanceForward(i, by: distance, limitedBy: limit) } var i = i for _ in stride(from: 0, to: distance, by: -1) { if i == limit { return nil } formIndex(before: &i) } return i } @inlinable // protocol-only public func distance(from start: Index, to end: Index) -> Int { return _distance(from: start, to: end) } @inlinable // protocol-only internal func _distance(from start: Index, to end: Index) -> Int { var start = start var count = 0 if start < end { while start != end { count += 1 formIndex(after: &start) } } else if start > end { while start != end { count -= 1 formIndex(before: &start) } } return count } } extension BidirectionalCollection where SubSequence == Self { /// Removes and returns the last element of the collection. /// /// You can use `popLast()` to remove the last element of a collection that /// might be empty. The `removeLast()` method must be used only on a /// nonempty collection. /// /// - Returns: The last element of the collection if the collection has one /// or more elements; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable // protocol-only public mutating func popLast() -> Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. To remove the last element of a /// collection that might be empty, use the `popLast()` method instead. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @inlinable // protocol-only @discardableResult public mutating func removeLast() -> Element { let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes the given number of elements from the end of the collection. /// /// - Parameter k: The number of elements to remove. `k` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to remove. @inlinable // protocol-only public mutating func removeLast(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") _precondition(count >= k, "Can't remove more items from a collection than it contains") self = self[startIndex..<index(endIndex, offsetBy: -k)] } } extension BidirectionalCollection { /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop off the end of the /// collection. `k` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off `k` elements from the end. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to drop. @inlinable // protocol-only public __consuming func dropLast(_ k: Int) -> SubSequence { _precondition( k >= 0, "Can't drop a negative number of elements from a collection") let end = index( endIndex, offsetBy: -k, limitedBy: startIndex) ?? startIndex return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains the entire collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is equal to /// `maxLength`. @inlinable // protocol-only public __consuming func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = index( endIndex, offsetBy: -maxLength, limitedBy: startIndex) ?? startIndex return self[start..<endIndex] } }
apache-2.0
bade963a92225b9e6bf34a7f4f879890
36.536232
80
0.637709
4.192069
false
false
false
false
studyYF/Weibo-swift-
WeiBo/WeiBo/CLasses/Home(首页)/HomeCell/PictureCollectionView.swift
1
1417
// // PictureCollectionView.swift // Weibo // // Created by YF on 16/10/5. // Copyright © 2016年 YF. All rights reserved. // import UIKit class PictureCollectionView: UICollectionView { //MARK: - 定义属性 var pictureURLs : [NSURL] = [NSURL]() { didSet { self.reloadData() } } override func awakeFromNib() { dataSource = self } } //MARK: - collectionView的数据源 extension PictureCollectionView : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pictureURLs.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath) as! PictureCollectionViewCell cell.picUrl = pictureURLs[indexPath.item] return cell } } class PictureCollectionViewCell : UICollectionViewCell { //MARK: - 定义属性 var picUrl : NSURL? { didSet { guard let picUrl = picUrl else { return } picImgv.sd_setImageWithURL(picUrl, placeholderImage: UIImage(named: "empty_picture")) } } //MARK: - 控件属性 @IBOutlet weak var picImgv: UIImageView! }
apache-2.0
96411cdb122873905bd4952880254ad7
24.127273
142
0.650507
5.099631
false
false
false
false
Jnosh/swift
test/SourceKit/DocSupport/Inputs/main.swift
70
2007
var globV: Int class CC0 { var x: Int = 0 } class CC { var instV: CC0 func meth() {} func instanceFunc0(_ a: Int, b: Float) -> Int { return 0 } func instanceFunc1(a x: Int, b y: Float) -> Int { return 0 } class func smeth() {} init() { instV = CC0() } } func +(a : CC, b: CC0) -> CC { return a } struct S { func meth() {} static func smeth() {} } enum E { case EElem } protocol Prot { func protMeth(_ a: Prot) } func foo(_ a: CC, b: E) { var b = b _ = b globV = 0 _ = a + a.instV a.meth() CC.smeth() b = E.EElem var _: CC class LocalCC {} var _: LocalCC } typealias CCAlias = CC extension CC : Prot { func meth2(_ x: CCAlias) {} func protMeth(_ a: Prot) {} var extV : Int { return 0 } } class SubCC : CC {} var globV2: SubCC class ComputedProperty { var value : Int { get { let result = 0 return result } set(newVal) { // completely ignore it! } } var readOnly : Int { return 0 } } class BC2 { func protMeth(_ a: Prot) {} } class SubC2 : BC2, Prot { override func protMeth(_ a: Prot) {} } class CC2 { subscript (i : Int) -> Int { get { return i } set(vvv) { _ = vvv+1 } } } func test1(_ cp: ComputedProperty, sub: CC2) { var x = cp.value x = cp.readOnly cp.value = x cp.value += 1 x = sub[0] sub[0] = x sub[0] += 1 } struct S2 { func sfoo() {} } var globReadOnly : S2 { get { return S2(); } } func test2() { globReadOnly.sfoo() } class B1 { func foo() {} } class SB1 : B1 { override func foo() { foo() self.foo() super.foo() } } func test3(_ c: SB1, s: S2) { test2() c.foo() s.sfoo() } func test4(_ a: inout Int) {} protocol Prot2 { associatedtype Element var p : Int { get } func foo() } struct S1 : Prot2 { typealias Element = Int var p : Int = 0 func foo() {} } func genfoo<T : Prot2>(_ x: T) where T.Element == Int {} protocol Prot3 { static func +(x: Self, y: Self) }
apache-2.0
237f313c605163db1f5c24e83612af09
11.948387
56
0.536124
2.745554
false
false
false
false
norio-nomura/RxSwift
RxSwift/Disposable/CompositeDisposable.swift
1
6086
// // CompositeDisposable.swift // RxSwift // // Created by 野村 憲男 on 4/14/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation public final class CompositeDisposable: ICancelable { // MARK: ICancelable public func dispose() { var currentDisposables: Set<DisposableOf>? = nil spinLock.wait { if !isDisposed { isDisposed = true currentDisposables = disposables disposables.removeAll(keepCapacity: false) } } if let currentDisposables = currentDisposables { for disposable in currentDisposables { disposable.dispose() } } } public private(set) var isDisposed = false // MARK: internal public init() { } public init(_ disposables: IDisposable...) { // spinlock is not needed in init() because another referrer does not exist self.disposables.unionInPlace(map(disposables) {DisposableOf($0)} ) } // MARK: Subset of ExtensibleCollectionType /// Append `x` to `self`. /// /// Applying `successor()` to the index of the new element yields /// `self.endIndex`. /// /// Complexity: amortized O(1). public func append(x: IDisposable) { var shouldDispose = false spinLock.wait { shouldDispose = isDisposed if !shouldDispose { disposables.insert(DisposableOf(x)) } } if shouldDispose { x.dispose() } } /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) /// /// A possible implementation:: /// /// reserveCapacity(count(self) + underestimateCount(newElements)) /// for x in newElements { /// self.append(x) /// } public func extend<S : SequenceType where S.Generator.Element == IDisposable>(newElements: S) { var shouldDispose = false spinLock.wait { shouldDispose = isDisposed if !shouldDispose { disposables.unionInPlace(map(newElements) {DisposableOf($0)}) } } if shouldDispose { for x in newElements { x.dispose() } } } // MARK: Subset of Set /// Returns `true` if the set contains a member. public func contains(disposable: IDisposable) -> Bool { return spinLock.wait { return disposables.contains(DisposableOf(disposable)) } } /// Remove the member from the set and return it if it was present. public func remove(disposable: IDisposable) -> IDisposable? { var shouldDispose = false spinLock.wait { if !isDisposed { if let removed = disposables.remove(DisposableOf(disposable)) { shouldDispose = true } } } if shouldDispose { disposable.dispose() } return shouldDispose ? disposable : nil } /// Erase all the elements. If `keepCapacity` is `true`, `capacity` /// will not decrease. public func removeAll(keepCapacity: Bool = false) { var removed: Set<DisposableOf>? = nil spinLock.wait { if !isDisposed { removed = disposables disposables.removeAll(keepCapacity: keepCapacity) } } if let removed = removed { for x in removed { x.dispose() } } } /// The number of members in the set. /// /// Complexity: O(1) var count: Int { return spinLock.wait { return disposables.count } } // MARK: private private var disposables = Set<DisposableOf>() private var spinLock = SpinLock() } extension CompositeDisposable: CollectionType { // MARK: CollectionType public subscript (position: Index) -> Generator.Element { return disposables[position] } public typealias Index = Set<DisposableOf>.Index /// The position of the first element in a non-empty set. /// /// This is identical to `endIndex` in an empty set. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSSet`, O(N) otherwise. public var startIndex: Index { return disposables.startIndex } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSSet`, O(N) otherwise. public var endIndex: Index { return disposables.endIndex } // MARK: SequenceType public typealias Generator = Set<DisposableOf>.Generator /// Return a *generator* over the members. /// /// Complexity: O(1) public func generate() -> Generator { return disposables.generate() } } // MARK: private public final class DisposableOf: IDisposable, Hashable { let disposable: IDisposable init(_ disposable: IDisposable) { if let disposableOf = disposable as? DisposableOf { self.disposable = disposableOf.disposable } else { self.disposable = disposable } } // MARK: IDisposable public func dispose() { disposable.dispose() } // MARK: Hashable public var hashValue: Int { return ObjectIdentifier(disposable).hashValue } } public func == (lhs: DisposableOf, rhs: DisposableOf) -> Bool { return lhs.hashValue == rhs.hashValue } public func == (var lhs: IDisposable, var rhs: IDisposable) -> Bool { return DisposableOf(lhs) == DisposableOf(rhs) } public func === (var lhs: IDisposable, var rhs: IDisposable) -> Bool { return DisposableOf(lhs) == DisposableOf(rhs) }
mit
50414d3b495b85265792affacd125358
27.269767
99
0.575518
4.770801
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/Classes.xcplaygroundpage/Contents.swift
1
8372
//: ## Classes //: ---- //: [Previous](@previous) import Foundation //: Classes Are Reference Types class DataImporter { var fileName = "data.txt" } let dataImporter = DataImporter() let aux = dataImporter print(dataImporter.fileName, aux.fileName) aux.fileName = "other.txt" print(dataImporter.fileName, aux.fileName) //: Lazy Stored Properties class DataManager { lazy var importer = DataImporter() var data = [String]() } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") print(manager.importer.fileName) // the DataImporter instance for the importer property has now been created //: Computed Properties class Point { var x = 0.0, y = 0.0 } class Size { var width = 0.0, height = 0.0 } class Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) let point = Point() point.x = centerX point.y = centerY return point } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } let square = Rect() square.origin.x = 0.0 square.origin.y = 0.0 square.size.width = 10.0 square.size.height = 10.0 let newPoint = Point() newPoint.x = 15.0 newPoint.y = 15.0 square.center = newPoint print("square.origin is now at (\(square.origin.x), \(square.origin.y))") //: Read-Only Computed Properties class Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid() fourByFiveByTwo.width = 4.0 fourByFiveByTwo.height = 5.0 fourByFiveByTwo.depth = 2.0 print("the volume is \(fourByFiveByTwo.volume)") //: Property Observers class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896 //: Type Property class SomeClass { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 27 } // use the class keyword to allow subclasses to override the superclass’s implementation class var overrideableComputedTypeProperty: Int { return 107 } } print(SomeClass.storedTypeProperty) SomeClass.storedTypeProperty = "Another value." print(SomeClass.storedTypeProperty) //: Singleton class Manager { static var sharedManager = Manager() var name = "Manager Singleton" } print(Manager.sharedManager.name) //: Instance Methods class Counter { var count = 0 func increment() { ++count } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } } let counter = Counter() print(counter.count) counter.increment() print(counter.count) counter.incrementBy(5) print(counter.count) counter.reset() print(counter.count) //: Local and External Parameter Names for Methods class Rectangle { var width = 0 var height = 0 func multiplyWidthWith(width: Int) { self.width *= width } } let rect = Rectangle() rect.width = 10 print(rect.width) rect.multiplyWidthWith(5) print(rect.width) //: Type Methods class AnotherClass { class func someTypeMethod() { print("type method!") } } AnotherClass.someTypeMethod() //: Initialization class Player { let playerName: String var playerAge: Int? init() { playerName = "Unknown" } init(name: String) { playerName = name } convenience init(name: String, surname: String) { self.init(name: name + " " + surname) } init?(fullname: String) { playerName = fullname if fullname.isEmpty { return nil } } // For subclasses required init(name: String, age: Int) { playerName = name playerAge = age } } let anyone = Player() print(anyone.playerName) let player = Player(name: "Mark") print(player.playerName) let proPlayer = Player(name: "Michael", surname: "Jordan") print(proPlayer.playerName) let failPlayer = Player(fullname: "") print(failPlayer) let fullnamePlayer = Player(fullname: "Tiger Woods") print(fullnamePlayer!.playerName) //: Deinitialization class Temp { let name: String init() { name = "My name" } deinit { print("Goodbye!") } } var temp: Temp? = Temp() print(temp?.name) temp = nil // Call deinit //: Subscripts class Game { var name = "Game Name" var players: [String] = [] init(withPlayers: [String]) { players = withPlayers } subscript(index: Int) -> String { return players[index] } } let match = Game(withPlayers: ["John", "Mark", "Patrick"]) print(match[0]) print(match[1]) print(match[2]) // Returning String class Person { var name: String = "" init(name: String) { self.name = name } } class Group { var list = [Person]() subscript(var index: Int) -> String { return list[index].name } } var group = Group() group.list.append(Person(name: "Ricardo")) group.list.append(Person(name: "Fabio")) group.list.append(Person(name: "Mauricio")) print(group[0]) print(group[1]) print(group[2]) //: Inheritance class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() {} } let someVehicle = Vehicle() print(someVehicle.description) class Bicycle: Vehicle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print(bicycle.description) //: Overriding Methods class Train: Vehicle { override func makeNoise() { print("Choo Choo") } } let train = Train() train.makeNoise() //: Overriding Properties class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear \(gear)" } } let car = Car() print(car.description) //: Overriding Property Observers class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let automatic = AutomaticCar() automatic.currentSpeed = 35.0 print(automatic.description) //: Preventing Overrides class FutureCar: Car { final var technology = "Unknown" } //: Optional Property Types class SurveyQuestion { let title: String var text: String var response: String? init(text: String) { self.title = "No Title" self.text = text } func ask() { print(text) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") cheeseQuestion.ask() cheeseQuestion.response = "Yes, I do like cheese." //: Weak References class Person2 { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } weak var tenant: Person2? deinit { print("Apartment \(unit) is being deinitialized") } } var john: Person2? var unit4A: Apartment? john = Person2(name: "John Appleseed") unit4A = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john john = nil unit4A = nil //: Unowned References class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { print("\(name) is being deinitialized") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { print("Card #\(number) is being deinitialized") } } var mark: Customer? mark = Customer(name: "Mark Nichols") mark!.card = CreditCard(number: 1234_5678_9012_3456, customer: mark!) mark = nil //: [Next](@next)
mit
14e11f5b1f662172ef6a2ffe31cd8a0e
18.419954
108
0.633333
3.671053
false
false
false
false
darkbrow/iina
iina/PlaylistViewController.swift
1
29724
// // PlaylistViewController.swift // iina // // Created by lhc on 17/8/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa fileprivate let PrefixMinLength = 7 fileprivate let FilenameMinLength = 12 fileprivate let MenuItemTagCut = 601 fileprivate let MenuItemTagCopy = 602 fileprivate let MenuItemTagPaste = 603 fileprivate let MenuItemTagDelete = 604 class PlaylistViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSMenuDelegate, SidebarViewController, NSMenuItemValidation { override var nibName: NSNib.Name { return NSNib.Name("PlaylistViewController") } weak var mainWindow: MainWindowController! { didSet { self.player = mainWindow.player } } weak var player: PlayerCore! /** Similiar to the one in `QuickSettingViewController`. Since IBOutlet is `nil` when the view is not loaded at first time, use this variable to cache which tab it need to switch to when the view is ready. The value will be handled after loaded. */ private var pendingSwitchRequest: TabViewType? var playlistChangeObserver: NSObjectProtocol? /** Enum for tab switching */ enum TabViewType: Int { case playlist = 0 case chapters } var currentTab: TabViewType = .playlist @IBOutlet weak var playlistTableView: NSTableView! @IBOutlet weak var chapterTableView: NSTableView! @IBOutlet weak var playlistBtn: NSButton! @IBOutlet weak var chaptersBtn: NSButton! @IBOutlet weak var tabView: NSTabView! @IBOutlet weak var buttonTopConstraint: NSLayoutConstraint! @IBOutlet weak var tabHeightConstraint: NSLayoutConstraint! @IBOutlet weak var deleteBtn: NSButton! @IBOutlet weak var loopBtn: NSButton! @IBOutlet weak var shuffleBtn: NSButton! @IBOutlet weak var totalLengthLabel: NSTextField! @IBOutlet var subPopover: NSPopover! @IBOutlet var addFileMenu: NSMenu! private var playlistTotalLengthIsReady = false private var playlistTotalLength: Double? = nil var downShift: CGFloat = 0 { didSet { buttonTopConstraint.constant = downShift } } var useCompactTabHeight = false { didSet { tabHeightConstraint.constant = useCompactTabHeight ? 32 : 48 } } override func viewDidLoad() { super.viewDidLoad() withAllTableViews { (view) in view.dataSource = self } playlistTableView.menu?.delegate = self [deleteBtn, loopBtn, shuffleBtn].forEach { $0?.image?.isTemplate = true $0?.alternateImage?.isTemplate = true } hideTotalLength() // colors if #available(macOS 10.14, *) { withAllTableViews { $0.backgroundColor = NSColor(named: .sidebarTableBackground)! } } // handle pending switch tab request if pendingSwitchRequest != nil { switchToTab(pendingSwitchRequest!) pendingSwitchRequest = nil } // nofitications playlistChangeObserver = NotificationCenter.default.addObserver(forName: .iinaPlaylistChanged, object: player, queue: OperationQueue.main) { _ in self.playlistTotalLengthIsReady = false self.reloadData(playlist: true, chapters: false) } // register for double click action let action = #selector(performDoubleAction(sender:)) playlistTableView.doubleAction = action playlistTableView.target = self // register for drag and drop playlistTableView.registerForDraggedTypes([.iinaPlaylistItem, .nsFilenames, .nsURL, .string]) (subPopover.contentViewController as! SubPopoverViewController).player = player if let popoverView = subPopover.contentViewController?.view, popoverView.trackingAreas.isEmpty { popoverView.addTrackingArea(NSTrackingArea(rect: popoverView.bounds, options: [.activeAlways, .inVisibleRect, .mouseEnteredAndExited, .mouseMoved], owner: mainWindow, userInfo: ["obj": 0])) } } override func viewDidAppear() { reloadData(playlist: true, chapters: true) let loopStatus = player.mpv.getString(MPVOption.PlaybackControl.loopPlaylist) loopBtn.state = (loopStatus == "inf" || loopStatus == "force") ? .on : .off } deinit { NotificationCenter.default.removeObserver(self.playlistChangeObserver!) } func reloadData(playlist: Bool, chapters: Bool) { if playlist { player.getPlaylist() playlistTableView.reloadData() } if chapters { player.getChapters() chapterTableView.reloadData() } } private func showTotalLength() { guard let playlistTotalLength = playlistTotalLength, playlistTotalLengthIsReady else { return } totalLengthLabel.isHidden = false if playlistTableView.numberOfSelectedRows > 0 { let info = player.info let selectedDuration = playlistTableView.selectedRowIndexes .compactMap { info.cachedVideoDurationAndProgress[info.playlist[$0].filename]?.duration } .compactMap { $0 > 0 ? $0 : 0 } .reduce(0, +) totalLengthLabel.stringValue = String(format: NSLocalizedString("playlist.total_length_with_selected", comment: "%@ of %@ selected"), VideoTime(selectedDuration).stringRepresentation, VideoTime(playlistTotalLength).stringRepresentation) } else { totalLengthLabel.stringValue = String(format: NSLocalizedString("playlist.total_length", comment: "%@ in total"), VideoTime(playlistTotalLength).stringRepresentation) } } private func hideTotalLength() { totalLengthLabel.isHidden = true } private func refreshTotalLength() { var totalDuration: Double? = 0 for p in player.info.playlist { if let duration = player.info.cachedVideoDurationAndProgress[p.filename]?.duration { totalDuration! += duration > 0 ? duration : 0 } else { totalDuration = nil break } } if let duration = totalDuration { playlistTotalLengthIsReady = true playlistTotalLength = duration DispatchQueue.main.async { self.showTotalLength() } } else { DispatchQueue.main.async { self.hideTotalLength() } } } // MARK: - Tab switching /** Switch tab (call from other objects) */ func pleaseSwitchToTab(_ tab: TabViewType) { if isViewLoaded { switchToTab(tab) } else { // cache the request pendingSwitchRequest = tab } } /** Switch tab (for internal call) */ private func switchToTab(_ tab: TabViewType) { switch tab { case .playlist: tabView.selectTabViewItem(at: 0) Utility.setBoldTitle(for: playlistBtn, true) Utility.setBoldTitle(for: chaptersBtn, false) case .chapters: tabView.selectTabViewItem(at: 1) Utility.setBoldTitle(for: chaptersBtn, true) Utility.setBoldTitle(for: playlistBtn, false) } currentTab = tab } // MARK: - NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { if tableView == playlistTableView { return player.info.playlist.count } else if tableView == chapterTableView { return player.info.chapters.count } else { return 0 } } // MARK: - Drag and Drop func copyToPasteboard(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) { let indexesData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes) let filePaths = rowIndexes.map { player.info.playlist[$0].filename } pboard.declareTypes([.iinaPlaylistItem, .nsFilenames], owner: tableView) pboard.setData(indexesData, forType: .iinaPlaylistItem) pboard.setPropertyList(filePaths, forType: .nsFilenames) } @discardableResult func pasteFromPasteboard(_ tableView: NSTableView, row: Int, from pboard: NSPasteboard) -> Bool { if let paths = pboard.propertyList(forType: .nsFilenames) as? [String] { let playableFiles = Utility.resolveURLs(player.getPlayableFiles(in: paths.map{ URL(string: $0) ?? URL(fileURLWithPath: $0) })) if playableFiles.count == 0 { return false } player.addToPlaylist(paths: playableFiles.map { $0.isFileURL ? $0.path : $0.absoluteString }, at: row) } else if let urls = pboard.propertyList(forType: .nsURL) as? [String] { player.addToPlaylist(paths: urls, at: row) } else if let droppedString = pboard.string(forType: .string), Regex.url.matches(droppedString) { player.addToPlaylist(paths: [droppedString], at: row) } else { return false } player.postNotification(.iinaPlaylistChanged) return true } func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool { if tableView == playlistTableView { copyToPasteboard(tableView, writeRowsWith: rowIndexes, to: pboard) return true } return false } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { playlistTableView.setDropRow(row, dropOperation: .above) if info.draggingSource as? NSTableView === tableView { return .move } return player.acceptFromPasteboard(info, isPlaylist: true) } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool { if info.draggingSource as? NSTableView === tableView, let rowData = info.draggingPasteboard.data(forType: .iinaPlaylistItem), let indexSet = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet { // Drag & drop within playlistTableView var oldIndexOffset = 0, newIndexOffset = 0 for oldIndex in indexSet { if oldIndex < row { player.playlistMove(oldIndex + oldIndexOffset, to: row) oldIndexOffset -= 1 } else { player.playlistMove(oldIndex, to: row + newIndexOffset) newIndexOffset += 1 } Logger.log("Playlist Drag & Drop from \(oldIndex) to \(row)") } player.postNotification(.iinaPlaylistChanged) return true } // Otherwise, could be copy/cut & paste within playlistTableView return pasteFromPasteboard(tableView, row: row, from: info.draggingPasteboard) } // MARK: - Edit Menu Support func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if currentTab == .playlist { switch menuItem.tag { case MenuItemTagCut, MenuItemTagCopy, MenuItemTagDelete: return playlistTableView.selectedRow != -1 case MenuItemTagPaste: return NSPasteboard.general.types?.contains(.nsFilenames) ?? false default: break } } return menuItem.isEnabled } @objc func copy(_ sender: NSMenuItem) { copyToPasteboard(playlistTableView, writeRowsWith: playlistTableView.selectedRowIndexes, to: .general) } @objc func cut(_ sender: NSMenuItem) { copy(sender) delete(sender) } @objc func paste(_ sender: NSMenuItem) { let dest = playlistTableView.selectedRowIndexes.first ?? 0 pasteFromPasteboard(playlistTableView, row: dest, from: .general) } @objc func delete(_ sender: NSMenuItem) { player.playlistRemove(playlistTableView.selectedRowIndexes) } // MARK: - private methods private func withAllTableViews(_ block: (NSTableView) -> Void) { block(playlistTableView) block(chapterTableView) } // MARK: - IBActions @IBAction func addToPlaylistBtnAction(_ sender: NSButton) { addFileMenu.popUp(positioning: nil, at: .zero, in: sender) } @IBAction func addFileAction(_ sender: AnyObject) { Utility.quickMultipleOpenPanel(title: "Add to playlist", canChooseDir: true) { urls in let playableFiles = self.player.getPlayableFiles(in: urls) if playableFiles.count != 0 { self.player.addToPlaylist(paths: playableFiles.map { $0.path }, at: self.player.info.playlist.count) self.player.mainWindow.playlistView.reloadData(playlist: true, chapters: false) self.player.sendOSD(.addToPlaylist(playableFiles.count)) } } } @IBAction func addURLAction(_ sender: AnyObject) { Utility.quickPromptPanel("add_url") { url in if Regex.url.matches(url) { self.player.addToPlaylist(url) self.player.mainWindow.playlistView.reloadData(playlist: true, chapters: false) self.player.sendOSD(.addToPlaylist(1)) } else { Utility.showAlert("wrong_url_format") } } } @IBAction func clearPlaylistBtnAction(_ sender: AnyObject) { player.clearPlaylist() reloadData(playlist: true, chapters: false) player.sendOSD(.clearPlaylist) } @IBAction func playlistBtnAction(_ sender: AnyObject) { reloadData(playlist: true, chapters: false) switchToTab(.playlist) } @IBAction func chaptersBtnAction(_ sender: AnyObject) { reloadData(playlist: false, chapters: true) switchToTab(.chapters) } @IBAction func loopBtnAction(_ sender: AnyObject) { player.togglePlaylistLoop() } @IBAction func shuffleBtnAction(_ sender: AnyObject) { player.toggleShuffle() } @objc func performDoubleAction(sender: AnyObject) { let tv = sender as! NSTableView if tv.numberOfSelectedRows > 0 { player.playFileInPlaylist(tv.selectedRow) tv.deselectAll(self) tv.reloadData() } } @IBAction func prefixBtnAction(_ sender: PlaylistPrefixButton) { sender.isFolded = !sender.isFolded } @IBAction func subBtnAction(_ sender: NSButton) { let row = playlistTableView.row(for: sender) guard let vc = subPopover.contentViewController as? SubPopoverViewController else { return } vc.filePath = player.info.playlist[row].filename vc.tableView.reloadData() vc.heightConstraint.constant = (vc.tableView.rowHeight + vc.tableView.intercellSpacing.height) * CGFloat(vc.tableView.numberOfRows) subPopover.show(relativeTo: sender.bounds, of: sender, preferredEdge: .maxY) } // MARK: - Table delegates // Due to NSTableView's type select feature, space key will be passed to // other responders like other keys. This is a workaround to prevent space // key cannot toggle pause when the table view is first responder. func tableView(_ tableView: NSTableView, shouldTypeSelectFor event: NSEvent, withCurrentSearch searchString: String?) -> Bool { if event.characters == " " { mainWindow.keyDown(with: event) } return false } func tableViewSelectionDidChange(_ notification: Notification) { let tv = notification.object as! NSTableView if tv == playlistTableView { showTotalLength() return } guard tv.numberOfSelectedRows > 0 else { return } let index = tv.selectedRow player.playChapter(index) let chapter = player.info.chapters[index] tv.deselectAll(self) tv.reloadData() player.sendOSD(.chapter(chapter.title)) } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let identifier = tableColumn?.identifier else { return nil } let info = player.info let v = tableView.makeView(withIdentifier: identifier, owner: self) as! NSTableCellView // playlist if tableView == playlistTableView { guard row < info.playlist.count else { return nil } let item = info.playlist[row] if identifier == .isChosen { v.textField?.stringValue = item.isPlaying ? Constants.String.play : "" } else if identifier == .trackName { let cellView = v as! PlaylistTrackCellView // file name let filename = item.filenameForDisplay let filenameWithoutExt: String = NSString(string: filename).deletingPathExtension if let prefix = player.info.currentVideosInfo.first(where: { $0.path == item.filename })?.prefix, !prefix.isEmpty, prefix.count <= filenameWithoutExt.count, // check whether prefix length > filename length prefix.count >= PrefixMinLength, filename.count > FilenameMinLength { cellView.prefixBtn.hasPrefix = true cellView.prefixBtn.text = prefix cellView.textField?.stringValue = String(filename[filename.index(filename.startIndex, offsetBy: prefix.count)...]) } else { cellView.prefixBtn.hasPrefix = false cellView.textField?.stringValue = filename } // playback progress and duration cellView.durationLabel.font = NSFont.monospacedDigitSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .regular) cellView.durationLabel.stringValue = "" if let cached = player.info.cachedVideoDurationAndProgress[item.filename], let duration = cached.duration { // if it's cached if duration > 0 { // if FFmpeg got the duration succcessfully cellView.durationLabel.stringValue = VideoTime(duration).stringRepresentation if let progress = cached.progress { cellView.playbackProgressView.percentage = progress / duration cellView.playbackProgressView.needsDisplay = true } self.refreshTotalLength() } } else { // get related data and schedule a reload if Preference.bool(for: .prefetchPlaylistVideoDuration) { player.playlistQueue.async { self.player.refreshCachedVideoProgress(forVideoPath: item.filename) self.refreshTotalLength() DispatchQueue.main.async { self.playlistTableView.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integersIn: 0...1)) } } } } // sub button if let matchedSubs = player.info.matchedSubs[item.filename], !matchedSubs.isEmpty { cellView.subBtn.isHidden = false cellView.subBtnWidthConstraint.constant = 12 } else { cellView.subBtn.isHidden = true cellView.subBtnWidthConstraint.constant = 0 } cellView.subBtn.image?.isTemplate = true } return v } // chapter else if tableView == chapterTableView { let chapters = info.chapters let chapter = chapters[row] // next chapter time let nextChapterTime = chapters[at: row+1]?.time ?? .infinite // construct view if identifier == .isChosen { // left column v.textField?.stringValue = (info.chapter == row) ? Constants.String.play : "" return v } else if identifier == .trackName { // right column let cellView = v as! ChapterTableCellView cellView.textField?.stringValue = chapter.title.isEmpty ? "Chapter \(row)" : chapter.title cellView.durationTextField.stringValue = "\(chapter.time.stringRepresentation) → \(nextChapterTime.stringRepresentation)" return cellView } else { return nil } } else { return nil } } // MARK: - Context menu var selectedRows: IndexSet? func menuNeedsUpdate(_ menu: NSMenu) { let selectedRow = playlistTableView.selectedRowIndexes let clickedRow = playlistTableView.clickedRow var target = IndexSet() if clickedRow != -1 { if selectedRow.contains(clickedRow) { target = selectedRow } else { target.insert(clickedRow) } } selectedRows = target menu.removeAllItems() let items = buildMenu(forRows: target).items for item in items { menu.addItem(item) } } @IBAction func contextMenuPlayNext(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } let current = player.mpv.getInt(MPVProperty.playlistPos) var ob = 0 // index offset before current playing item var mc = 1 // moved item count, +1 because move to next item of current played one for item in selectedRows { if item == current { continue } if item < current { player.playlistMove(item + ob, to: current + mc + ob) ob -= 1 } else { player.playlistMove(item, to: current + mc + ob) } mc += 1 } playlistTableView.deselectAll(nil) player.postNotification(.iinaPlaylistChanged) } @IBAction func contextMenuPlayInNewWindow(_ sender: NSMenuItem) { let files = selectedRows!.enumerated().map { (_, i) in URL(fileURLWithPath: player.info.playlist[i].filename) } PlayerCore.newPlayerCore.openURLs(files, shouldAutoLoad: false) } @IBAction func contextMenuRemove(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } player.playlistRemove(selectedRows) } @IBAction func contextMenuDeleteFile(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } var count = 0 for index in selectedRows { player.playlistRemove(index) guard !player.info.playlist[index].isNetworkResource else { continue } let url = URL(fileURLWithPath: player.info.playlist[index].filename) do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) count += 1 } catch let error { Utility.showAlert("playlist.error_deleting", arguments: [error.localizedDescription]) } } playlistTableView.deselectAll(nil) player.postNotification(.iinaPlaylistChanged) } @IBAction func contextMenuDeleteFileAfterPlayback(_ sender: NSMenuItem) { // WIP } @IBAction func contextMenuRevealInFinder(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } var urls: [URL] = [] for index in selectedRows { if !player.info.playlist[index].isNetworkResource { urls.append(URL(fileURLWithPath: player.info.playlist[index].filename)) } } playlistTableView.deselectAll(nil) NSWorkspace.shared.activateFileViewerSelecting(urls) } @IBAction func contextMenuAddSubtitle(_ sender: NSMenuItem) { guard let selectedRows = selectedRows, let index = selectedRows.first else { return } let filename = player.info.playlist[index].filename let fileURL = URL(fileURLWithPath: filename).deletingLastPathComponent() Utility.quickMultipleOpenPanel(title: NSLocalizedString("alert.choose_media_file.title", comment: "Choose Media File"), dir: fileURL, canChooseDir: true) { subURLs in for subURL in subURLs { guard Utility.supportedFileExt[.sub]!.contains(subURL.pathExtension.lowercased()) else { return } self.player.info.matchedSubs[filename, default: []].append(subURL) } self.playlistTableView.reloadData(forRowIndexes: selectedRows, columnIndexes: IndexSet(integersIn: 0...1)) } } @IBAction func contextMenuWrongSubtitle(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } for index in selectedRows { let filename = player.info.playlist[index].filename player.info.matchedSubs[filename]?.removeAll() playlistTableView.reloadData(forRowIndexes: selectedRows, columnIndexes: IndexSet(integersIn: 0...1)) } } @IBAction func contextOpenInBrowser(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } selectedRows.forEach { i in let info = player.info.playlist[i] if info.isNetworkResource, let url = URL(string: info.filename) { NSWorkspace.shared.open(url) } } } @IBAction func contextCopyURL(_ sender: NSMenuItem) { guard let selectedRows = selectedRows else { return } let urls = selectedRows.compactMap { i -> String? in let info = player.info.playlist[i] return info.isNetworkResource ? info.filename : nil } NSPasteboard.general.clearContents() NSPasteboard.general.writeObjects([urls.joined(separator: "\n") as NSString]) } private func buildMenu(forRows rows: IndexSet) -> NSMenu { let result = NSMenu() let isSingleItem = rows.count == 1 if !rows.isEmpty { let firstURL = player.info.playlist[rows.first!] let matchedSubCount = player.info.matchedSubs[firstURL.filename]?.count ?? 0 let title: String = isSingleItem ? firstURL.filenameForDisplay : String(format: NSLocalizedString("pl_menu.title_multi", comment: "%d Items"), rows.count) result.addItem(withTitle: title) result.addItem(NSMenuItem.separator()) result.addItem(withTitle: NSLocalizedString("pl_menu.play_next", comment: "Play Next"), action: #selector(self.contextMenuPlayNext(_:))) result.addItem(withTitle: NSLocalizedString("pl_menu.play_in_new_window", comment: "Play in New Window"), action: #selector(self.contextMenuPlayInNewWindow(_:))) result.addItem(withTitle: NSLocalizedString(isSingleItem ? "pl_menu.remove" : "pl_menu.remove_multi", comment: "Remove"), action: #selector(self.contextMenuRemove(_:))) if !player.isInMiniPlayer { result.addItem(NSMenuItem.separator()) if isSingleItem { result.addItem(withTitle: String(format: NSLocalizedString("pl_menu.matched_sub", comment: "Matched %d Subtitle(s)"), matchedSubCount)) result.addItem(withTitle: NSLocalizedString("pl_menu.add_sub", comment: "Add Subtitle…"), action: #selector(self.contextMenuAddSubtitle(_:))) } if matchedSubCount != 0 { result.addItem(withTitle: NSLocalizedString("pl_menu.wrong_sub", comment: "Wrong Subtitle"), action: #selector(self.contextMenuWrongSubtitle(_:))) } } result.addItem(NSMenuItem.separator()) // network resources related operations let networkCount = rows.filter { player.info.playlist[$0].isNetworkResource }.count if networkCount != 0 { result.addItem(withTitle: NSLocalizedString("pl_menu.browser", comment: "Open in Browser"), action: #selector(self.contextOpenInBrowser(_:))) result.addItem(withTitle: NSLocalizedString(networkCount == 1 ? "pl_menu.copy_url" : "pl_menu.copy_url_multi", comment: "Copy URL(s)"), action: #selector(self.contextCopyURL(_:))) result.addItem(NSMenuItem.separator()) } // file related operations let localCount = rows.count - networkCount if localCount != 0 { result.addItem(withTitle: NSLocalizedString(localCount == 1 ? "pl_menu.delete" : "pl_menu.delete_multi", comment: "Delete"), action: #selector(self.contextMenuDeleteFile(_:))) // result.addItem(withTitle: NSLocalizedString(isSingleItem ? "pl_menu.delete_after_play" : "pl_menu.delete_after_play_multi", comment: "Delete After Playback"), action: #selector(self.contextMenuDeleteFileAfterPlayback(_:))) result.addItem(withTitle: NSLocalizedString("pl_menu.reveal_in_finder", comment: "Reveal in Finder"), action: #selector(self.contextMenuRevealInFinder(_:))) result.addItem(NSMenuItem.separator()) } } result.addItem(withTitle: NSLocalizedString("pl_menu.add_file", comment: "Add File"), action: #selector(self.addFileAction(_:))) result.addItem(withTitle: NSLocalizedString("pl_menu.add_url", comment: "Add URL"), action: #selector(self.addURLAction(_:))) result.addItem(withTitle: NSLocalizedString("pl_menu.clear_playlist", comment: "Clear Playlist"), action: #selector(self.clearPlaylistBtnAction(_:))) return result } } class PlaylistTrackCellView: NSTableCellView { @IBOutlet weak var subBtn: NSButton! @IBOutlet weak var subBtnWidthConstraint: NSLayoutConstraint! @IBOutlet weak var prefixBtn: PlaylistPrefixButton! @IBOutlet weak var durationLabel: NSTextField! @IBOutlet weak var playbackProgressView: PlaylistPlaybackProgressView! override func prepareForReuse() { playbackProgressView.percentage = 0 playbackProgressView.needsDisplay = true } } class PlaylistPrefixButton: NSButton { var text = "" { didSet { refresh() } } var hasPrefix = true { didSet { refresh() } } var isFolded = true { didSet { refresh() } } private func refresh() { self.title = hasPrefix ? (isFolded ? "…" : text) : "" } } class PlaylistView: NSView { override func resetCursorRects() { let rect = NSRect(x: frame.origin.x - 4, y: frame.origin.y, width: 4, height: frame.height) addCursorRect(rect, cursor: .resizeLeftRight) } override func mouseDown(with event: NSEvent) {} // override var allowsVibrancy: Bool { return true } } class SubPopoverViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var playlistTableView: NSTableView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! weak var player: PlayerCore! var filePath: String = "" func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return false } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { guard let matchedSubs = player.info.matchedSubs[filePath] else { return nil } return matchedSubs[row].lastPathComponent } func numberOfRows(in tableView: NSTableView) -> Int { return player.info.matchedSubs[filePath]?.count ?? 0 } @IBAction func wrongSubBtnAction(_ sender: AnyObject) { player.info.matchedSubs[filePath]?.removeAll() tableView.reloadData() if let row = player.info.playlist.firstIndex(where: { $0.filename == filePath }) { playlistTableView.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integersIn: 0...1)) } } } class ChapterTableCellView: NSTableCellView { @IBOutlet weak var durationTextField: NSTextField! }
gpl-3.0
33aa7effbe41910c921e6fd02a9365c0
34.760529
233
0.685836
4.545274
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/extension/BTCAmount+extension.swift
1
2761
// // BTCAmount+extension.swift // Chance_wallet // // Created by Chance on 16/1/20. // Copyright © 2016年 Chance. All rights reserved. // import Foundation extension BTCAmount { /** 把聪类型转为浮点格式的字符 - parameter satoshiAmount: 聪 - returns: 浮点的字符串 */ public static func stringWithSatoshiInBTCFormat(_ satoshiAmount: BTCAmount) -> String { var BTCValueDecimalNumber = NSDecimalNumber(value: satoshiAmount as Int64) BTCValueDecimalNumber = BTCValueDecimalNumber.dividing(by: NSDecimalNumber(value: BTCCoin as Int64)) let twoDecimalPlacesFormatter = NumberFormatter() twoDecimalPlacesFormatter.maximumFractionDigits = 10 twoDecimalPlacesFormatter.minimumFractionDigits = 2 twoDecimalPlacesFormatter.minimumIntegerDigits = 1 return twoDecimalPlacesFormatter.string(from: BTCValueDecimalNumber)! } /** 把浮点的字符串转未聪类型 - parameter amountString: - returns: */ public static func satoshiWithStringInBTCFormat(_ amountString: String) -> BTCAmount { let amountDecimalNumber = NSDecimalNumber(string: amountString) let satoshiAmountDecimalNumber = amountDecimalNumber.multiplying(by: NSDecimalNumber(value: BTCCoin as Int64)) let satoshiAmountInteger = satoshiAmountDecimalNumber.int64Value return satoshiAmountInteger } /// 把聪转为BTC单位 /// /// - Returns: BTC单位的字符串类型 public func toBTC() -> String { var BTCValueDecimalNumber = NSDecimalNumber(value: self as Int64) BTCValueDecimalNumber = BTCValueDecimalNumber.dividing(by: NSDecimalNumber(value: BTCCoin as Int64)) let twoDecimalPlacesFormatter = NumberFormatter() twoDecimalPlacesFormatter.maximumFractionDigits = 10 twoDecimalPlacesFormatter.minimumFractionDigits = 2 twoDecimalPlacesFormatter.minimumIntegerDigits = 1 return twoDecimalPlacesFormatter.string(from: BTCValueDecimalNumber)! } } extension String { /// 把BTC单位的字符串类型转为聪(Int64) /// /// - Returns: func toBTCAmount(_ def: BTCAmount = 0) -> BTCAmount { if !self.isEmpty { let amountDecimalNumber = NSDecimalNumber(string: self) let satoshiAmountDecimalNumber = amountDecimalNumber.multiplying(by: NSDecimalNumber(value: BTCCoin as Int64)) let satoshiAmountInteger = satoshiAmountDecimalNumber.int64Value return satoshiAmountInteger } else { return def } } }
mit
5532d5392ab9a50cb0073c2199e3f1a0
30.035294
122
0.666414
4.912477
false
false
false
false
baottran/nSURE
nSURE/AssessmentChooseViewController.swift
1
6773
// // AssessmentViewController.swift // nSURE // // Created by Bao Tran on 7/13/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit import MBProgressHUD class AssessmentChooseViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var openSideBarButton: UIBarButtonItem! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var previousDateButton: UIButton! @IBOutlet weak var nextDateButton: UIButton! @IBOutlet weak var timeSlotCollectionView: UICollectionView! var timeSlotTaken = ["","","","","","","","","",""] var timeSlotArray = ["","","","","","","","","",""] var assessmentArray: Array<PFObject>? var currentDate: NSDate? override func viewDidLoad() { super.viewDidLoad() if currentDate == nil { currentDate = NSDate.today().beginningOfDay } dateLabel.text = currentDate?.toLongDateString() openSideBarButton.target = self.revealViewController() openSideBarButton.action = Selector("revealToggle:") self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addSubview(timeSlotCollectionView) timeSlotCollectionView.dataSource = self timeSlotCollectionView.delegate = self queryAssessments() } func queryAssessments(){ let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.labelText = "Searching For Assessments" let query = PFQuery(className: "Repair") query.findObjectsInBackgroundWithBlock{ results, error in if let results = results as? Array<PFObject> { self.assessmentArray = results MBProgressHUD.hideAllHUDsForView(self.view, animated: true) self.timeSlotCollectionView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func previousDate(){ if currentDate == NSDate.today().beginningOfDay { //do nothing } else { currentDate = currentDate! - 1.day dateLabel.text = currentDate?.toLongDateString() timeSlotCollectionView.reloadData() timeSlotTaken = ["","","","","","","","","",""] } } @IBAction func nextDate(){ currentDate = currentDate! + 1.day dateLabel.text = currentDate?.toLongDateString() timeSlotCollectionView.reloadData() timeSlotTaken = ["","","","","","","","","",""] } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("TimeSlot", forIndexPath: indexPath) as! DayTimeSlotCollectionViewCell if indexPath.row < 4 { cell.dayTimeSlotLabel.text = "\(indexPath.row + 8):00 AM" } else if indexPath.row == 4 { cell.dayTimeSlotLabel.text = "12:00 PM" } else { cell.dayTimeSlotLabel.text = "\(indexPath.row - 4):00 PM" } let hour = indexPath.row + 8 let timeSlot = currentDate! + hour.hours if let assessments = assessmentArray { for assessment in assessments { if let assessmentTime = assessment["assessmentDate"] as? NSDate { if (assessmentTime >= timeSlot) && (assessmentTime < (timeSlot + 1.hour)){ let assessmentCompleted = assessment["assessmentCompleted"] as! Bool let customerObj = assessment["customer"] as! PFObject let customerName = getCustomerName(customerObj) timeSlotArray[indexPath.row] = assessment.objectId! if assessmentCompleted == true { cell.dayTimeSlotLabel.text = "\(assessmentTime.toShortTimeString()) \(customerName): Assessment Completed" cell.backgroundColor = UIColor.whiteColor() timeSlotTaken[indexPath.row] = "completed" } else { cell.dayTimeSlotLabel.text = "\(assessmentTime.toShortTimeString()) \(customerName) : Assessment Not Completed" cell.backgroundColor = UIColor.greenColor() timeSlotTaken[indexPath.row] = "open" } } } } } if timeSlotTaken[indexPath.row] == "" { cell.backgroundColor = UIColor.lightGrayColor() } return cell } func getCustomerName(customerObj: PFObject) -> String { var customerName = "" let query = PFQuery(className: "Customer") let result = query.getObjectWithId(customerObj.objectId!) if let customer = result { let customerFirstName = customer["firstName"] as! String let customerLastName = customer["lastName"] as! String customerName = "\(customerFirstName) \(customerLastName)" } return customerName } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if timeSlotTaken[indexPath.row] == "open" { // print("assessmentArrayObject: \(timeSlotArray[indexPath.row])", terminator: "") // var assessmentDate = currentDate! + indexPath.row.hours self.performSegueWithIdentifier("ViewAssessment", sender: timeSlotArray[indexPath.row]) } else { print("nope", terminator: "") } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ViewAssessment"{ let reviewController = segue.destinationViewController as! AssessmentReviewDetailsViewController let assessmentObjId = sender as! String let query = PFQuery(className: "Repair") let assessmentObject = query.getObjectWithId(assessmentObjId) reviewController.assessmentObj = assessmentObject } } }
mit
23e31e4484a001878a9edbe96eac5643
37.050562
143
0.595453
5.592898
false
false
false
false
Eonil/HomeworkApp1
Driver/HomeworkApp1/Client.swift
1
1668
// // Client.swift // HomeworkApp1 // // Created by Hoon H. on 2015/02/26. // // import Foundation import UIKit struct Client { static func fetchImageAtURL(url:NSURL, handler:(image:UIImage?)->()) -> Transmission { Debug.log("Client.fetchImageAtURL beginning with url `\(url)`.") let t = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (d:NSData!, r:NSURLResponse!, e:NSError!) -> Void in if d == nil { Debug.log("Client.fetchImageAtURL download failure with no error from URL `\(url)`.") handler(image: nil) return } if e != nil { if e!.domain == NSURLErrorDomain { if e!.code == NSURLErrorCancelled { // Cancelled intentionally. Debug.log("Client.fetchImageAtURL download from URL `\(url)` cancelled intentionally.") return } } Debug.log("Client.fetchImageAtURL download error `\(e)` while downloading from URL `\(url)`.") handler(image: nil) return } let m = UIImage(data: d!) if m == nil { Debug.log("Client.fetchImageAtURL downloaded `\(d.length) bytes` from URL `\(url)`, but data is not decodable into an image.") handler(image: nil) return } Debug.log("Client.fetchImageAtURL downloaded from url `\(url)` and decoded successfully into an image. All green.") handler(image: m) }) t.resume() return Transmission() { t.cancel() } } } /// Abstracts network I/O operation. /// Provides cancellation. final class Transmission { init(cancellation: ()->()) { self.cancellation = cancellation } deinit { self.cancel() } func cancel() { cancellation() } //// private let cancellation:()->() }
mit
359cffaea81a030226161dbd592829a8
22.492958
133
0.645683
3.533898
false
false
false
false
sonnygauran/trailer
Trailer/PullRequestDelegate.swift
1
1905
final class PullRequestDelegate: NSObject, NSTableViewDelegate, NSTableViewDataSource { private var pullRequestIds: [NSObject] override init() { pullRequestIds = [NSObject]() super.init() reloadData(nil) } func reloadData(filter: String?) { pullRequestIds.removeAll(keepCapacity: false) let f = ListableItem.requestForItemsOfType("PullRequest", withFilter: filter, sectionIndex: -1) let allPrs = try! mainObjectContext.executeFetchRequest(f) as! [PullRequest] if let firstPr = allPrs.first { var lastSection = firstPr.sectionIndex!.integerValue pullRequestIds.append(PullRequestSection.prMenuTitles[lastSection]) for pr in allPrs { let i = pr.sectionIndex!.integerValue if lastSection < i { pullRequestIds.append(PullRequestSection.prMenuTitles[i]) lastSection = i } pullRequestIds.append(pr.objectID) } } } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let object = pullRequestIds[row] if object.isKindOfClass(NSManagedObjectID) { let pr = existingObjectWithID(object as! NSManagedObjectID) as! PullRequest return PullRequestCell(pullRequest: pr) } else { let title = object as! String let showButton = (title == PullRequestSection.Merged.prMenuName() || title == PullRequestSection.Closed.prMenuName()) return SectionHeader(title: title, showRemoveAllButton: showButton) } } func tableView(tv: NSTableView, heightOfRow row: Int) -> CGFloat { let prView = tableView(tv, viewForTableColumn: nil, row: row) return prView!.frame.size.height } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return pullRequestIds.count } func pullRequestAtRow(row: Int) -> PullRequest? { if let object = pullRequestIds[row] as? NSManagedObjectID { return existingObjectWithID(object) as? PullRequest } else { return nil } } }
mit
0af4c0e10b543ff7169ce0c2c153ecc7
29.725806
120
0.741732
3.919753
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/Controllers/ShortDescriptionController.swift
1
10291
import Foundation import WMF enum ShortDescriptionControllerError: Error { case failureConstructingRegexExpression case missingSelf } protocol ShortDescriptionControllerDelegate: AnyObject { func currentDescription(completion: @escaping (String?) -> Void) } class ShortDescriptionController: ArticleDescriptionControlling { private let sectionFetcher: SectionFetcher private let sectionUploader: WikiTextSectionUploader private let articleURL: URL let article: WMFArticle let articleLanguageCode: String private let sectionID: Int = 0 let descriptionSource: ArticleDescriptionSource private weak var delegate: ShortDescriptionControllerDelegate? fileprivate static let templateRegex = "(\\{\\{\\s*[sS]hort description\\|(?:1=)?)([^}|]+)([^}]*\\}\\})" // MARK: Public /// Inits for use of updating EN Wikipedia article description /// - Parameters: /// - sectionFetcher: section fetcher that fetches the first section of wikitext. Injectable for unit tests. /// - sectionUploader: section uploader that uploads the new section wikitext. Injectable for unit tests. /// - article: WMFArticle from ArticleViewController /// - articleLanguageCode: Language code of article that we want to update (from ArticleViewController) /// - articleURL: URL of article that we want to update (from ArticleViewController) /// - descriptionSource: ArticleDescriptionSource determined via .edit action across ArticleViewController js bridge /// - delegate: Delegate that can extract the current description from the article content init(sectionFetcher: SectionFetcher = SectionFetcher(), sectionUploader: WikiTextSectionUploader = WikiTextSectionUploader(), article: WMFArticle, articleLanguageCode: String, articleURL: URL, descriptionSource: ArticleDescriptionSource, delegate: ShortDescriptionControllerDelegate) { self.sectionFetcher = sectionFetcher self.sectionUploader = sectionUploader self.article = article self.articleURL = articleURL self.articleLanguageCode = articleLanguageCode self.descriptionSource = descriptionSource self.delegate = delegate } /// Publishes a new article description to article wikitext. Detects the existence of the {{Short description}} template in the first section and replaces the text within or prepends the section with the new template. /// - Parameters: /// - description: The new description to insert into the wikitext /// - completion: Completion called when updated section upload call is successful. func publishDescription(_ description: String, completion: @escaping (Result<ArticleDescriptionPublishResult, Error>) -> Void) { sectionFetcher.fetchSection(with: sectionID, articleURL: articleURL) { [weak self] (result) in guard let self = self else { completion(.failure(ShortDescriptionControllerError.missingSelf)) return } switch result { case .success(let response): let wikitext = response.wikitext let revisionID = response.revisionID self.uploadNewDescriptionToWikitext(wikitext, baseRevisionID: revisionID, newDescription: description, completion: completion) case .failure(let error): completion(.failure(error)) } } } func currentDescription(completion: @escaping (String?) -> Void) { delegate?.currentDescription(completion: completion) } func errorTextFromError(_ error: Error) -> String { let errorText = "\((error as NSError).domain)-\((error as NSError).code)" return errorText } func learnMoreViewControllerWithTheme(_ theme: Theme) -> UIViewController? { guard let url = URL(string: "https://en.wikipedia.org/wiki/Wikipedia:Short_description") else { return nil } return SinglePageWebViewController(url: url, theme: theme, doesUseSimpleNavigationBar: true) } func warningTypesForDescription(_ description: String?) -> ArticleDescriptionWarningTypes { return descriptionIsTooLong(description) ? [.length] : [] } } // MARK: Private helpers private extension ShortDescriptionController { func uploadNewDescriptionToWikitext(_ wikitext: String, baseRevisionID: Int, newDescription: String, completion: @escaping (Result<ArticleDescriptionPublishResult, Error>) -> Void) { do { guard try wikitext.containsShortDescription() else { prependNewDescriptionToWikitextAndUpload(wikitext, baseRevisionID: baseRevisionID, newDescription: newDescription, completion: completion) return } replaceDescriptionInWikitextAndUpload(wikitext, newDescription: newDescription, baseRevisionID: baseRevisionID, completion: completion) } catch let error { completion(.failure(error)) } } func prependNewDescriptionToWikitextAndUpload(_ wikitext: String, baseRevisionID: Int, newDescription: String, completion: @escaping (Result<ArticleDescriptionPublishResult, Error>) -> Void) { let newTemplateToPrepend = "{{Short description|\(newDescription)}}\n" sectionUploader.prepend(toSectionID: "\(sectionID)", text: newTemplateToPrepend, forArticleURL: articleURL, isMinorEdit: true, baseRevID: baseRevisionID as NSNumber, completion: { [weak self] (result, error) in guard let self = self else { completion(.failure(ShortDescriptionControllerError.missingSelf)) return } if let error = error { completion(.failure(error)) return } guard let result = result, let revisionID = self.revisionIDFromResult(result: result) else { completion(.failure(RequestError.unexpectedResponse)) return } completion(.success(ArticleDescriptionPublishResult(newRevisionID: revisionID, newDescription: newDescription))) }) } func replaceDescriptionInWikitextAndUpload(_ wikitext: String, newDescription: String, baseRevisionID: Int, completion: @escaping (Result<ArticleDescriptionPublishResult, Error>) -> Void) { do { let updatedWikitext = try wikitext.replacingShortDescription(with: newDescription) sectionUploader.uploadWikiText(updatedWikitext, forArticleURL: articleURL, section: "\(sectionID)", summary: nil, isMinorEdit: true, addToWatchlist: false, baseRevID: baseRevisionID as NSNumber, captchaId: nil, captchaWord: nil, completion: { [weak self] (result, error) in guard let self = self else { completion(.failure(ShortDescriptionControllerError.missingSelf)) return } if let error = error { completion(.failure(error)) return } guard let result = result, let revisionID = self.revisionIDFromResult(result: result) else { completion(.failure(RequestError.unexpectedResponse)) return } completion(.success(ArticleDescriptionPublishResult(newRevisionID: revisionID, newDescription: newDescription))) }) } catch let error { completion(.failure(error)) } } func revisionIDFromResult(result: [AnyHashable: Any]) -> UInt64? { guard let fetchedData = result as? [String: Any], let newRevID = fetchedData["newrevid"] as? UInt64 else { assertionFailure("Could not extract revisionID as UInt64") return nil } return newRevID } } private extension String { /// Detects if the message receiver contains a {{short description}} template or not /// - Throws: If short description NSRegularExpression fails to instantiate /// - Returns: Boolean indicating whether the message receiver contains a {{short description}} template or not func containsShortDescription() throws -> Bool { guard let regex = try? NSRegularExpression(pattern: ShortDescriptionController.templateRegex) else { throw ShortDescriptionControllerError.failureConstructingRegexExpression } let matches = regex.matches(in: self, range: NSRange(self.startIndex..., in: self)) return matches.count > 0 } /// Replaces the {{short description}} template value in message receiver with the new description. /// Assumes the {{short description}} template already exists. Does not insert a {{short description}} template if it doesn't exist. /// - Parameter newShortDescription: new short description value to replace existing with /// - Throws: If short description NSRegularExpression fails to instantiate /// - Returns: Message receiver with short description template within replaced. func replacingShortDescription(with newShortDescription: String) throws -> String { guard let regex = try? NSRegularExpression(pattern: ShortDescriptionController.templateRegex) else { throw ShortDescriptionControllerError.failureConstructingRegexExpression } return regex.stringByReplacingMatches(in: self, range: NSRange(self.startIndex..., in: self), withTemplate: "$1\(newShortDescription)$3") } } #if TEST extension String { func testContainsShortDescription() throws -> Bool { return try containsShortDescription() } func testReplacingShortDescription(with newShortDescription: String) throws -> String { return try replacingShortDescription(with: newShortDescription) } } #endif
mit
a0616d70dcd51a3e6f888bc3ccd58afd
43.549784
289
0.657954
5.568723
false
false
false
false
danielmartin/swift
stdlib/public/core/ContiguouslyStored.swift
2
3445
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @usableFromInline internal protocol _HasContiguousBytes { func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R var _providesContiguousBytesNoCopy: Bool { get } } extension _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return true } } } extension Array: _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { #if _runtime(_ObjC) return _buffer._isNative #else return true #endif } } } extension ContiguousArray: _HasContiguousBytes {} extension UnsafeBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeMutableBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension String: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._guts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(self._guts.isFastUTF8) { return try self._guts.withFastUTF8 { try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } } extension Substring: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._wholeGuts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(_wholeGuts.isFastUTF8) { return try _wholeGuts.withFastUTF8(range: self._offsetRange) { return try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } }
apache-2.0
f6c6373854719f63d479e33ff5bb001e
28.956522
80
0.6627
4.532895
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/Nav/YepNavigationController.swift
1
2117
// // YepNavigationController.swift // Yep // // Created by kevinzhow on 15/5/27. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit final class YepNavigationController: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() interactivePopGestureRecognizer?.delegate = self delegate = self // self.navigationBar.changeBottomHairImage() } override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func pushViewController(viewController: UIViewController, animated: Bool) { if animated { interactivePopGestureRecognizer?.enabled = false } super.pushViewController(viewController, animated: animated) } override func popToRootViewControllerAnimated(animated: Bool) -> [UIViewController]? { if animated { interactivePopGestureRecognizer?.enabled = false } return super.popToRootViewControllerAnimated(animated) } override func popToViewController(viewController: UIViewController, animated: Bool) -> [UIViewController]? { if animated { interactivePopGestureRecognizer?.enabled = false } return super.popToViewController(viewController, animated: false) } func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { interactivePopGestureRecognizer?.enabled = true } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == interactivePopGestureRecognizer { if self.viewControllers.count < 2 || self.visibleViewController == self.viewControllers[0] { return false } } return true } }
mit
d611190ea0ac56e92de0e4897f2e1ed8
29.652174
149
0.677541
6.184211
false
false
false
false
DesenvolvimentoSwift/Taster
Taster/RecentFoodTableViewController.swift
1
3378
// // RecentFoodTableViewController.swift // pt.fca.Taster // // © 2016 Luis Marcelino e Catarina Silva // Desenvolvimento em Swift para iOS // FCA - Editora de Informática // import UIKit class RecentFoodTableViewController: UITableViewController { var recentFood = [Food]() override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UINib(nibName: "FoodTableViewCell", bundle: nil), forCellReuseIdentifier: "foodTableCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.recentFood = FoodRepository.repository.foodByDate() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return recentFood.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "foodTableCell", for: indexPath) as! FoodTableViewCell cell.food = recentFood[(indexPath as NSIndexPath).row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let food = recentFood[(indexPath as NSIndexPath).row] self.performSegue(withIdentifier: "foodDetailSegue", sender: food) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? FoodDetailViewController { if let food = sender as? Food { controller.food = food } } } }
mit
91848bb77fbd7bc6f7347c5f1c7ee351
32.76
158
0.664396
5.283255
false
false
false
false
zshowing/SwiftyTiledScrollView
TiledScrollView/TiledScrollView/TiledScrollView.swift
1
16024
// // TiledScrollView.swift // // Created by Shuo Zhang on 15/11/10. // Copyright © 2015年 Jon Showing, All rights reserved. // import UIKit public protocol TiledScrollViewDelegate{ } public protocol TiledScrollViewDataSource{ func tiledScrollView(_scrollView: TiledScrollView, tileForRow row: UInt, column: UInt, resolution: Int) -> UIView } public class TiledScrollView: UIScrollView, UIScrollViewDelegate { internal var totalTiles = 0 // we will recycle tiles by removing them from the view and storing them here internal var reusableTiles: Set<UIView> = Set<UIView>() internal var maximumResolution: Int = 0 internal var minimumResolution: Int = 0 // no rows or columns are visible at first; note this by making the firsts very high and the lasts very low internal var firstVisibleRow: UInt = UInt.max internal var firstVisibleColumn: UInt = UInt.max internal var lastVisibleRow: UInt = UInt.min internal var lastVisibleColumn: UInt = UInt.min internal var level: Int = 0 internal let tileContainerView: UIView = { // we need a tile container view to hold all the tiles. This is the view that is returned // in the -viewForZoomingInScrollView: delegate method, and it also detects taps. let tileContainerView = UIView.init(frame: CGRectZero) tileContainerView.backgroundColor = Color.MapBackgroundColor return tileContainerView }() public var tileSize: CGSize = CGSizeMake(Constants.MapViewTileSize, Constants.MapViewTileSize) public var mapSize: CGSize = CGSizeZero public var resolution: Int = 0 public var tiledScrollViewDelegate: TiledScrollViewDelegate? public var tiledScrollViewDataSource: TiledScrollViewDataSource? /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ public override required init(frame: CGRect) { super.init(frame: frame) self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.addSubview(tileContainerView) self.resetTiles() super.delegate = self } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.addSubview(tileContainerView) self.resetTiles() // the TiledScrollView is its own UIScrollViewDelegate, so we can handle our own zooming. // We need to return our tileContainerView as the view for zooming, and we also need to receive // the scrollViewDidEndZooming: delegate callback so we can update our resolution. super.delegate = self let singleTapGR: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:") singleTapGR.numberOfTapsRequired = 1 let doubleTapGR: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:") doubleTapGR.numberOfTapsRequired = 2 self.addGestureRecognizer(singleTapGR) self.addGestureRecognizer(doubleTapGR) } // MARK: - Public Methods public func reloadData(_contentSize: CGSize){ self.zoomScale = 1.0 self.minimumZoomScale = 1.0 self.maximumZoomScale = 1.0 self.resolution = 0 self.contentSize = _contentSize self.tileContainerView.frame = CGRectMake(0, 0, _contentSize.width, _contentSize.height) self.minimumResolution = { var w = _contentSize.width var h = _contentSize.height var res: Int = 0 while w > CGRectGetWidth(self.frame) && h > CGRectGetHeight(self.frame){ w = _contentSize.width * pow(CGFloat(2), CGFloat(--res)) h = _contentSize.height * pow(CGFloat(2), CGFloat(res)) } return ++res }() self.minimumZoomScale = max(CGRectGetWidth(self.frame) / _contentSize.width, CGRectGetHeight(self.frame) / _contentSize.height) self.zoomScale = self.minimumZoomScale self.contentOffset = CGPointMake((_contentSize.width * self.minimumZoomScale - CGRectGetWidth(self.frame)) / 2, (_contentSize.height * self.minimumZoomScale - CGRectGetHeight(self.frame)) / 2) self.updateResolution() } public func dequeueReusableTile() -> UIView?{ if let tile = reusableTiles.first{ reusableTiles.remove(tile) return tile } return nil } // MARK: - Tap Detecting Methods public func handleSingleTap(tapGR: UITapGestureRecognizer){ } public func handleDoubleTap(tapGR: UITapGestureRecognizer){ let tapPoint: CGPoint = tapGR.locationInView(tileContainerView) let newScale = self.zoomScale * CGFloat(Constants.DoubleTapZoomStep) let zoomRect = zoomRectForScale(newScale, center: tapPoint) self.zoomToRect(zoomRect, animated: true) } // MARK: - UIScrollView Delegate Overrides public func scrollViewDidZoom(scrollView: UIScrollView) { } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { } public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { self.updateResolution() } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { } public override func setZoomScale(scale: CGFloat, animated: Bool) { super.setZoomScale(scale, animated: animated) if !animated{ self.updateResolution() } } public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return tileContainerView } // MARK: - Update Overrides func resetTiles(){ autoreleasepool { () -> () in for view: UIView in tileContainerView.subviews{ reusableTiles.insert(view) view.removeFromSuperview() } } // no rows or columns are visible at first; note this by making the firsts very high and the lasts very low firstVisibleColumn = UInt.max firstVisibleRow = UInt.max lastVisibleColumn = UInt.min lastVisibleRow = UInt.min self.setNeedsLayout() } /***********************************************************************************/ /* Most of the work of tiling is done in layoutSubviews, which we override here. */ /* We recycle the tiles that are no longer in the visible bounds of the scrollView */ /* and we add any tiles that should now be present but are missing. */ /***********************************************************************************/ override public func layoutSubviews() { super.layoutSubviews() let visibleBounds = self.bounds // first recycle all tiles that are no longer visible for tile: UIView in tileContainerView.subviews{ // We want to see if the tiles intersect our (i.e. the scrollView's) bounds, so we need to convert their // frames to our own coordinate system let scaledTileFrame = tileContainerView.convertRect(tile.frame, toView: self) // If the tile doesn't intersect, it's not visible, so we can recycle it if !CGRectIntersectsRect(scaledTileFrame, visibleBounds){ reusableTiles.insert(tile) tile.removeFromSuperview() } } // calculate which rows and columns are visible by doing a bunch of math. let scaledTileWidth = tileSize.width * self.zoomScale let scaledTileHeight = tileSize.height * self.zoomScale // this is the maximum possible row let maxRow: UInt = UInt(floorf(Float(CGRectGetHeight(tileContainerView.frame) / scaledTileHeight))) // and the maximum possible column let maxCol: UInt = UInt(floorf(Float(CGRectGetWidth(tileContainerView.frame) / scaledTileWidth))) let firstNeededRow: UInt = max(UInt(0), UInt(floorf(Float(visibleBounds.origin.y / scaledTileHeight)))) let firstNeededCol: UInt = max(UInt(0), UInt(floorf(Float(visibleBounds.origin.x / scaledTileWidth)))) let lastNeededRow: UInt = min(maxRow, UInt(floorf(Float(CGRectGetMaxY(visibleBounds) / scaledTileHeight)))) let lastNeededCol: UInt = min(maxCol, UInt(floorf(Float(CGRectGetMaxX(visibleBounds) / scaledTileWidth)))) // iterate through needed rows and columns, adding any tiles that are missing for var row: UInt = firstNeededRow; row <= lastNeededRow; ++row{ for var col: UInt = firstNeededCol; col <= lastNeededCol; ++col{ autoreleasepool({ () -> () in let tileIsMissing = (firstVisibleRow > row || firstVisibleColumn > col || lastVisibleRow < row || lastVisibleColumn < col) if tileIsMissing{ let tile: UIView = tiledScrollViewDataSource?.tiledScrollView(self, tileForRow: row, column: col, resolution: resolution) ?? UIView(frame: CGRectZero) // set the tile's frame so we insert it at the correct position let frame = CGRectMake(tileSize.width * CGFloat(col), tileSize.height * CGFloat(row), tileSize.width, tileSize.height) tile.frame = frame tileContainerView.addSubview(tile) self.annotateTile(tile) } }) } } // update our record of which rows/cols are visible firstVisibleRow = firstNeededRow firstVisibleColumn = firstNeededCol lastVisibleRow = lastNeededRow lastVisibleColumn = lastNeededCol level = self.currentLevel() } /*****************************************************************************************/ /* The following method handles changing the resolution of our tiles when our zoomScale */ /* gets below 50% or above 100%. When we fall below 50%, we lower the resolution 1 step, */ /* and when we get above 100% we raise it 1 step. The resolution is stored as a power of */ /* 2, so -1 represents 50%, and 0 represents 100%, and so on. */ /*****************************************************************************************/ func updateResolution(){ // delta will store the number of steps we should change our resolution by. If we've fallen below // a 25% zoom scale, for example, we should lower our resolution by 2 steps so delta will equal -2. // (Provided that lowering our resolution 2 steps stays within the limit imposed by minimumResolution.) var delta: Int = 0 // check if we should decrease our resolution for var thisResolution: Int = self.minimumResolution; thisResolution < resolution; ++thisResolution{ let thisDelta = thisResolution - resolution // we decrease resolution by 1 step if the zoom scale is <= 0.5 (= 2^-1); by 2 steps if <= 0.25 (= 2^-2), and so on let scaleCutoff = powf(Float(2), Float(thisDelta)) if Float(self.zoomScale) <= scaleCutoff{ delta = thisDelta break } } // if we didn't decide to decrease the resolution, see if we should increase it if delta == 0{ for var thisResolutin = maximumResolution; thisResolutin > resolution; --thisResolutin{ let thisDelta = thisResolutin - resolution // we increase by 1 step if the zoom scale is > 1 (= 2^0); by 2 steps if > 2 (= 2^1), and so on let scaleCutoff = powf(Float(2), Float(thisDelta - 1)) if Float(self.zoomScale) > scaleCutoff{ delta = thisDelta break } } } if delta != 0 { resolution += delta // if we're increasing resolution by 1 step we'll multiply our zoomScale by 0.5; up 2 steps multiply by 0.25, etc // if we're decreasing resolution by 1 step we'll multiply our zoomScale by 2.0; down 2 steps by 4.0, etc let zoomFactor = powf(Float(2), Float(-1 * Int(delta))) // save content offset, content size, and tileContainer size so we can restore them when we're done // (contentSize is not equal to containerSize when the container is smaller than the frame of the scrollView.) let contentOffset = self.contentOffset let contentSize = self.contentSize let containerSize = self.tileContainerView.frame.size // adjust all zoom values (they double as we cut resolution in half) self.maximumZoomScale = self.maximumZoomScale * CGFloat(zoomFactor) self.minimumZoomScale = self.minimumZoomScale * CGFloat(zoomFactor) super.zoomScale = self.zoomScale * CGFloat(zoomFactor) // restore content offset, content size, and container size self.contentOffset = contentOffset self.contentSize = contentSize self.tileContainerView.frame = CGRectMake(0, 0, containerSize.width, containerSize.height) // throw out all tiles so they'll reload at the new resolution self.resetTiles() } } // MARK: - Utilities internal func annotateTile(_tile: UIView){ if let label = _tile.viewWithTag(Constants.MapViewAnnotationTag){ _tile.bringSubviewToFront(label) }else{ totalTiles += 1 let label = UILabel(frame: CGRectMake(5, 0, 80, 80)) label.backgroundColor = UIColor.clearColor() label.textColor = UIColor.greenColor() label.shadowColor = UIColor.grayColor() label.shadowOffset = CGSizeMake(1.0, 1.0) label.tag = Constants.MapViewAnnotationTag label.font = UIFont.boldSystemFontOfSize(40) label.text = "\(totalTiles)" _tile.addSubview(label) _tile.layer.borderColor = UIColor.greenColor().CGColor _tile.layer.borderWidth = 1.0 } } internal func currentLevel() -> Int{ let scale: CGFloat = self.zoomScale * CGFloat(pow(Double(2), Double(resolution))) if scale > 0.758{ return 0 }else if scale > 0.5{ return -1 }else if scale > 0.25{ return -2 } return -3 } internal func zoomRectForScale(_scale: CGFloat, center: CGPoint) -> CGRect{ var zoomRect: CGRect = CGRectZero // the zoom rect is in the content view's coordinates. // At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds. // As the zoom scale decreases, so more content is visible, the size of the rect grows. zoomRect.size.height = self.frame.size.height / _scale zoomRect.size.width = self.frame.size.width / _scale // choose an origin so as to get the right center. zoomRect.origin.x = center.x - zoomRect.size.width / 2 zoomRect.origin.y = center.y - zoomRect.size.height / 2 return zoomRect } }
mit
0569eee3a89cb31f82dcbf52781103b4
43.379501
200
0.608077
5.158081
false
false
false
false
bag-umbala/music-umbala
Music-Umbala/Music-Umbala/Controller/MusicViewController.swift
1
3532
// // MusicViewController.swift // Music-Umbala // // Created by Nam Nguyen on 5/16/17. // Copyright © 2017 Nam Vo. All rights reserved. // import UIKit class MusicViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating { // MARK: *** Data model // MARK: *** UI Elements @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var playlistView: UIView! @IBOutlet weak var songOfflineView: UIView! @IBOutlet weak var songOnlineView: UIView! @IBOutlet weak var searchBar: UISearchBar! var searchController: UISearchController = UISearchController(searchResultsController: nil) // MARK: *** UI events @IBAction func indexChanged(_ sender: UISegmentedControl) { searchBar.isHidden = true switch segmentedControl.selectedSegmentIndex { case 0: playlistView.isHidden = false songOfflineView.isHidden = true songOnlineView.isHidden = true case 1: playlistView.isHidden = true songOfflineView.isHidden = false songOnlineView.isHidden = true case 2: playlistView.isHidden = true songOfflineView.isHidden = true songOnlineView.isHidden = false default: break; } } @IBAction func search(_ sender: UIBarButtonItem) { print("search") searchBar.isHidden = false } // MARK: *** Local variables // MARK: *** UIViewController override func viewDidLoad() { super.viewDidLoad() searchController = UISearchController(searchResultsController: nil) // searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false // searchController.searchBar.scopeButtonTitles = ["title"] searchController.searchBar.delegate = self // searchController.hidesNavigationBarDuringPresentation = false // searchBar.delegate = self // tableview?.tableHeaderView = searchBar definesPresentationContext = true DB.createDBOrGetDBExist() playlistView.isHidden = false songOfflineView.isHidden = true songOnlineView.isHidden = true searchBar.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } @available(iOS 8.0, *) func updateSearchResults(for searchController: UISearchController) { let selectedIndex = searchBar.selectedScopeButtonIndex let searchString = searchBar.text ?? "" // filterContentForSearchText(searchString, scope: selectedIndex) // tableview?.reloadData() } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { let selectedIndex = searchBar.selectedScopeButtonIndex let searchString = searchBar.text ?? "" // filterContentForSearchText(searchString, scope: selectedIndex) // tableview?.reloadData() } }
mit
891fd2847fdb906f86bc82eb40461243
33.281553
106
0.659587
5.695161
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/CommonSource/InfoScreen/InfoScreenViewController.swift
1
6617
// // InfoScreenViewController.swift // AviasalesSDKTemplate // // Created by Dim on 14.07.17. // Copyright © 2017 Go Travel Un Limited. All rights reserved. // import UIKit import SafariServices class InfoScreenViewController: UIViewController, InfoScreenIconImageViewFiveTimesTapHandler { private let presenter = InfoScreenPresenter() @IBOutlet weak var containerView: UIView! @IBOutlet weak var tableView: UITableView! private let sender = HLEmailSender() var cellModels = [InfoScreenCellModelProtocol]() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupViewController() presenter.attach(self) } // MARK: - Setup func setupViewController() { automaticallyAdjustsScrollViewInsets = false setupTableView() setupUI() } func setupTableView() { tableView.backgroundColor = .white tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.tableFooterView = UIView(frame: .zero) tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: tabBarController?.tabBar.frame.height ?? 0, right: 0) } func setupUI() { view.backgroundColor = JRColorScheme.mainBackgroundColor() containerView.layer.cornerRadius = 6 navigationItem.backBarButtonItem = UIBarButtonItem.backBarButtonItem() } // MARK: - Navigation func showCurrencyPickerViewController() { let currencyPickerViewController = CurrencyPickerViewController { [weak self] in self?.presenter.update() } pushOrPresentBasedOnDeviceType(viewController: currencyPickerViewController, animated: true) } func openEmailSender(address: String) { sender.sendFeedbackEmail(to: address) present(sender.mailer, animated: true, completion: nil) } } private extension InfoScreenViewController { func buildAboutCell(cellModel: InfoScreenAboutCellModel) -> InfoScreenAboutCell { guard let cell = InfoScreenAboutCell.loadFromNib() else { fatalError("InfoScreenAboutCell has not been loaded") } cell.setup(cellModel: cellModel as InfoScreenAboutCellProtocol) let left: CGFloat = cellModel.separator ? tableView.separatorInset.left : view.bounds.width cell.separatorInset = UIEdgeInsets(top: 0, left: left, bottom: 0, right: 0) cell.iconImageViewFiveTimesTapAction = { [weak self] in self?.handleFiveTimesTap() } return cell } func buildRateCell(cellModel: InfoScreenRateCellModel) -> InfoScreenRateCell { guard let cell = InfoScreenRateCell.loadFromNib() else { fatalError("InfoScreenRateCell has not been loaded") } cell.setup(cellModel: cellModel as InfoScreenRateCellProtocol) { [weak self] (_) in self?.presenter.rate() } return cell } func buildDetailCell(cellModel: InfoScreenDetailCellModel) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.textLabel?.text = cellModel.title cell.textLabel?.textColor = JRColorScheme.darkTextColor() cell.detailTextLabel?.text = cellModel.subtitle cell.detailTextLabel?.textColor = JRColorScheme.mainColor() cell.accessoryType = .disclosureIndicator return cell } func buildBasicCell(cellModel: InfoScreenBasicCellModel) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = cellModel.title cell.textLabel?.textColor = JRColorScheme.darkTextColor() cell.accessoryType = .disclosureIndicator return cell } func buildExternalCell(cellModel: InfoScreenExtrnalCellModel) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = cellModel.name cell.textLabel?.textColor = JRColorScheme.darkTextColor() cell.accessoryType = .disclosureIndicator return cell } func buildVersionCell(cellModel: InfoScreenVersionCellModel) -> InfoScreenVersionCell { guard let cell = InfoScreenVersionCell.loadFromNib() else { fatalError("InfoScreenVersionCell has not been loaded") } cell.setup(cellModel: cellModel as InfoScreenVersionCellProtocol) cell.separatorInset = UIEdgeInsets(top: 0, left: view.bounds.width, bottom: 0, right: 0) return cell } } extension InfoScreenViewController: InfoScreenViewProtocol { func set(title: String) { navigationItem.title = title } func set(cellModels: [InfoScreenCellModelProtocol]) { self.cellModels = cellModels tableView.reloadData() } func open(url: URL) { present(SFSafariViewController(url: url), animated: true, completion: nil) } func showCurrencyPicker() { showCurrencyPickerViewController() } func sendEmail(address: String) { if HLEmailSender.canSendEmail() { openEmailSender(address: address) } else { HLEmailSender.showUnavailableAlert(in: self) } } } extension InfoScreenViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellModel = cellModels[indexPath.row] switch cellModel.type { case .about: return buildAboutCell(cellModel: cellModel as! InfoScreenAboutCellModel) case .rate: return buildRateCell(cellModel: cellModel as! InfoScreenRateCellModel) case .currency: return buildDetailCell(cellModel: cellModel as! InfoScreenDetailCellModel) case .email: return buildBasicCell(cellModel: cellModel as! InfoScreenBasicCellModel) case .external: return buildExternalCell(cellModel: cellModel as! InfoScreenExtrnalCellModel) case .version: return buildVersionCell(cellModel: cellModel as! InfoScreenVersionCellModel) } } } extension InfoScreenViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cellModel = cellModels[indexPath.row] presenter.select(cellModel: cellModel) } }
mit
0b9d3dae480dbe0b3575919c4b77b77e
34.005291
124
0.689389
5.027356
false
false
false
false
avaidyam/Parrot
Hangouts/Channel.swift
1
15054
import Foundation import HangoutsCore import ParrotServiceExtension import class Mocha.Logger private let log = Logger(subsystem: "Hangouts.Channel") public final class Channel : NSObject { // The prefix for any BrowserChannel endpoint. private static let URLPrefix = "https://0.client-channel.google.com/client-channel" private static let APIKey = "AIzaSyAfFJCeph-euFSwtmqFZi0kaKk-cZ5wufM" // Long-polling requests send heartbeats every 15 seconds, // so if we miss two in a row, consider the connection dead. private static let connectTimeout = 30 private static let pushTimeout = 30 private static let maxBytesRead = 1024 * 1024 private static let maxRetries = 5 // NotificationCenter notification and userInfo keys. internal static let didConnectNotification = Notification.Name(rawValue: "Hangouts.Channel.DidConnect") internal static let didDisconnectNotification = Notification.Name(rawValue: "Hangouts.Channel.DidDisconnect") internal static let didReceiveMessageNotification = Notification.Name(rawValue: "Hangouts.Channel.ReceiveMessage") internal static let didReceiveMessageKey = "Hangouts.Channel.ReceiveMessage.Key" // Parse data from the backward channel into chunks. // Responses from the backward channel consist of a sequence of chunks which // are streamed to the client. Each chunk is prefixed with its length, // followed by a newline. The length allows the client to identify when the // entire chunk has been received. internal class ChunkParser { internal var buf = NSMutableData() // Yield submissions generated from received data. // Responses from the push endpoint consist of a sequence of submissions. // Each submission is prefixed with its length followed by a newline. // The buffer may not be decodable as UTF-8 if there's a split multi-byte // character at the end. To handle this, do a "best effort" decode of the // buffer to decode as much of it as possible. // The length is actually the length of the string as reported by // JavaScript. JavaScript's string length function returns the number of // code units in the string, represented in UTF-16. We can emulate this by // encoding everything in UTF-16 and multipling the reported length by 2. // Note that when encoding a string in UTF-16, Python will prepend a // byte-order character, so we need to remove the first two bytes. internal func getChunks(newBytes: Data) -> [String] { buf.append(newBytes) var submissions = [String]() while buf.length > 0 { if let decoded = bestEffortDecode(data: buf) { let bufUTF16 = decoded.data(using: String.Encoding.utf16BigEndian)! let decodedUtf16LengthInChars = bufUTF16.count / 2 let lengths = decoded.findAllOccurrences(matching: "([0-9]+)\n", all: true) if let lengthStr = lengths.first { //lengthStr.endIndex.advancedBy(n: -1) let lengthStrWithoutNewline = lengthStr[..<lengthStr.index(lengthStr.endIndex, offsetBy: -1)] if let length = Int(lengthStrWithoutNewline) { if (decodedUtf16LengthInChars - lengthStr.utf16.count) < length { break } let subData = bufUTF16.subdata(in: Range(NSMakeRange(lengthStr.utf16.count * 2, length * 2))!) let submission = NSString(data: subData, encoding: String.Encoding.utf16BigEndian.rawValue)! as String submissions.append(submission) let submissionAsUTF8 = submission.data(using: String.Encoding.utf8)! let removeRange = NSMakeRange(0, (lengthStr.utf16.count + submissionAsUTF8.count)) buf.replaceBytes(in: removeRange, withBytes: nil, length: 0) } else { break } } else { break } } } return submissions } // Decode data into a string using UTF-8. // If data cannot be decoded, pop the last byte until it can be or // return an empty string. private func bestEffortDecode(data: NSMutableData) -> String? { for i in 0 ..< data.length { if let s = NSString(data: data.subdata(with: NSMakeRange(0, (data.length - i))), encoding: String.Encoding.utf8.rawValue) { return s as String } } return nil } } // For use in Client: internal var session = URLSession() internal var proxy = URLSessionDelegateProxy() internal var queue = DispatchQueue(label: "Hangouts.Channel", qos: .userInitiated) internal var isConnected = false internal var onConnectCalled = false private var chunkParser: ChunkParser? = nil private var sidParam: String? = nil private var gSessionIDParam: String? = nil private var retries = Channel.maxRetries private var needsSID = true // NOTE: getCookieValue causes a CFNetwork leak repeatedly. internal lazy var cachedSAPISID: String = { Channel.getCookieValue(key: "SAPISID")! }() public init(configuration: URLSessionConfiguration) { super.init() session = URLSession(configuration: configuration, delegate: self.proxy, delegateQueue: nil) } // Listen for messages on the backwards channel. // This method only returns when the connection has been closed due to an error. public func listen() { func _firstListen() { log.debug("cleaned chunk parser and starting request...") // Clear any previous push data, since if there was an error it could contain garbage. self.chunkParser = ChunkParser() self.longPollRequest() } log.debug("listen invoked! needs SID? \(self.needsSID)") self.queue.async { // Request a new SID if we don't have one yet, or the previous one became invalid. if self.needsSID { self.fetchChannelSID { _firstListen() self.needsSID = false } } else { _firstListen() } } } // Creates a new channel for receiving push data. // There's a separate API to get the gsessionid alone that Hangouts for // Chrome uses, but if we don't send a gsessionid with this request, it // will return a gsessionid as well as the SID. private func fetchChannelSID(cb: (() -> Void)? = nil) { self.sidParam = nil self.gSessionIDParam = nil log.debug("sending maps...") self.sendMaps { let r = Channel.parseSIDResponse(res: $0) log.debug("received response \(r)") self.sidParam = r.sid self.gSessionIDParam = r.gSessionID cb?() } } // Sends a request to the server containing maps (dicts). public func sendMaps(_ mapList: [[String: Any]]? = nil, cb: ((Data) -> Void)? = nil) { var params = [ "VER": 8, // channel protocol version "RID": 81188, // request identifier "ctype": "hangouts", // client type ] as [String : Any] if self.gSessionIDParam != nil { params["gsessionid"] = self.gSessionIDParam! } if self.sidParam != nil { params["SID"] = self.sidParam! } var dataDict = [ "count": mapList?.count ?? 0, "ofs": 0 ] as [String: Any] if let mapList = mapList { for (mapNum, map_) in mapList.enumerated() { for (mapKey, mapVal) in map_ { dataDict["req\(mapNum)_\(mapKey)"] = mapVal } } } let url = "\(Channel.URLPrefix)/channel/bind?\(params.encodeURL())" var request = URLRequest(url: URL(string: url)!) request.httpMethod = "POST" /* TODO: Clearly, we shouldn't call encodeURL(), but what do we do? */ request.httpBody = dataDict.encodeURL().data(using: String.Encoding.utf8, allowLossyConversion: false)! for (k, v) in Channel.getAuthorizationHeaders(self.cachedSAPISID) { request.setValue(v, forHTTPHeaderField: k) } log.debug("maps about to go out!") // If the network is not connected at the time this request is made, // then the internal SPI logs: `[57] Socket not connected` without // erroring up here. Therefore, you should always wait until the network // is connected or queue it. self.session.request(request: request) { guard let data = $0.data else { log.error("(maps) Request failed with error: \($0.error!)") return } log.debug("maps succeeded!") cb?(data) } } // Open a long-polling request and receive push data. // This method uses keep-alive to make re-opening the request faster, but // the remote server will set the "Connection: close" header once an hour. private func longPollRequest() { let params: [String: Any] = [ "VER": 8, // channel protocol version "gsessionid": self.gSessionIDParam ?? "", "RID": "rpc", // request identifier "t": 1, // trial "SID": self.sidParam ?? "", // session ID "CI": 0, // 0 if streaming/chunked requests should be used "ctype": "hangouts", // client type "TYPE": "xmlhttp", // type of request ] let url = "\(Channel.URLPrefix)/channel/bind?\(params.encodeURL())" var request = URLRequest(url: URL(string: url)!) request.timeoutInterval = Double(Channel.connectTimeout) for (k, v) in Channel.getAuthorizationHeaders(self.cachedSAPISID) { request.setValue(v, forHTTPHeaderField: k) } log.debug("request val: \(request)") self.task = self.session.dataTask(with: request) let p = URLSessionDataDelegateProxy() p.didReceiveData = { _,_,data in self.queue.async { self.onPushData(data: data) } } p.didComplete = { [weak self] _,t,error in guard let r = t.response as? HTTPURLResponse else { log.error("Received no response...") self?.disconnect() return } if r.statusCode >= 400 { log.error("Request failed with: \(String(describing: error))") self?.disconnect() } else if r.statusCode == 200 { log.debug("200 OK: restart long-poll") self?.longPollRequest() } else { log.error("Received unknown response code \(r.statusCode)") self?.disconnect() } } self.proxy[self.task!] = p self.task?.resume() } private var task: URLSessionDataTask? = nil public func disconnect() { self.task?.cancel() self.proxy[self.task!] = nil if self.isConnected { self.isConnected = false hangoutsCenter.post(name: Channel.didDisconnectNotification, object: self) } self.needsSID = true } // Delay subscribing until first byte is received prevent "channel not // ready" errors that appear to be caused by a race condition on the server. private func onPushData(data: Data) { for chunk in (self.chunkParser?.getChunks(newBytes: data))! { // This method is only called when the long-polling request was // successful, so use it to trigger connection events if necessary. if !self.isConnected { if self.onConnectCalled { self.isConnected = true hangoutsCenter .post(name: Channel.didConnectNotification, object: self) } else { self.onConnectCalled = true self.isConnected = true hangoutsCenter .post(name: Channel.didConnectNotification, object: self) } } if let json = try? chunk.decodeJSON(), let container = json as? [Any] { for inner in container { //let arrayId = inner[0] if let _inner = inner as? [Any], let array = _inner[1] as? [Any] { hangoutsCenter .post(name: Channel.didReceiveMessageNotification, object: self, userInfo: [Channel.didReceiveMessageKey: array]) } } } } } // Send a Protocol Buffer or JSON formatted chat API request. // endpoint is the chat API endpoint to use. // requestPb: The request body as a Protocol Buffer message. // responsePb: The response body as a Protocol Buffer message. // Valid formats are: 'json' (JSON), 'protojson' (pblite), and 'proto' // (binary Protocol Buffer). 'proto' requires manually setting an extra // header 'X-Goog-Encode-Response-If-Executable: base64'. internal func baseRequest( path: String, contentType: String = "application/json+protobuf", data: Data, useJson: Bool = true, cb: @escaping (Result) -> Void) { let params = ["alt": useJson ? "json" : "protojson"] let url = URL(string: (path + "?key=" + Channel.APIKey + "&" + params.encodeURL()))! let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.httpBody = data for (k, v) in Channel.getAuthorizationHeaders(self.cachedSAPISID) { request.setValue(v, forHTTPHeaderField: k) } request.setValue(contentType, forHTTPHeaderField: "Content-Type") self.session.request(request: request as URLRequest) { guard let _ = $0.data else { log.error("Request failed with error: \($0.error!)") return } cb($0) } } // Get the cookie value of the key given from the NSHTTPCookieStorage. internal class func getCookieValue(key: String) -> String? { if let c = HTTPCookieStorage.shared.cookies { if let match = (c.filter { ($0 as HTTPCookie).name == key && ($0 as HTTPCookie).domain == ".google.com" }).first { return match.value } } return nil } // Parse response format for request for new channel SID. // Example format (after parsing JS): // [ [0,["c","SID_HERE","",8]], // [1,[{"gsid":"GSESSIONID_HERE"}]]] internal class func parseSIDResponse(res: Data) -> (sid: String, gSessionID: String) { if let firstSubmission = Channel.ChunkParser().getChunks(newBytes: res).first { log.debug("chunk parsing...") let val = PBLiteDecoder.sanitize(firstSubmission)! let sid = ((val[0] as! NSArray)[1] as! NSArray)[1] as! String let gSessionID = (((val[1] as! NSArray)[1] as! NSArray)[0] as! NSDictionary)["gsid"]! as! String return (sid, gSessionID) } return ("", "") } // Return authorization headers for API request. It doesn't seem to matter // what the url and time are as long as they are consistent. // SAPISID = Secure API Session Identifier ? public static func getAuthorizationHeaders(_ sapisidCookie: String, origin: String = "https://talkgadget.google.com", extras: [String: String] = [:]) -> [String: String] { func sha1(_ source: String) -> String { let str = Array(source.utf8).map { UInt8($0) } // Int8 //var store = [Int8](repeating: 0, count: 20) //SHA1(&store, str, Int32(str.count)) let store = SHA1().calculate(for: str) return store.map { String(format: "%02hhx", $0) }.joined(separator: "") } let timeMsec = Int(Date().timeIntervalSince1970 * 1000) let authString = "\(timeMsec) \(sapisidCookie) \(origin)" let authHash = sha1(authString) let sapisidHash = "SAPISIDHASH \(timeMsec)_\(authHash)" return [ "Authorization": sapisidHash, "X-Origin": origin, "X-Goog-AuthUser": "0", ].merging(extras) { a, _ in a } } }
mpl-2.0
89f787d17a65de5e245de39ba941ed18
36.729323
127
0.650857
3.823724
false
false
false
false
tardieu/swift
test/SILGen/existential_erasure.swift
1
4656
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s protocol P { func downgrade(_ m68k: Bool) -> Self func upgrade() throws -> Self } protocol Q {} struct X: P, Q { func downgrade(_ m68k: Bool) -> X { return self } func upgrade() throws -> X { return self } } func makePQ() -> P & Q { return X() } func useP(_ x: P) { } func throwingFunc() throws -> Bool { return true } // CHECK-LABEL: sil hidden @_T019existential_erasure5PQtoPyyF : $@convention(thin) () -> () { func PQtoP() { // CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]] // CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]] // CHECK: copy_addr [take] [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]] // CHECK: deinit_existential_addr [[PQ]] // CHECK-NOT: destroy_addr [[P]] // CHECK-NOT: destroy_addr [[P_PAYLOAD]] // CHECK-NOT: destroy_addr [[PQ]] // CHECK-NOT: destroy_addr [[PQ_PAYLOAD]] useP(makePQ()) } // Make sure uninitialized existentials are properly deallocated when we // have an early return. // CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP1yAA1P_pKF func openExistentialToP1(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1 : {{.*}}, [[OPEN]] // CHECK: [[FUNC:%.*]] = function_ref @_T019existential_erasure12throwingFuncSbyKF // CHECK: try_apply [[FUNC]]() // // CHECK: bb1([[SUCCESS:%.*]] : $Bool): // CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]]) // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.downgrade(throwingFunc())) } // CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP2yAA1P_pKF func openExistentialToP2(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1 : {{.*}}, [[OPEN]] // CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]]: $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.upgrade()) } // Same as above but for boxed existentials extension Error { func returnOrThrowSelf() throws -> Self { throw self } } // CHECK-LABEL: sil hidden @_T019existential_erasure12errorHandlers5Error_psAC_pKF func errorHandler(_ e: Error) throws -> Error { // CHECK: bb0(%0 : $Error): // CHECK: debug_value %0 : $Error // CHECK: [[OPEN:%.*]] = open_existential_box %0 : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]] // CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error // CHECK: [[FUNC:%.*]] = function_ref @_T0s5ErrorP19existential_erasureE17returnOrThrowSelf{{[_0-9a-zA-Z]*}}F // CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: destroy_value %0 : $Error // CHECK: return [[RESULT]] : $Error // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: dealloc_existential_box [[RESULT]] // CHECK: destroy_value %0 : $Error // CHECK: throw [[FAILURE]] : $Error // return try e.returnOrThrowSelf() } // rdar://problem/22003864 -- SIL verifier crash when init_existential_addr // references dynamic Self type class EraseDynamicSelf { required init() {} // CHECK-LABEL: sil hidden @_T019existential_erasure16EraseDynamicSelfC7factoryACXDyFZ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf // CHECK: [[ANY:%.*]] = alloc_stack $Any // CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf // class func factory() -> Self { let instance = self.init() let _: Any = instance return instance } }
apache-2.0
7c5bf50943e0b2ff5fac495b09c5074d
33.746269
167
0.61512
3.262789
false
false
false
false
Mazy-ma/DemoBySwift
PullToRefresh/PullToRefresh/PullToRefresh/RefreshBaseView.swift
1
6098
// // RefreshBaseView.swift // PullToRefresh // // Created by Mazy on 2017/12/5. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit //控件的刷新状态 enum RefreshState { case normal // 普通状态 case pulling // 松开就可以进行刷新的状态 case refreshing // 正在刷新中的状态 case willRefreshing // 将要刷新的状态 case refreshingNoData // 无数据刷新的状态 } //控件的类型 enum RefreshViewType { case header // 头部控件 case footer // 尾部控件 } class RefreshBaseView: UIView { // MARK: =========================定义属性============================= // 刷新回调的闭包 typealias beginRefreshingClosure = ()->Void // 父控件 var scrollView: UIScrollView! var scrollViewOriginalInset: UIEdgeInsets! // 箭头图片 var arrowImage: UIImageView! // 菊花 var indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) // 无更多视图 Label var noMoreLabel: UILabel! // 刷新后回调 var beginRefreshingCallback: beginRefreshingClosure? // 交给子类去实现和调用 var oldState: RefreshState? // 当状态改变时设置状态(State)就会调用这个方法 var State : RefreshState = .normal { willSet { self.State = newValue } didSet { guard self.State != self.oldState else { return } switch self.State { // 普通状态时 隐藏那个菊花 case .normal: arrowImage.isHidden = false indicatorView.stopAnimating() // 释放刷新状态 case .pulling: break; // 正在刷新状态 1隐藏箭头 2显示菊花 3回调 case .refreshing: arrowImage.isHidden = true indicatorView.startAnimating() if let refreshingCallback = self.beginRefreshingCallback { refreshingCallback() } case .refreshingNoData: arrowImage.isHidden = true indicatorView.stopAnimating() indicatorView.isHidden = true default : break; } } } // MARK: =========================定义方法=========================== override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white // 初始化箭头 self.arrowImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) self.arrowImage.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] self.arrowImage.image = UIImage(named: "RefreshSource.bundle/refresh_arrow.png") self.arrowImage.contentMode = .center self.arrowImage.tag = 500 self.addSubview(arrowImage) // 添加菊花视图 self.addSubview(indicatorView) noMoreLabel = UILabel() noMoreLabel.text = "————— 我是有底线的 —————" noMoreLabel.font = UIFont.systemFont(ofSize: 10) noMoreLabel.textAlignment = .center noMoreLabel.textColor = .lightGray noMoreLabel.sizeToFit() noMoreLabel.isHidden = true self.addSubview(noMoreLabel) // self.autoresizingMask = .flexibleWidth } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // 设置箭头和菊花居中 arrowImage.center = CGPoint(x: self.width / 2, y: self.height / 2) indicatorView.center = CGPoint(x: self.width / 2, y: self.height / 2) noMoreLabel.center = CGPoint(x: self.width / 2, y: self.height / 2) } //显示到屏幕上 override func draw(_ rect: CGRect) { superview?.draw(rect); if self.State == .willRefreshing { self.State = .refreshing } } // MARK: ==============================让子类去重写======================= override func willMove(toSuperview newSuperview: UIView!) { super.willMove(toSuperview: newSuperview) // 移走旧的父控件 if let _superView = self.superview { _superView.removeObserver(self, forKeyPath: RefreshContentOffset) } // 新的父控件 添加监听器 newSuperview.addObserver(self, forKeyPath: RefreshContentOffset, options: .new, context: nil) var rect: CGRect = self.frame // 设置宽度 位置 rect.size.width = newSuperview.frame.size.width rect.origin.x = 0 self.frame = frame // UIScrollView scrollView = newSuperview as! UIScrollView scrollViewOriginalInset = scrollView.contentInset } // 判断是否正在刷新 func isRefreshing()->Bool{ return self.State == .refreshing } // 开始刷新 func beginRefreshing(){ if (self.window != nil) { self.State = .refreshing } else { //不能调用set方法 State = .willRefreshing super.setNeedsDisplay() } } // 结束刷新 func endRefreshing(){ if self.State == .normal { return } noMoreLabel.isHidden = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + RefreshSlowAnimationDuration) { self.State = .normal } } // 结束刷新并提示无数据 func endRefreshingWithNoMoreData() { if self.State == .refreshingNoData { return } noMoreLabel.isHidden = false indicatorView.isHidden = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + RefreshSlowAnimationDuration) { self.State = .refreshingNoData } } }
apache-2.0
e773d12aa49cc2bd24004833909b0bdd
28.219895
101
0.556531
4.827855
false
false
false
false
JaySonGD/SwiftDayToDay
导航2/导航2/ViewController.swift
1
3370
// // ViewController.swift // 导航2 // // Created by czljcb on 16/3/12. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController { // MARK: - 属性 lazy var coder : CLGeocoder = CLGeocoder() @IBOutlet weak var mapView: MKMapView! // ******************************************************************************************************** // MARK: - < 系统回调方法 > override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. coder.geocodeAddressString("广州") { (clps: [CLPlacemark]?,error: NSError?) -> Void in let gzls = clps?.first self.coder.geocodeAddressString("深圳") { (clps: [CLPlacemark]?,error: NSError?) -> Void in let szls = clps?.first self.getDirection(gzls!, end: szls!) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let circle = MKCircle(centerCoordinate: mapView.centerCoordinate, radius: 1000000) mapView.addOverlay(circle) } // ******************************************************************************************************** // MARK: - < 自定方法 > func getDirection(start: CLPlacemark , end: CLPlacemark){ let startPlaceMark = MKPlacemark(placemark: start) let startItem = MKMapItem(placemark:startPlaceMark) let endPlaceMark = MKPlacemark(placemark: end) let endItem = MKMapItem(placemark:endPlaceMark) let request = MKDirectionsRequest() request.source = startItem request.destination = endItem let direction = MKDirections(request: request) direction.calculateDirectionsWithCompletionHandler({ (response: MKDirectionsResponse?,error: NSError?) -> Void in print("----",response) for route in (response?.routes)!{ print(route.name) self.mapView.addOverlay(route.polyline) for step in route.steps{ print(step.instructions) } } }) } } // MARK: - MKMapViewDelegate extension ViewController: MKMapViewDelegate{ func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay.isKindOfClass(MKCircle.self){ let overlayView = MKCircleRenderer(overlay: overlay) overlayView.lineWidth = 2.0 overlayView.fillColor = UIColor.orangeColor() return overlayView } else { let overlayView = MKPolylineRenderer(overlay: overlay) overlayView.lineWidth = 2.0 overlayView.strokeColor = UIColor.orangeColor() return overlayView } } }
mit
1ac93ce4164803f8999b837363322364
28.477876
121
0.518463
5.772964
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwift/convnet-swift/Vol.swift
1
4732
// Vol is the basic building block of all data in a net. // it is essentially just a 3D volume of numbers, with a // width (sx), height (sy), and depth (depth). // it is used to hold data for all filters, all volumes, // all weights, and also stores all gradients w.r.t. // the data. c is optionally a value to initialize the volume // with. If c is missing, fills the Vol with random numbers. import Foundation class Vol { var sx: Int = 1 var sy: Int = 1 var depth: Int = 0 var w: [Double] = [] var dw: [Double] = [] convenience init (array: [Double]) { self.init() // we were given a list in sx, assume 1D volume and fill it up sx = 1 sy = 1 depth = array.count // we have to do the following copy because we want to use // fast typed arrays, not an ordinary javascript array w = ArrayUtils.zerosDouble(depth) dw = ArrayUtils.zerosDouble(depth) for i in 0 ..< depth { w[i] = array[i] } } convenience init(width sx: Int, height sy: Int, depth: Int, array: [Double]) { self.init() assert(array.count==sx*sy*depth) self.sx = sx self.sy = sy self.depth = depth w = array } convenience init(sx: Int, sy: Int, depth: Int) { self.init(width: sx, height: sy, depth: depth, c: nil) } convenience init(sx: Int, sy: Int, depth: Int, c: Double) { self.init(width: sx, height: sy, depth: depth, c: c) } convenience init(width sx: Int, height sy: Int, depth: Int, c: Double?) { self.init() // we were given dimensions of the vol self.sx = sx self.sy = sy self.depth = depth let n = sx*sy*depth w = ArrayUtils.zerosDouble(n) dw = ArrayUtils.zerosDouble(n) if c == nil { // weight normalization is done to equalize the output // variance of every neuron, otherwise neurons with a lot // of incoming connections have outputs of larger variance let scale = sqrt(1.0/Double(sx*sy*depth)) for i in 0 ..< n { w[i] = RandUtils.randn(0.0, std: scale) } } else { for i in 0 ..< n { w[i] = c! } } } func get(x: Int, y: Int, d: Int) -> Double { let ix=((sx * y)+x)*depth+d return w[ix] } func set(x: Int, y: Int, d: Int, v: Double) -> () { let ix=((sx * y)+x)*depth+d w[ix] = v } func add(x: Int, y: Int, d: Int, v: Double) -> () { let ix=((sx * y)+x)*depth+d w[ix] += v } func getGrad(x: Int, y: Int, d: Int) -> Double { let ix = ((sx * y)+x)*depth+d return dw[ix] } func setGrad(x: Int, y: Int, d: Int, v: Double) -> () { let ix = ((sx * y)+x)*depth+d dw[ix] = v } func addGrad(x: Int, y: Int, d: Int, v: Double) -> () { let ix = ((sx * y)+x)*depth+d dw[ix] += v } func cloneAndZero() -> Vol { return Vol(sx: sx, sy: sy, depth: depth, c: 0.0) } func clone() -> Vol { let V = Vol(sx: sx, sy: sy, depth: depth, c: 0.0) let n = w.count for i in 0 ..< n { V.w[i] = w[i] } return V } func addFrom(_ V: Vol) { for k in 0 ..< w.count { w[k] += V.w[k] } } func addFromScaled(_ V: Vol, a: Double) { for k in 0 ..< w.count { w[k] += a*V.w[k] } } func setConst(_ a: Double) { for k in 0 ..< w.count { w[k] = a } } func toJSON() -> [String: AnyObject] { // TODO: we may want to only save d most significant digits to save space var json: [String: AnyObject] = [:] json["sx"] = sx as AnyObject? json["sy"] = sy as AnyObject? json["depth"] = depth as AnyObject? json["w"] = w as AnyObject? return json // we wont back up gradients to save space } // func fromJSON(json: [String: AnyObject]) -> () { // sx = json["sx"] // sy = json["sy"] // depth = json["depth"] // // var n = sx*sy*depth // w = zeros(n) // dw = zeros(n) // // copy over the elements. // for i in 0 ..< n { // // w[i] = json["w"][i] // } // } func description() -> String { return "size: \(sx)*\(sy)*\(depth)\nw:\n\(w)\ndw:\n\(dw)" } func debugDescription() -> String { return "size: \(sx)*\(sy)*\(depth)\nw:\n\(w)\ndw:\n\(dw)" } }
mit
dcbc5c5f2420b55ef7a0eadc6cf4bb99
26.511628
82
0.479079
3.424023
false
false
false
false
almazrafi/Metatron
Sources/Types/MemoryStream.swift
1
5526
// // MemoryStream.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 class MemoryStream: Stream { // MARK: Instance Properties public private(set) var data: [UInt8] // MARK: public private(set) var isReadable: Bool public private(set) var isWritable: Bool public var isOpen: Bool { return (self.isReadable || self.isWritable) } // MARK: public private(set) var offset: UInt64 public var length: UInt64 { return UInt64(data.count) } // MARK: Initializers public init(data: [UInt8] = []) { self.data = data self.isReadable = false self.isWritable = false self.offset = 0 } // MARK: Instance Methods @discardableResult public func openForReading() -> Bool { guard !self.isOpen else { return false } self.isReadable = true self.isWritable = false self.offset = 0 return true } @discardableResult public func openForUpdating(truncate: Bool) -> Bool { guard !self.isOpen else { return false } if truncate { self.data.removeAll() } self.isReadable = true self.isWritable = true self.offset = 0 return true } @discardableResult public func openForWriting(truncate: Bool) -> Bool { guard !self.isOpen else { return false } if truncate { self.data.removeAll() } self.isReadable = false self.isWritable = true self.offset = 0 return true } public func synchronize() { } public func close() { self.isReadable = false self.isWritable = false self.offset = 0 } // MARK: @discardableResult public func seek(offset: UInt64) -> Bool { guard self.isOpen else { return false } guard offset <= self.length else { return false } self.offset = offset return true } public func read(maxLength: Int) -> [UInt8] { guard self.isReadable && (maxLength > 0) else { return [] } let data = [UInt8](self.data.suffix(from: Int(self.offset)).prefix(maxLength)) self.offset += UInt64(data.count) return data } @discardableResult public func write(data: [UInt8]) -> Int { guard self.isWritable && (data.count > 0) else { return 0 } let offset = Int(self.offset) let margin = self.data.count - offset if margin < data.count { let dataLength = min(Int.max - offset, data.count) for i in 0..<margin { self.data[offset + i] = data[i] } for i in margin..<dataLength { self.data.append(data[i]) } self.offset = UInt64(self.data.count) return dataLength } else { for i in 0..<data.count { self.data[offset + i] = data[i] } self.offset += UInt64(data.count) return data.count } } @discardableResult public func truncate(length: UInt64) -> Bool { guard self.isWritable else { return false } guard length < self.length else { return false } if self.offset > length { self.offset = length } self.data = [UInt8](self.data.prefix(Int(length))) return true } @discardableResult public func insert(data: [UInt8]) -> Bool { guard self.isReadable && self.isWritable else { return false } guard Int.max - self.data.count >= data.count else { return false } guard data.count > 0 else { return true } self.data.insert(contentsOf: data, at: Int(self.offset)) self.offset += UInt64(data.count) return true } @discardableResult public func remove(length: UInt64) -> Bool { guard self.isReadable && self.isWritable && (length <= self.length - self.offset) else { return false } guard length > 0 else { return true } self.data.removeSubrange(Int(self.offset)..<Int(self.offset + length)) return true } }
mit
6fa5c40fc68be83ca4edf5cceaadfe09
21.929461
96
0.580347
4.392687
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/Business/Scheduling/ActiveLifeScheduleCalculator.swift
1
5900
// // ActiveLifeScheduleCalculator.swift // YourGoals // // Created by André Claaßen on 29.06.19. // Copyright © 2019 André Claaßen. All rights reserved. // import Foundation extension ActionableTimeInfo { /// create a actionable time info from a task progress record /// /// - Parameters: /// - day: calculate the values for this day /// - actionable: the actionable /// - progress: the progress of the actionable init(day: Date, actionable: Actionable, progress: TaskProgress ) { self.startingTime = progress.startOfDay(day: day) self.endingTime = progress.endOfDay(day: day) self.estimatedLength = self.endingTime.timeIntervalSince(self.startingTime) self.conflicting = false self.fixedStartingTime = false self.actionable = actionable self.progress = progress } } extension Actionable { /// fetch all done progress items fromt the task and create time infos out of them /// /// - Parameters: /// - actionable: the task /// - day: the day /// - Returns: an array of time infos from the done task progress records func timeInfosFromDoneProgress(forDay day:Date) -> [ActionableTimeInfo] { guard let task = self as? Task else { return [] } let day = day.day() let timeInfos = task .progressFor(day: day) .filter{ $0.state == .done } .map{ ActionableTimeInfo(day: day, actionable: self, progress: $0) } .sorted { $0.startingTime.compare($1.startingTime) == .orderedAscending } return timeInfos } } /// class for calculating starting times for the active life view class ActiveLifeScheduleCalculator:StorageManagerWorker { /// calculate the correct starting time for an actionable /// /// - Parameters: /// - time: actual system time /// - actionable: the actionable /// - Returns: the starting time func calculateStartingTime(forTime time:Date, actionable: Actionable) -> Date { if let task = actionable as? Task, let progress = task.progressFor(date: time), let progressStart = progress.start { return progressStart } if let beginTime = actionable.beginTime { return beginTime } return time } /// calculate the starting times relative to the given time for the actionables in a way similar to active life /// /// - Parameters: /// - time: start time for all actionalbes /// - actionables: the actinalbes /// - Returns: array with associated starting ties /// - Throws: core data exception func calculateTimeInfoForActiveLife(forTime time: Date, actionables:[Actionable]) throws -> [ActionableTimeInfo] { assert(actionables.first(where: { $0.type == .habit}) == nil, "there only tasks allowed") var timeInfos = [ActionableTimeInfo]() var startingTimeOfTask = time for actionable in actionables { let task = actionable as! Task timeInfos.append(contentsOf: actionable.timeInfosFromDoneProgress(forDay: time)) // if this actionable is done, leave the loop if actionable.checkedState(forDate: time) == .done { // let timeInfo = ActionableTimeInfo(start: actionable.) if let doneDate = task.doneDate { let timeInfo = ActionableTimeInfo(start: doneDate, end: doneDate, remainingTimeInterval: 0, conflicting: false, fixed: false, actionable: task) timeInfos.append(timeInfo) } else { NSLog("warning: no done date set in done task: \(task)") } continue } // calculate next starting time of done items startingTimeOfTask = timeInfos.reduce(startingTimeOfTask) { let nextStartingTime = $1.endingTime // start is one second later than ending return $0.compare(nextStartingTime) == .orderedAscending ? nextStartingTime: $0 } let startingTimeForActionable = calculateStartingTime(forTime: startingTimeOfTask, actionable: actionable) let conflicting = startingTimeForActionable.compare(startingTimeOfTask) == .orderedAscending let fixed = actionable.beginTime != nil let remainingTime = actionable.calcRemainingTimeInterval(atDate: startingTimeForActionable) let endingTimeForTask = startingTimeForActionable.addingTimeInterval(remainingTime) let timeInfo = ActionableTimeInfo(start: startingTimeForActionable, end: endingTimeForTask, remainingTimeInterval: remainingTime, conflicting: conflicting, fixed: fixed, actionable: actionable) timeInfos.append(timeInfo) startingTimeOfTask = endingTimeForTask } return timeInfos } /// calculate the start time for the longest active task /// /// - Parameter time: new starting times /// - Returns: a starting time relative to the longest remaining active task /// - Throws: a core data exception func calcStartTimeRelativeToActiveTasks(forTime time: Date) throws -> Date { let activeTasks = try TaskProgressManager(manager: self.manager).activeTasks(forDate: time) let maximalRemainingTime = activeTasks.reduce(TimeInterval(0.0)) { n, task in let remainingTime = task.calcRemainingTimeInterval(atDate: time) return n > remainingTime ? n: remainingTime } let startTime = time.addingTimeInterval(maximalRemainingTime) return startTime } }
lgpl-3.0
b2140a5c9191c9e1e849fd9957943a45
40.514085
163
0.625276
4.916597
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/boats-to-save-people.swift
2
500
/** * https://leetcode.com/problems/boats-to-save-people/ * * */ // Date: Wed Jan 13 09:32:10 PST 2021 class Solution { func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { let p = people.sorted() var left = 0 var right = p.count - 1 var result = 0 while left <= right { result += 1 if p[left] + p[right] <= limit { left += 1 } right -= 1 } return result } }
mit
57b5b7a94ed358e6cf4252d74a8f3f6a
21.772727
63
0.456
3.703704
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Compiler/BindingGroup.swift
1
5477
// // BindingGroup.swift // LispKit // // Created by Matthias Zenger on 14/02/2016. // Copyright © 2016 ObjectHub. 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. // public final class BindingGroup: Reference, CustomStringConvertible { public unowned var owner: Compiler public let parent: Env private var bindings: [Symbol : Definition] private let nextIndex: (() -> Int)? internal let checkpoint: UInt public private(set) var box: WeakBox<BindingGroup>! public init(owner: Compiler, parent: Env, nextIndex: (() -> Int)? = nil) { self.owner = owner self.parent = parent self.bindings = [Symbol: Definition]() self.nextIndex = nextIndex self.checkpoint = owner.checkpointer.checkpoint() super.init() self.box = WeakBox(self) } @discardableResult public func defineMacro(_ sym: Symbol, proc: Procedure) -> Definition { let def = Definition(proc: proc) self.bindings[sym] = def return def } @discardableResult public func allocBindingFor(_ sym: Symbol) -> Definition { let variable = !owner.checkpointer.isValueBinding(sym, at: self.checkpoint) if let binding = self.bindings[sym] { return binding } let binding = Definition(index: self.nextIndex?() ?? owner.nextLocalIndex(), isVar: variable) self.bindings[sym] = binding return binding } public func bindingFor(_ sym: Symbol) -> Definition? { return self.bindings[sym] } public func symbol(at index: Int) -> Symbol? { for (sym, bind) in self.bindings { if bind.index == index { return sym } } return nil } public func covers(_ group: BindingGroup) -> Bool { var env: Env = .local(self) while case .local(let this) = env { if this === group { return true } env = this.parent } return false } public var count: Int { return self.bindings.count } public var symbols: [Symbol?] { var seq = [Symbol?](repeating: nil, count: self.bindings.count) for (sym, bind) in self.bindings { var extendBy = 1 + bind.index - seq.count while extendBy > 0 { seq.append(nil) extendBy -= 1 } seq[bind.index] = sym } return seq } public func macroGroup() -> BindingGroup { var env = self.parent while case .local(let group) = env { env = group.parent } let macroGroup = BindingGroup(owner: self.owner, parent: env, nextIndex: { return 0 }) env = .local(self) while case .local(let group) = env { for (sym, bind) in group.bindings { if case .macro(_) = bind.kind , macroGroup.bindingFor(sym) == nil { macroGroup.bindings[sym] = bind } } env = group.parent } return macroGroup } public func finalize() { for (sym, binding) in self.bindings { if binding.isImmutableVariable { owner.checkpointer.associate(.valueBinding(sym), with: self.checkpoint) } } } public var description: String { let seq = self.symbols var builder = StringBuilder() for index in seq.indices { builder.append(index, width: 5, alignRight: true) builder.append(": ") builder.append(seq[index]?.description ?? "<undef>") builder.appendNewline() } return builder.description } } public final class Definition: Reference, CustomStringConvertible { public enum Kind { case value case variable case mutatedVariable case macro(Procedure) } public let index: Int public private(set) var kind: Kind fileprivate init(index: Int, isVar: Bool = true) { self.index = index self.kind = isVar ? .variable : .value } fileprivate init(proc: Procedure) { self.index = 0 self.kind = .macro(proc) } public var isValue: Bool { switch self.kind { case .value: return true default: return false } } public var isVariable: Bool { switch self.kind { case .variable, .mutatedVariable: return true default: return false } } public var isImmutableVariable: Bool { switch self.kind { case .variable: return true default: return false } } public func wasMutated() { switch self.kind { case .value: preconditionFailure("cannot declare value mutable") case .variable: self.kind = .mutatedVariable case .mutatedVariable: break case .macro(_): preconditionFailure("cannot declare macro mutable") } } public var description: String { switch self.kind { case .value: return "value at index \(self.index)" case .variable: return "variable at index \(self.index)" case .mutatedVariable: return "mutated variable at index \(self.index)" case .macro(let proc): return "macro \(proc)" } } }
apache-2.0
573cdd2ca5f610f87477bbae66431419
25.200957
97
0.628013
4.104948
false
false
false
false
srxboys/RXSwiftExtention
Pods/SwifterSwift/Source/Extensions/DictionaryExtensions.swift
1
1997
// // DictionaryExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/24/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation // MARK: - Methods public extension Dictionary { /// SwifterSwift: Check if key exists in dictionary. /// /// - Parameter key: key to search for /// - Returns: true if key exists in dictionary. func has(key: Key) -> Bool { return index(forKey: key) != nil } /// SwifterSwift: JSON Data from dictionary. /// /// - Parameter prettify: set true to prettify data (default is false). /// - Returns: optional JSON Data (if applicable). public func jsonData(prettify: Bool = false) -> Data? { guard JSONSerialization.isValidJSONObject(self) else { return nil } let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions() return try? JSONSerialization.data(withJSONObject: self, options: options) } /// SwifterSwift: JSON String from dictionary. /// /// - Parameter prettify: set true to prettify string (default is false). /// - Returns: optional JSON String (if applicable). public func jsonString(prettify: Bool = false) -> String? { guard JSONSerialization.isValidJSONObject(self) else { return nil } let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions() let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) return jsonData?.string(encoding: .utf8) } } // MARK: - Methods (ExpressibleByStringLiteral) public extension Dictionary where Key: ExpressibleByStringLiteral { /// SwifterSwift: Lowercase all keys in dictionary. public mutating func lowercaseAllKeys() { // http://stackoverflow.com/questions/33180028/extend-dictionary-where-key-is-of-type-string for key in keys { if let lowercaseKey = String(describing: key).lowercased() as? Key { self[lowercaseKey] = removeValue(forKey: key) } } } }
mit
5f61931637c0f747b8d381d4e343c3b3
30.1875
120
0.719439
3.992
false
false
false
false
entotsu/MaterialKit
Example/MaterialKit/TableViewController.swift
1
1433
// // TableViewController.swift // MaterialKit // // Created by Le Van Nghia on 11/16/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var labels = ["MKButton", "MKTextField", "MKTableViewCell", "MKTextView", "MKColor", "MKLayer", "MKAlert", "MKCheckBox"] var rippleLocations: [MKRippleLocation] = [.TapLocation, .TapLocation, .Center, .Left, .Right, .TapLocation, .TapLocation, .TapLocation] var circleColors = [UIColor.MKColor.LightBlue, UIColor.MKColor.Grey, UIColor.MKColor.LightGreen] override func viewDidLoad() { } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return labels.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 65.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell cell.setMessage(labels[indexPath.row]) cell.rippleLocation = rippleLocations[indexPath.row] let index = indexPath.row % circleColors.count cell.rippleLayerColor = circleColors[index] return cell } }
mit
72d6b3d08fd395b0f423015a7895693e
36.736842
140
0.701326
4.776667
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Runtime/Context.swift
1
7420
// // Context.swift // LispKit // // Created by Matthias Zenger on 14/01/2016. // Copyright © 2016-2022 ObjectHub. 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 Foundation /// /// Represents a Scheme evaluation context. Evaluation contexts provide access to /// components shared by all environments. This class should be used if extensions, or /// customizations of individual components are needed. Class `LispKitContext` can be /// used if the interpreter is used without customizations. /// open class Context { /// The name of the LispKit interpreter which is defined by this context. public let implementationName: String? /// Version of the LispKit interpreter which is defined by this context. public let implementationVersion: String? /// Command-line arguments public let commandLineArguments: [String] /// Initial home path used by the LispKit file system public let initialHomePath: String? /// A delegate object which receives updates related to the virtual machine managed by /// this context. The virtual machine also delegates some functionality to this object. /// Context delegates are only referenced weakly. public weak var delegate: ContextDelegate? /// The global expression heap. public let heap: Heap /// A centralized module for handling files. public let fileHandler: FileHandler /// The source manager of this context. public let sources: SourceManager /// The managed object pool for freeing up objects with cyclic dependencies. public let objects: ManagedObjectPool /// The symbol table for managing interned symbols. public let symbols: SymbolTable /// The library manager of this context. public private(set) var libraries: LibraryManager! = nil /// The global environment is typically used for read-eval-print loops. public private(set) var environment: Environment! = nil /// The evaluator for executing code. public private(set) var evaluator: Evaluator! = nil /// The features exposed by the LispKit interpreter defined by this context public let features: Set<String> /// The default input port. internal var inputPort: Port! /// The default output port. internal var outputPort: Port! /// Use simplified descriptions? public static var simplifiedDescriptions: Bool = false /// Initializes a new context. public init(delegate: ContextDelegate, implementationName: String?, implementationVersion: String?, commandLineArguments: [String], initialHomePath: String?, includeInternalResources: Bool, includeDocumentPath: String?, assetPath: String?, gcDelay: Double, features: [String], limitStack: Int) { // Initialize components self.delegate = delegate self.implementationName = implementationName self.implementationVersion = implementationVersion self.commandLineArguments = commandLineArguments self.initialHomePath = initialHomePath self.heap = Heap() self.fileHandler = FileHandler(includeInternalResources: includeInternalResources, includeDocumentPath: includeDocumentPath) if let path = assetPath { _ = self.fileHandler.addAssetSearchPath(path) } self.sources = SourceManager() self.objects = ManagedObjectPool(marker: GarbageCollector(), gcDelay: gcDelay, gcCallback: delegate.garbageCollected) self.symbols = SymbolTable() var supported = Feature.supported for feature in features { supported.insert(feature) } self.features = supported self.libraries = LibraryManager(for: self) self.environment = Environment(in: self) self.evaluator = Evaluator(for: self, limitStack: limitStack) self.inputPort = Port(input: TextInput(source: delegate, abortionCallback: self.evaluator.isAbortionRequested)) self.outputPort = Port(output: TextOutput(target: delegate, threshold: 0)) // Register tracked objects self.objects.track(self.heap) self.objects.track(self.libraries) self.objects.track(self.evaluator) // Register native libraries do { for nativeLibrary in LibraryRegistry.nativeLibraries { try self.libraries.register(libraryType: nativeLibrary) } } catch let error { preconditionFailure("cannot load native libraries: \(error)") } } /// Prepares context to be ready to execute code. Library `(lispkit core)` and /// `(lispkit dynamic)` gets loaded as a result of this. If `forRepl` is set to true, /// `bootstrap` will also introduce the variables `*1`, `*2`, and `*3` in the global /// environment. These will be used by a REPL to store the last three results. public func bootstrap(forRepl: Bool = false) throws { // Guarantee that (lispkit dynamic) is imported; this will also load (lispkit core) try self.environment.import(["lispkit", "dynamic"]) // Install error handler if let dynamicLib = try self.libraries.lookup("lispkit", "dynamic") as? DynamicControlLibrary { if let raiseProc = dynamicLib.raiseProc { self.evaluator.raiseProc = raiseProc } if let raiseContinuableProc = dynamicLib.raiseContinuableProc { self.evaluator.raiseContinuableProc = raiseContinuableProc } } // Install definition procedures if let coreLib = try self.libraries.lookup("lispkit", "core") as? CoreLibrary { self.evaluator.loader = coreLib.loader self.evaluator.defineSpecial = coreLib.defineSpecial self.evaluator.defineValuesSpecial = coreLib.defineValuesSpecial } if forRepl { _ = self.environment.define(self.symbols.starOne, as: .undef) _ = self.environment.define(self.symbols.starTwo, as: .undef) _ = self.environment.define(self.symbols.starThree, as: .undef) } } /// This method updates the variables `*1`, `*2`, and `*3` in the global environment /// to match the last three results that were being evaluated via a REPL. public func update(withReplResult expr: Expr) { if let expr = self.environment[self.symbols.starTwo] { self.environment.set(self.symbols.starThree, to: expr) } if let expr = self.environment[self.symbols.starOne] { self.environment.set(self.symbols.starTwo, to: expr) } self.environment.set(self.symbols.starOne, to: expr) } /// Returns the global environment of this context. public var global: Env { return .global(self.environment) } /// Reset this context public func release() { self.evaluator.release() self.libraries.release() self.heap.release() self.sources.release() self.symbols.release() } }
apache-2.0
5640eb191a4a5238938ea39a999cb540
37.640625
99
0.693355
4.49092
false
false
false
false
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
Branch-TestBed-Swift/TestBed-Swift/TextFieldFormTableViewController.swift
1
1942
// // TextFieldFormTableViewController.swift // TestBed-Swift // // Created by David Westgate on 8/29/16. // Copyright © 2016 Branch Metrics. All rights reserved. // import UIKit class TextFieldFormTableViewController: UITableViewController, UITextFieldDelegate { // MARK: Control @IBOutlet weak var textField: UITextField! @IBOutlet weak var saveButton: UIBarButtonItem! var sender = "" var incumbantValue = "" var updatedValue = "" var viewTitle = "Default Title" var placeholder = "Default Placeholder" var header = "Default Header" var footer = "Default Footer" var keyboardType = UIKeyboardType.default // MARK: - Core View Functions override func viewDidLoad() { super.viewDidLoad() title = viewTitle textField.placeholder = placeholder textField.text = incumbantValue textField.keyboardType = keyboardType textField.delegate = self textField.addTarget(self, action: #selector(textFieldDidChange), for: UIControlEvents.editingChanged) textField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Control Functions override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return header } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return footer } func textFieldShouldReturn(_ textField: UITextField) -> Bool { performSegue(withIdentifier: "Save", sender: "save") return false } @objc func textFieldDidChange() { if ((textField.text == incumbantValue) || (textField.text == "")) { saveButton.isEnabled = false } else { saveButton.isEnabled = true } } }
mit
08fab6606d01053fc03f044862c766b3
28.409091
109
0.648635
5.347107
false
false
false
false
Kuggleland/kuggle-api-swift
Crypto.swift
1
4502
// The MIT License (MIT) // // Copyright (c) 2015 Jernej Strasner // // 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 enum CryptoAlgorithm { case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 var HMACAlgorithm: CCHmacAlgorithm { var result: Int = 0 switch self { case .MD5: result = kCCHmacAlgMD5 case .SHA1: result = kCCHmacAlgSHA1 case .SHA224: result = kCCHmacAlgSHA224 case .SHA256: result = kCCHmacAlgSHA256 case .SHA384: result = kCCHmacAlgSHA384 case .SHA512: result = kCCHmacAlgSHA512 } return CCHmacAlgorithm(result) } typealias DigestAlgorithm = (UnsafePointer<Void>, CC_LONG, UnsafeMutablePointer<CUnsignedChar>) -> UnsafeMutablePointer<CUnsignedChar> var digestAlgorithm: DigestAlgorithm { switch self { case .MD5: return CC_MD5 case .SHA1: return CC_SHA1 case .SHA224: return CC_SHA224 case .SHA256: return CC_SHA256 case .SHA384: return CC_SHA384 case .SHA512: return CC_SHA512 } } var digestLength: Int { var result: Int32 = 0 switch self { case .MD5: result = CC_MD5_DIGEST_LENGTH case .SHA1: result = CC_SHA1_DIGEST_LENGTH case .SHA224: result = CC_SHA224_DIGEST_LENGTH case .SHA256: result = CC_SHA256_DIGEST_LENGTH case .SHA384: result = CC_SHA384_DIGEST_LENGTH case .SHA512: result = CC_SHA512_DIGEST_LENGTH } return Int(result) } } extension String { // MARK: HMAC func hmac(algorithm: CryptoAlgorithm, key: String) -> String { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = algorithm.digestLength let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding) let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result) let digest = stringFromResult(result, length: digestLen) result.dealloc(digestLen) return digest } // MARK: Digest var md5: String { return digest(.MD5) } var sha1: String { return digest(.SHA1) } var sha224: String { return digest(.SHA224) } var sha256: String { return digest(.SHA256) } var sha384: String { return digest(.SHA384) } var sha512: String { return digest(.SHA512) } func digest(algorithm: CryptoAlgorithm) -> String { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = algorithm.digestLength let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) algorithm.digestAlgorithm(str!, strLen, result) let digest = stringFromResult(result, length: digestLen) result.dealloc(digestLen) return digest } // MARK: Private private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String { let hash = NSMutableString() for i in 0..<length { hash.appendFormat("%02x", result[i]) } return String(hash) } }
mit
c9f7f394540da3857497b3985a9fa276
31.157143
138
0.667703
4.409403
false
false
false
false
sergdort/SwiftImport
Pod/Classes/Extensions.swift
1
7483
// // CoreDataExtensions.swift // CoreDataImporter // // Created by Segii Shulga on 8/28/15. // Copyright © 2015 Sergey Shulga. All rights reserved. // import Foundation import CoreData //MARK:Public extension NSManagedObject: JSONToEntityMapable { /// map dictionary for entityKey to jsonKey public class var map: [String:String] { return [:] } /// Primary attribute name of the Entity public class var primaryAttribute: String { return "" } } private let lock = NSLock() extension NSManagedObject { /// key for lazy associated property private static let dateFormatterKey = "com.swiftimport.NSManagedObject.dateFormatterKey" /// default date format public class var dateFormat: String { return "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'" } /// default date formatter singleton class var dateFormatter: NSDateFormatter { lock.lock() defer {lock.unlock()} let formatter = lazyAssociatedProperty(self, key: dateFormatterKey, factory: { return NSDateFormatter() }) formatter.dateFormat = dateFormat return formatter } } extension NSManagedObject { static func importIn(context: NSManagedObjectContext) -> (json: JSONDictionary) throws -> NSManagedObject { return { json in guard let value = json[map[primaryAttribute] ?? primaryAttribute] else { throw ImportError.MissingPrimaryAttribute(entityName: swi_entityName) } return try swi_ifFindFirst(primaryAttribute, value: value, context: context, elseThen: swi_createEntityInContext) .swi_updateWith(json) } } } //MARK:Private extension NSManagedObject { class var swi_entityName: String { return String(self) } class func swi_createEntityInContext(context: NSManagedObjectContext) -> NSManagedObject { return NSEntityDescription .insertNewObjectForEntityForName(swi_entityName, inManagedObjectContext: context) } class func swi_findFirst(value: AnyObject, key: String, context: NSManagedObjectContext) -> NSManagedObject? { let request = NSFetchRequest() request.entity = NSEntityDescription .entityForName(swi_entityName, inManagedObjectContext: context) request.predicate = NSPredicate(format: "%K == '\(value)'", key) do { let data = try context.executeFetchRequest(request) return data.first as? NSManagedObject } catch { print("NSManagedObject swi_findFirst ERROR:\(error)") return .None } } class func swi_ifFindFirst(key: String, value: AnyObject, context: NSManagedObjectContext, elseThen: NSManagedObjectContext -> NSManagedObject ) -> NSManagedObject { if let first = swi_findFirst(value, key: key, context: context) { return first } else { return elseThen(context) } } } extension NSManagedObject { func swi_updateWith(json: JSONDictionary) throws -> NSManagedObject { do { try swi_updatePropertiesWith(json) try swi_updateRelationsWith(json) } catch { throw error } return self } private func swi_updatePropertiesWith(json: JSONDictionary) throws -> Void { try entity.attributesByName.forEach { (tuple) -> () in do { try swi_updateAttribute(tuple.1) <^> json[classForCoder.map[tuple.0] ?? tuple.0] <*> tuple.0 } catch { throw error } } } private func swi_updateRelationsWith(json: JSONDictionary) throws -> Void { try entity.relationshipsByName.forEach { (tuple) -> () in try swi_updateRelationshipWith <^> JSONObject -<< json[classForCoder.map[tuple.0] ?? tuple.0] <*> tuple.0 try swi_updateRelationshipsWith <^> JSONObjects -<< json[classForCoder.map[tuple.0] ?? tuple.0] <*> tuple.0 } } private func swi_updateRelationshipWith(json: JSONDictionary) -> (key: String) throws -> Void { return { key in guard let relation = self.entity.relationshipsByName[key], entity = relation.destinationEntity, name = entity.managedObjectClassName, clas = NSClassFromString(name) as? NSManagedObject.Type, value = json[clas.map[clas.primaryAttribute] ?? clas.primaryAttribute], context = self.managedObjectContext where relation.toMany == false else { throw ImportError.RelationTypeMismatch(entityName: self.classForCoder.swi_entityName, expected: "To one", got: "To many") } let obj = try clas.swi_ifFindFirst(clas.primaryAttribute, value: value, context: context, elseThen: clas.swi_createEntityInContext) .swi_updateWith(json) self.setValue(obj, forKey: key) // setting value for relationship } } private func swi_updateRelationshipsWith(array: [JSONDictionary]) -> (key: String) throws -> Void { return { key in guard let relation = self.entity.relationshipsByName[key], entity = relation.destinationEntity, name = entity.managedObjectClassName, clas = NSClassFromString(name) as? NSManagedObject.Type where relation.toMany else { throw ImportError.RelationTypeMismatch(entityName: self.classForCoder.swi_entityName, expected: "To many", got: "To one") } try array.forEach { guard let value = $0[clas.map[clas.primaryAttribute] ?? clas.primaryAttribute], context = self.managedObjectContext else { return } let obj = try clas.swi_ifFindFirst(clas.primaryAttribute, value: value, context: context, elseThen: clas.swi_createEntityInContext) .swi_updateWith($0) let relationName = relation.name.swi_capitalizedFirstCharacterString() let selector = Selector("add\(relationName)Object:") assert(self.respondsToSelector(selector))//this should not be happened if self.respondsToSelector(selector) { self.performSelector(selector, withObject: obj) } } } } private func swi_updateAttribute(att: NSAttributeDescription) -> (value: AnyObject) -> (key: String) throws -> NSManagedObject { return { value in return { key in if att.attributeValueClassName == NSStringFromClass(value.classForCoder) { self.setValue(value, forKey: key) } else { throw ImportError.TypeMismatch(entityName: self.classForCoder.swi_entityName, expectedType: att.attributeValueClassName ?? "", type: value.dynamicType, key: key) } return self } } } } extension String { func swi_capitalizedFirstCharacterString() -> String { if !isEmpty { let firstChar = substringToIndex(startIndex.successor()).capitalizedString return firstChar + substringFromIndex(startIndex.successor()) } else { return "" } } }
mit
70a1acc11137c23e706f35975d0c7204
34.628571
100
0.613339
4.867925
false
false
false
false
davefoxy/SwiftBomb
SwiftBomb/Classes/Resources/ComingUpSchedule.swift
1
1547
// // ComingUpSchedule.swift // Pods // // Created by David Fox on 23/07/2016. // // import Foundation /** A struct representing the current schedule for upcoming streams on Giant Bomb. It essentially wraps up currently live and upcoming posts as detailed at the top of GiantBomb.com and the homepage's "Coming up on Giant Bomb" panel. */ public struct ComingUpSchedule { /// An optional instance of `ComingUpScheduleItem` describing any currently-live stream or event taking place when the request is made. public let liveNow: ComingUpScheduleItem? /// An array of `ComingUpScheduleItem` instances describing upcoming posts on Giant Bomb. This mirrors the contents of the "Coming up on Giant Bomb" panel on the site's homepage. public let upcoming: [ComingUpScheduleItem] init(json: [String: AnyObject]) { if let liveNowJSON = json["liveNow"] as? [String: AnyObject] { liveNow = ComingUpScheduleItem(json: liveNowJSON) } else { liveNow = nil } if let comingUpItemDicts = json["upcoming"] as? [[String: AnyObject]] { var upcoming = [ComingUpScheduleItem]() for comingUpItemDict in comingUpItemDicts { let comingUpItem = ComingUpScheduleItem(json: comingUpItemDict) upcoming.append(comingUpItem) } self.upcoming = upcoming } else { upcoming = [ComingUpScheduleItem]() } } }
mit
d4a8a8b4c7ca6fba995c9a38dba98ec1
33.4
230
0.634777
4.673716
false
false
false
false
openxc/openxc-ios-app-demo
openXCenabler/Utility.swift
1
519
// // AppUtility.swift // openXCenabler // // Created by Ranjan, Kumar sahu (K.) on 23/01/18. // Copyright © 2018 Ford Motor Company. All rights reserved. // import Foundation public var errorMSG: String = "Error" public var errorMsgBLE: String = "BLE is not connected to the Device. " public var errorMsgCustomCommand: String = "it is not a valid json. " public var errorMsgforText: String = "you need to enter the value. " public var errorMsgcustomCommand: String = "Change to json mode for custom command. "
bsd-3-clause
3a0fc5c778d7c15c7ee0499c96bf262c
31.375
85
0.72973
3.597222
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ExternalUsernameRowItem.swift
1
5383
// // ExternalUsernameRowItem.swift // Telegram // // Created by Mike Renoir on 06.10.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import TGUIKit import TelegramCore import Postbox import SwiftSignalKit final class ExternalUsernameRowItem : GeneralRowItem { let username: TelegramPeerUsername fileprivate let title: TextViewLayout fileprivate let status: TextViewLayout init(_ initialSize: NSSize, stableId: AnyHashable, username: TelegramPeerUsername, viewType: GeneralViewType, activate: @escaping()->Void) { self.username = username self.title = .init(.initialize(string: "@\(username.username)", color: theme.colors.text, font: .normal(.text)), maximumNumberOfLines: 1) let status: String = username.flags.contains(.isActive) ? strings().usernameActive : strings().usernameNotActive let statusColor = username.flags.contains(.isActive) ? theme.colors.accent : theme.colors.grayText self.status = .init(.initialize(string: status, color: statusColor, font: .normal(.text)), maximumNumberOfLines: 1) super.init(initialSize, height: 50, stableId: stableId, viewType: viewType, action: activate) _ = makeSize(initialSize.width) } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) title.measure(width: width - viewType.innerInset.right - viewType.innerInset.left * 2 - 40 - 40) status.measure(width: width - viewType.innerInset.right - viewType.innerInset.left * 2 - 40 - 40) return true } override func viewClass() -> AnyClass { return ExternalUsernameRowView.self } } private final class ExternalUsernameRowView: GeneralContainableRowView { private let resort = ImageButton() private let title = TextView() private let status = TextView() private let imageView = ImageView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(resort) addSubview(title) addSubview(status) addSubview(imageView) title.isSelectable = false title.userInteractionEnabled = false status.isSelectable = false status.userInteractionEnabled = false resort.set(handler: { [weak self] _ in if let event = NSApp.currentEvent { self?.mouseDown(with: event) } }, for: .Down) resort.set(handler: { [weak self] _ in if let event = NSApp.currentEvent { self?.mouseDragged(with: event) } }, for: .MouseDragging) resort.set(handler: { [weak self] _ in if let event = NSApp.currentEvent { self?.mouseUp(with: event) } }, for: .Up) containerView.set(handler: { [weak self] _ in if let item = self?.item as? GeneralRowItem { item.action() } }, for: .Click) } override func updateColors() { super.updateColors() containerView.set(background: backdorColor, for: .Normal) containerView.set(background: backdorColor.lighter(), for: .Highlight) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() guard let item = item as? GeneralRowItem else { return } resort.centerY(x: containerView.frame.width - resort.frame.width - item.viewType.innerInset.right) imageView.centerY(x: item.viewType.innerInset.left) title.setFrameOrigin(NSMakePoint(imageView.frame.maxX + item.viewType.innerInset.left, 7)) status.setFrameOrigin(NSMakePoint(imageView.frame.maxX + item.viewType.innerInset.left, containerView.frame.height - status.frame.height - 7)) } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? ExternalUsernameRowItem else { return } resort.isHidden = !item.username.flags.contains(.isActive) imageView.setFrameSize(NSMakeSize(35, 35)) imageView.layer?.cornerRadius = 17.5 imageView.contentGravity = .center if item.username.flags.contains(.isActive) { imageView.background = theme.colors.accent imageView.image = NSImage(named: "Icon_ExportedInvitation_Link")?.precomposed(.white) } else { imageView.background = theme.colors.grayBackground.darker() imageView.image = NSImage(named: "Icon_ExportedInvitation_Expired")?.precomposed(.white) } if animated { imageView.layer?.animateBackground() imageView.layer?.animateContents() } self.title.update(item.title) self.status.update(item.status) resort.autohighlight = false resort.scaleOnClick = true resort.set(image: theme.icons.resort, for: .Normal) resort.sizeToFit() needsLayout = true } }
gpl-2.0
44e95e83de809d553b7c347843a64a00
32.849057
150
0.616128
4.796791
false
false
false
false
sufangliang/LiangDYZB
LiangDYZB/Classes/Main/Controller/BaseAnchorViewController.swift
1
4399
// // BaseAnchorViewController.swift // LiangDYZB // // Created by qu on 2017/1/24. // Copyright © 2017年 qu. All rights reserved. // import UIKit private let kItemMargin:CGFloat = 10 private let kHeaderViewH:CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let KPrettyCellID = "CollectionPrettyCell" private let kHeaderViewID = "kHeaderViewID" private let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH = kNormalItemW * 3 / 4 private let kPrettyItemH = kNormalItemW * 4 / 3 class BaseAnchorViewController: BaseViewController { // MARK: 定义属性 var baseVM : RecommendViewModel! lazy var collectionView:UICollectionView = { // 创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)//调整左右间隙都为10 // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: KPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseAnchorViewController{ override func setupUI() { // 2.添加collectionView view.addSubview(collectionView) // 3.调用super.setupUI() super.setupUI() } } //MARK: - collectView 数据源 extension BaseAnchorViewController:UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { print("共有多少组\( baseVM.anchorGroups.count)") return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let cell = collectionView .dequeueReusableCell(withReuseIdentifier: KPrettyCellID, for: indexPath) as! CollectionPrettyCell let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] cell.anchor = anchor return cell } let cell = collectionView .dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] cell.anchor = anchor return cell } //组头视图 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{ let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView headView.group = baseVM.anchorGroups[indexPath.section]; return headView } } extension BaseAnchorViewController : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
mit
42c1ccf4cf7ab8d6fe70ea49d847af56
37.990991
186
0.713725
5.717305
false
false
false
false
crossroadlabs/Express
Express/UrlMatcher.swift
1
2438
//===--- UrlMatcher.swift -------------------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express is free software: you can redistribute it and/or modify //it under the terms of the GNU Lesser General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express 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 Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation public protocol UrlMatcherType { /// /// Matches path with a route and returns matched params if avalable. /// - Parameter path: path to match over /// - Returns: nil if route does not match. Matched params otherwise /// func match(method:String, path:String) -> [String: String]? } extension RouterType { func nextRoute(index:Array<RouteType>.Index?, request:RequestHeadType?) -> (RouteType, [String: String])? { return request.flatMap { req in let url = req.path let method = req.method let route:(RouteType, [String: String])? = index.flatMap { i in let rest = routes.suffix(from: i) return rest.mapFirst { e in guard let match = e.matcher.match(method: method, path:url) else { return nil } return (e, match) } } return route } } func nextRoute(routeId:String, request:RequestHeadType?) -> (RouteType, [String: String])? { return request.flatMap { req in let index = routes.index {routeId == $0.id}.map { $0 + 1 } // $0.successor return nextRoute(index: index, request: request) } } func firstRoute(request:RequestHeadType?) -> (RouteType, [String: String])? { return nextRoute(index: routes.startIndex, request: request) } }
gpl-3.0
c94b6affa8b602acdaa0c588850bf0af
36.507692
111
0.581214
4.634981
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Services/ApiKeyService.swift
1
5330
// // ApiKeyService2.swift // NearbyWeather // // Created by Erik Maximilian Martens on 07.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import RxSwift import RxAlamofire // MARK: - Domain-Specific Errors extension ApiKeyService { enum DomainError: Error { var domain: String { "WeatherInformationService" } case apiKeyMissingError case apiKeyInvalidError(invalidApiKey: String) var rawValue: String { switch self { case .apiKeyMissingError: return "Trying to request data from OpenWeatherMap, but no API key exists." case let .apiKeyInvalidError(invalidApiKey): return "Trying to request data from OpenWeatherMap, but the API key is invalid: \(invalidApiKey)." } } } } // MARK: - Domain-Specific Types extension ApiKeyService { enum ApiKeyValidity { case valid(apiKey: String) case invalid(invalidApiKey: String) case missing case unknown(apiKey: String) var isValid: Bool { switch self { case .valid: return true case .invalid, .missing, .unknown: return false } } } } extension ApiKeyService.ApiKeyValidity: Equatable { static func == (lhs: Self, rhs: Self) -> Bool { switch (lhs, rhs) { case (let .valid(lhsVal), let .valid(rhsVal)): return lhsVal == rhsVal case (let .unknown(lhsVal), let .unknown(rhsVal)): return lhsVal == rhsVal case (.invalid, .invalid): return true case (.missing, .missing): return true default: return false } } } // MARK: - Persistency Keys private extension ApiKeyService { enum PersistencyKeys { case userApiKey var collection: String { switch self { case .userApiKey: return "/api_keys/" } } var identifier: String { switch self { case .userApiKey: return "user_api_key" } } } } // MARK: - Dependencies extension ApiKeyService { struct Dependencies { let persistencyService: PersistencyProtocol } } // MARK: - Class Definition final class ApiKeyService { // MARK: - Properties private let dependencies: Dependencies // MARK: - Initialization init(dependencies: Dependencies) { self.dependencies = dependencies } } // MARK: - API Key Validity protocol ApiKeyValidity { func createApiKeyIsValidObservable() -> Observable<ApiKeyService.ApiKeyValidity> } extension ApiKeyService: ApiKeyValidity { func createApiKeyIsValidObservable() -> Observable<ApiKeyService.ApiKeyValidity> { let identity = PersistencyModelIdentity( collection: PersistencyKeys.userApiKey.collection, identifier: PersistencyKeys.userApiKey.identifier ) return dependencies .persistencyService .observeResource(with: identity, type: ApiKeyDTO.self) .map { $0?.entity.apiKey } .flatMapLatest { apiKey -> Observable<ApiKeyService.ApiKeyValidity> in guard let apiKey = apiKey else { return Observable.just(.missing) } return RxAlamofire .requestData(.get, Constants.Urls.kOpenWeatherMapApitTestRequestUrl(with: apiKey)) .map { response -> ApiKeyService.ApiKeyValidity in if response.0.statusCode == 401 { return .invalid(invalidApiKey: apiKey) } guard response.0.statusCode == 200 else { return .unknown(apiKey: apiKey) // another http error was returned and it cannot be determined whether the key is valid } return .valid(apiKey: apiKey) } } } } // MARK: - API Key Persistence protocol ApiKeyPersistence: ApiKeySetting, ApiKeyReading { func createSetApiKeyCompletable(_ apiKey: String) -> Completable func createGetApiKeyObservable() -> Observable<String> } extension ApiKeyService: ApiKeyPersistence { func createSetApiKeyCompletable(_ apiKey: String) -> Completable { Single .just(ApiKeyDTO(apiKey: apiKey)) .map { PersistencyModel(identity: PersistencyModelIdentity(collection: PersistencyKeys.userApiKey.collection, identifier: PersistencyKeys.userApiKey.identifier), entity: $0) } .flatMapCompletable { [dependencies] in dependencies.persistencyService.saveResource($0, type: ApiKeyDTO.self) } } func createGetApiKeyObservable() -> Observable<String> { createApiKeyIsValidObservable() .map { apiKeyValidity -> String in switch apiKeyValidity { case let .valid(apiKey): return apiKey case let .invalid(invalidApiKey): throw ApiKeyService.DomainError.apiKeyInvalidError(invalidApiKey: invalidApiKey) case .missing: throw ApiKeyService.DomainError.apiKeyMissingError case let .unknown(apiKey): return apiKey } } } } // MARK: - API Key Setting protocol ApiKeySetting { func createSetApiKeyCompletable(_ apiKey: String) -> Completable } extension ApiKeyService: ApiKeySetting {} // MARK: - API Key Reading protocol ApiKeyReading { func createGetApiKeyObservable() -> Observable<String> func createApiKeyIsValidObservable() -> Observable<ApiKeyService.ApiKeyValidity> } extension ApiKeyService: ApiKeyReading {}
mit
9262b5d162f95e7602f1eda5195ee02c
25.914141
149
0.666917
4.41874
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/AlignmentRectController.swift
1
4196
// // AlignmentRectController.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2018/4/28. // Copyright © 2018 伯驹 黄. All rights reserved. // import UIKit class AlignmentRectView: UILabel { override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return size } override func alignmentRect(forFrame frame: CGRect) -> CGRect { let rect = super.alignmentRect(forFrame: frame) print("🍀🍀\(#function)🍀🍀") print(rect) print("\n\n") return rect } override func frame(forAlignmentRect alignmentRect: CGRect) -> CGRect { let rect = super.frame(forAlignmentRect: alignmentRect) print("🍀🍀\(#function)🍀🍀") print(rect) print("\n\n") return rect } override var alignmentRectInsets: UIEdgeInsets { var inset = super.alignmentRectInsets print("🍀🍀\(#function)🍀🍀") print(inset) print("\n\n") inset.bottom -= 10 return inset } } class AlignmentRectController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // initTest1() // initStackView() let field = UITextField() field.backgroundColor = .red let stackView = UIStackView(arrangedSubviews: [field]) stackView.axis = .horizontal stackView.distribution = .fill stackView.alignment = .fill view.addSubview(stackView) stackView.snp.makeConstraints { (make) in make.leading.equalTo(15) make.center.equalToSuperview() make.height.equalTo(30) } } let subview1 = AlignmentRectView() override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // temp.text = "" } func initTest1() { let subview = AlignmentRectView() subview.text = "这是一段测试代码" view.addSubview(subview) subview.backgroundColor = UIColor.red subview.snp.makeConstraints { (make) in make.center.equalToSuperview() } subview1.numberOfLines = 0 subview1.text = "这是一段测试代码\n这是一段测试代码" view.addSubview(subview1) subview1.backgroundColor = UIColor.gray subview1.snp.makeConstraints { (make) in make.top.equalTo(subview.snp.bottom) make.centerX.equalToSuperview() } let subview2 = AlignmentRectView() subview2.numberOfLines = 0 subview2.text = "这是代码\n这是代码" view.addSubview(subview2) subview2.backgroundColor = UIColor.blue subview2.snp.makeConstraints { (make) in make.top.equalTo(subview1.snp.bottom) make.centerX.equalToSuperview() } } var temp: AlignmentRectView! func initStackView() { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.alignment = .center view.addSubview(stackView) stackView.spacing = 10 stackView.snp.makeConstraints { (make) in make.leading.trailing.centerY.equalToSuperview() } let texts = [ "这是一段测试代码", "这是一段测试代码\n这是一段测试代码", "这是代码\n这是代码" ] for (i, text) in texts.enumerated() { let subview = AlignmentRectView() subview.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 100, height: 100)).priority(999) } subview.text = text subview.numberOfLines = 0 subview.backgroundColor = UIColor.yellow if i == 1 { temp = subview } stackView.addArrangedSubview(subview) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
80cde8be80fc7fb356274cbf81c36af1
27.913669
80
0.584971
4.567045
false
false
false
false
HongliYu/firefox-ios
Providers/PocketFeed.swift
1
5942
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Alamofire import Shared import Deferred import Storage private let PocketEnvAPIKey = "PocketEnvironmentAPIKey" private let PocketGlobalFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs" private let MaxCacheAge: Timestamp = OneMinuteInMilliseconds * 60 // 1 hour in milliseconds private let SupportedLocales = ["en_US", "en_GB", "en_ZA", "de_DE", "de_AT", "de_CH"] public let PocketVideoFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-video-recs" /*s The Pocket class is used to fetch stories from the Pocked API. Right now this only supports the global feed For a sample feed item check ClientTests/pocketglobalfeed.json */ struct PocketStory { let url: URL let title: String let storyDescription: String let imageURL: URL let domain: String static func parseJSON(list: Array<[String: Any]>) -> [PocketStory] { return list.compactMap({ (storyDict) -> PocketStory? in guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String, let imageURLS = storyDict["image_src"] as? String, let title = storyDict["title"] as? String, let description = storyDict["excerpt"] as? String else { return nil } guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS) else { return nil } return PocketStory(url: url, title: title, storyDescription: description, imageURL: imageURL, domain: domain) }) } } private class PocketError: MaybeErrorType { var description = "Failed to load from API" } class Pocket { private let pocketGlobalFeed: String static let MoreStoriesURL = URL(string: "https://getpocket.com/explore/trending?src=ff_ios&cdn=0")! // Allow endPoint to be overriden for testing init(endPoint: String = PocketGlobalFeed) { self.pocketGlobalFeed = endPoint } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.defaultClientUserAgent let configuration = URLSessionConfiguration.default var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:] defaultHeaders["User-Agent"] = ua configuration.httpAdditionalHeaders = defaultHeaders return SessionManager(configuration: configuration) }() private func findCachedResponse(for request: URLRequest) -> [String: Any]? { let cachedResponse = URLCache.shared.cachedResponse(for: request) guard let cachedAtTime = cachedResponse?.userInfo?["cache-time"] as? Timestamp, (Date.now() - cachedAtTime) < MaxCacheAge else { return nil } guard let data = cachedResponse?.data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else { return nil } return json as? [String: Any] } private func cache(response: HTTPURLResponse?, for request: URLRequest, with data: Data?) { guard let resp = response, let data = data else { return } let metadata = ["cache-time": Date.now()] let cachedResp = CachedURLResponse(response: resp, data: data, userInfo: metadata, storagePolicy: .allowed) URLCache.shared.removeCachedResponse(for: request) URLCache.shared.storeCachedResponse(cachedResp, for: request) } // Fetch items from the global pocket feed func globalFeed(items: Int = 2) -> Deferred<Array<PocketStory>> { let deferred = Deferred<Array<PocketStory>>() guard let request = createGlobalFeedRequest(items: items) else { deferred.fill([]) return deferred } if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["recommendations"] as? Array<[String: Any]> { deferred.fill(PocketStory.parseJSON(list: items)) return deferred } alamofire.request(request).validate(contentType: ["application/json"]).responseJSON { response in guard response.error == nil, let result = response.result.value as? [String: Any] else { return deferred.fill([]) } self.cache(response: response.response, for: request, with: response.data) guard let items = result["recommendations"] as? Array<[String: Any]> else { return deferred.fill([]) } return deferred.fill(PocketStory.parseJSON(list: items)) } return deferred } // Returns nil if the locale is not supported static func IslocaleSupported(_ locale: String) -> Bool { return SupportedLocales.contains(locale) } // Create the URL request to query the Pocket API. The max items that the query can return is 20 private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? { guard items > 0 && items <= 20 else { return nil } let locale = Locale.current.identifier let pocketLocale = locale.replacingOccurrences(of: "_", with: "-") var params = [URLQueryItem(name: "count", value: String(items)), URLQueryItem(name: "locale_lang", value: pocketLocale), URLQueryItem(name: "version", value: "3")] if let consumerKey = Bundle.main.object(forInfoDictionaryKey: PocketEnvAPIKey) as? String { params.append(URLQueryItem(name: "consumer_key", value: consumerKey)) } guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParams(params) else { return nil } return URLRequest(url: feedURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 5) } }
mpl-2.0
1b15eb211366433a72dd1ef165d0f980
40.552448
171
0.658028
4.591963
false
false
false
false
dawsonbotsford/MobileAppsFall2015
iOS/lab4/lab4/ViewController.swift
1
2868
// // ViewController.swift // animation // Dawson Botsford import UIKit class ViewController: UIViewController { var delta = CGPointMake(0.0, 12) //initialize the delta to move 0 pixels horizontally, 10 pixels vertically var ballRadius = CGFloat() //radius of the ball image var timer = NSTimer() //animation timer var translation = CGPointMake(0.0, 0.0) //specifies how many pixels the image will move var angle:CGFloat=0.0 //roation angle var reboundRate:CGFloat = 1.0 var spinIt = true @IBOutlet weak var slider: UISlider! @IBOutlet weak var sliderLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBAction func sliderMoved(sender: UISlider) { timer.invalidate() changeSliderValue() } //changes the position of the image view func moveImage() { let duration=Double(slider.value) UIView.beginAnimations("bball", context: nil) if (spinIt) { UIView.animateWithDuration(duration, animations: {self.imageView.transform=CGAffineTransformMakeRotation(self.angle) self.imageView.center = CGPointMake(self.imageView.center.x + self.delta.x, self.imageView.center.y + self.delta.y) }) UIView.commitAnimations() } angle += 0.07 //amount you increase the angle //if it's a full rotation reset the angle if angle > CGFloat(2*M_PI){ angle=0 } delta.y += 0.7 if imageView.center.x > self.view.bounds.size.width-ballRadius || imageView.center.x < ballRadius{ delta.x = -delta.x } if imageView.center.y > self.view.bounds.size.height - ballRadius || imageView.center.y < ballRadius { delta.y = -delta.y if (delta.y < 0) { delta.y += 2; } if (abs(delta.y) < 3) { delta.y = 0 spinIt = false } } } //updates the timer and label with the current slider value @IBAction func changeSliderValue() { sliderLabel.text=String(format: "%.2f", slider.value) timer = NSTimer.scheduledTimerWithTimeInterval(Double(slider.value / 34), target: self, selector: "moveImage", userInfo: nil, repeats: true) } override func viewDidLoad() { //ball radius is half the width of the image ballRadius=imageView.frame.size.width/2 changeSliderValue() super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldAutorotate() -> Bool { return false } }
mit
d85c2252f947239e5f07da35d0631935
32.741176
148
0.608089
4.432767
false
false
false
false
FranDepascuali/ProyectoAlimentar
ProyectoAlimentar/UIComponents/Main/MainViewModel.swift
1
1675
// // MainViewModel.swift // ProyectoAlimentar // // Created by Francisco Depascuali on 10/20/16. // Copyright © 2016 Alimentar. All rights reserved. // import ReactiveSwift public enum TabViewItem: Int { case first = 0 case second case third case four } public final class MainViewModel { public let selectedTab: Property<TabViewItem> fileprivate let _selectedTab = MutableProperty(TabViewItem.first) fileprivate let _donationsRepository: DonationRepositoryType fileprivate let _userRepository: UserRepositoryType public init(donationsRepository: DonationRepositoryType, userRepository: UserRepositoryType) { selectedTab = Property(_selectedTab) _donationsRepository = donationsRepository _userRepository = userRepository } public func selectTab(at index: Int) { guard let selectedTab = TabViewItem(rawValue: index), selectedTab != _selectedTab.value else { return } _selectedTab.value = selectedTab } public func createDonationPickerViewModel() -> DonationPickerViewModel { return DonationPickerViewModel(donationRepository: _donationsRepository) } public func createActiveDonationsViewModel() -> ActiveDonationsViewModel { return ActiveDonationsViewModel(donationRepository: _donationsRepository) } public func createDonationsRecordViewModel() -> DonationsRecordsViewModel { return DonationsRecordsViewModel(donationRepository: _donationsRepository) } public func createProfileViewModel() -> LoginViewModel { return LoginViewModel(userRepository: _userRepository) } }
apache-2.0
98e9244d89304281eeda13658dc2a3de
28.892857
111
0.726404
5.417476
false
false
false
false
zisko/swift
test/Constraints/lvalues.swift
2
8554
// RUN: %target-typecheck-verify-swift func f0(_ x: inout Int) {} func f1<T>(_ x: inout T) {} func f2(_ x: inout X) {} func f2(_ x: inout Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(lhs: inout X, rhs : X) {} prefix operator +++ prefix func +++(rhs: inout X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x +++x var yi = y[i] // Non-settable lvalues var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++z.non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} +++z[0] // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} +++fz().settable_x // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++z.non_settable_x.property // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(_ x: Int) {} func testInOut(_ arg: inout Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error{{variable has type 'inout Int' which includes nested inout parameters}} \ // expected-error{{'&' can only appear immediately in a call argument list}} var ir2 = ((&i)) // expected-error{{variable has type 'inout Int' which includes nested inout parameters}} \ // expected-error{{'&' can only appear immediately in a call argument list}} // <rdar://problem/17133089> func takeArrayRef(_ x: inout Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{cannot pass immutable value of type '[String]' as inout argument}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(_ p: UnsafeMutableRawPointer) {} func f2(_ a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(pi) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(_ p: UnsafePointer<Int>) { p.pointee = 1 // expected-error {{cannot assign to property: 'pointee' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (v: inout Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(_ fn: (_ x: inout Int) -> Void) { var a = 0 fn(&a) } r23331567 { $0 += 1 } // <rdar://problem/30685195> Compiler crash with invalid assignment struct G<T> { subscript(x: Int) -> T { get { } nonmutating set { } } // expected-note@-1 {{'subscript' declared here}} } func wump<T>(to: T, _ body: (G<T>) -> ()) {} wump(to: 0, { $0[] = 0 }) // expected-error@-1 {{missing argument for parameter #1 in call}}
apache-2.0
473220b3c23f0aa6a3c38d77eb775aa8
34.057377
139
0.668342
3.274885
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadNumberOfSupportedAdvertisingSets.swift
1
2041
// // HCILEReadNumberOfSupportedAdvertisingSets.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/15/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Read Number of Supported Advertising Sets Command /// /// The command is used to read the maximum number of advertising sets supported by /// the advertising Controller at the same time. Note: The number of advertising sets that /// can be supported is not fixed and the Controller can change it at any time because the memory /// used to store advertising sets can also be used for other purposes. func readNumberOfSupportedAdvertisingSets(timeout: HCICommandTimeout = .default) async throws -> UInt8 { let value = try await deviceRequest(HCILEReadNumberOfSupportedAdvertisingSets.self, timeout: timeout) return value.numSupportedAdvertisingSets } } // MARK: - Return parameter /// LE Read Number of Supported Advertising Sets Command /// /// The command is used to read the maximum number of advertising sets supported by /// the advertising Controller at the same time. Note: The number of advertising sets that /// can be supported is not fixed and the Controller can change it at any time because the memory /// used to store advertising sets can also be used for other purposes. @frozen public struct HCILEReadNumberOfSupportedAdvertisingSets: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.readNumberOfSupportedAdvertisingSets //0x003B public static let length: Int = 1 /// Number of advertising sets supported at the same time public let numSupportedAdvertisingSets: UInt8 //Num_Supported_Advertising_Sets public init?(data: Data) { guard data.count == type(of: self).length else { return nil } numSupportedAdvertisingSets = data[0] } }
mit
1ac127933b7eef6eada7896703c7e81b
36.777778
108
0.714216
4.880383
false
false
false
false
xudafeng/ios-app-bootstrap
ios-app-bootstrap/components/ToastViewController.swift
1
1647
// // CoreMotionViewController.swift // ios-app-bootstrap // // Created by xdf on 3/25/16. // Copyright © 2016 open source. All rights reserved. // import UIKit import Logger_swift class ToastViewController: UIViewController { let logger = Logger() override func viewDidLoad() { super.viewDidLoad() initView() } func initView() { navigationItem.title = Utils.Path.basename(#file) view.backgroundColor = UIColor.white let button = UIButton() button.backgroundColor = Utils.getRGB(Const.COLOR_1) button.setTitle("show", for: UIControl.State()) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 2 button.titleLabel!.font = UIFont(name: "Helvetica",size: 12) button.addTarget(self, action: #selector(ToastViewController.show(_:)), for: .touchUpInside) view.addSubview(button) let views:Dictionary<String, AnyObject>=["button": button] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[button(<=20)]-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-120-[button]-120-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views)) showToast() } func showToast() { view.makeToast(message: "this is toast", duration: 3, position: HRToastPositionCenter as AnyObject) } @objc func show(_ sender: UIButton) { showToast() } }
mit
ad15c586923620626b29b53e2b02ada9
32.591837
178
0.651883
4.757225
false
false
false
false
hughbe/swift
test/Constraints/patterns.swift
2
8112
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var a // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // TODO: should warn that cast can't succeed with currently known conformances () // TODO: Bad error message case .HairForceOne: // expected-error{{cannot convert}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } // <rdar://problem/21995744> QoI: Binary operator '~=' cannot be applied to operands of type 'String' and 'String?' switch ("foo" as String?) { case "what": break // expected-error{{expression pattern of type 'String' cannot match values of type 'String?'}} {{12-12=?}} default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // expected-error{{enum case 'foo' not found in type 'SR2057?'}} // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } static func method(withLabel: Int) -> StaticMembers { return prop } static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{cannot match values of type 'StaticMembers'}} case .init(opt:): break // expected-error{{cannot match values of type 'StaticMembers'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{not unwrapped}} case .prop: break // TODO: repeated error message case .optProp: break // expected-error* {{not unwrapped}} case .method: break // expected-error{{cannot match}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{cannot match}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{cannot match}} case .optMethod(0): break // expected-error{{not unwrapped}} } _ = 0
apache-2.0
a2dde902360a6c760b900169a0f2ba8e
24.670886
208
0.64608
3.590969
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamCore/Application/AppMigration.swift
1
3796
// // AppMigration.swift // ZamzamCore // // Inspired by: https://github.com/mysterioustrousers/MTMigration // // Created by Basem Emara on 5/30/17. // Copyright © 2017 Zamzam Inc. All rights reserved. // import Foundation.NSUserDefaults /// Manages blocks of code that only need to run once on version updates in apps. /// /// @UIApplicationMain /// class AppDelegate: UIResponder, UIApplicationDelegate { /// /// var window: UIWindow? /// let migration = Migration() /// /// func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { /// migration /// .performUpdate { /// print("Migrate update occurred.") /// } /// .perform(forVersion: "1.0") { /// print("Migrate to 1.0 occurred.") /// } /// .perform(forVersion: "1.7") { /// print("Migrate to 1.7 occurred.") /// } /// .perform(forVersion: "2.4") { /// print("Migrate to 2.4 occurred.") /// } /// /// return true /// } /// } public class AppMigration { public static let suiteName = "io.zamzam.ZamzamKit.Migration" private let defaults: UserDefaults private let bundle: Bundle private lazy var appVersion: String = bundle .infoDictionary?["CFBundleShortVersionString"] as? String ?? "" public init(userDefaults: UserDefaults = UserDefaults(suiteName: suiteName) ?? .standard, bundle: Bundle = .main) { self.defaults = userDefaults self.bundle = bundle } } public extension AppMigration { /// Checks the current version of the app against the previous saved version. /// /// - Parameter completion: Will be called when the app is updated. Will always be called once. @discardableResult func performUpdate(completion: () -> Void) -> Self { guard lastAppVersion != appVersion else { return self } completion() lastAppVersion = appVersion return self } /// Checks the current version of the app against the previous saved version. /// If it doesn't match the completion block gets called, and passed in the current app verson. /// /// - Parameters: /// - version: Version to update. /// - build: Build to update. /// - completion: Will be called when the app is updated. Will always be called once. @discardableResult func perform(forVersion version: String, completion: () -> Void) -> Self { guard version.compare(lastMigrationVersion ?? "", options: .numeric) == .orderedDescending, version.compare(appVersion, options: .numeric) != .orderedDescending else { return self } completion() lastMigrationVersion = version return self } /// Wipe saved values when last migrated so next update will occur. func reset() { lastAppVersion = nil lastMigrationVersion = nil } } private extension AppMigration { private static let lastAppVersionKey = "lastAppVersion" private static let lastVersionKey = "lastMigrationVersion" var lastAppVersion: String? { get { defaults.string(forKey: Self.lastAppVersionKey) } set { defaults.setValue(newValue, forKey: Self.lastAppVersionKey) } } var lastMigrationVersion: String? { get { defaults.string(forKey: Self.lastVersionKey) } set { defaults.setValue(newValue, forKey: Self.lastVersionKey) } } } // MARK: - Only used for XCTest extension AppMigration { func set(version: String) { appVersion = version } }
mit
93470677c13b42481a3635b8a5759945
32.584071
160
0.614756
4.645043
false
false
false
false
eBay/NMessenger
nMessenger/Source/MessageNodes/ContentNodes/TextContent/TextContentNode.swift
2
18758
// // Copyright (c) 2016 eBay Software Foundation // // 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 AsyncDisplayKit //MARK: TextMessageNode /** TextMessageNode class for N Messenger. Extends MessageNode. Defines content that is a text. */ open class TextContentNode: ContentNode,ASTextNodeDelegate { // MARK: Public Variables /** Insets for the node */ open var insets = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) { didSet { setNeedsLayout() } } /** UIFont for incoming text messages*/ open var incomingTextFont = UIFont.n1B1Font() { didSet { self.updateAttributedText() } } /** UIFont for outgoinf text messages*/ open var outgoingTextFont = UIFont.n1B1Font() { didSet { self.updateAttributedText() } } /** UIColor for incoming text messages*/ open var incomingTextColor = UIColor.n1DarkestGreyColor() { didSet { self.updateAttributedText() } } /** UIColor for outgoinf text messages*/ open var outgoingTextColor = UIColor.n1WhiteColor() { didSet { self.updateAttributedText() } } /** String to present as the content of the cell*/ open var textMessageString: NSAttributedString? { get { return self.textMessageNode.attributedText } set { self.textMessageNode.attributedText = newValue } } /** Overriding from super class Set backgroundBubble.bubbleColor and the text color when valus is set */ open override var isIncomingMessage: Bool { didSet { if isIncomingMessage { self.backgroundBubble?.bubbleColor = self.bubbleConfiguration.getIncomingColor() self.updateAttributedText() } else { self.backgroundBubble?.bubbleColor = self.bubbleConfiguration.getOutgoingColor() self.updateAttributedText() } } } // MARK: Private Variables /** ASTextNode as the content of the cell*/ open fileprivate(set) var textMessageNode:ASTextNode = ASTextNode() /** Bool as mutex for handling attributed link long presses*/ fileprivate var lockKey: Bool = false // MARK: Initialisers /** Initialiser for the cell. - parameter textMessageString: Must be String. Sets text for cell. Calls helper method to setup cell */ public init(textMessageString: String, bubbleConfiguration: BubbleConfigurationProtocol? = nil) { super.init(bubbleConfiguration: bubbleConfiguration) self.setupTextNode(textMessageString) } /** Initialiser for the cell. - parameter textMessageString: Must be String. Sets text for cell. - parameter currentViewController: Must be an UIViewController. Set current view controller holding the cell. Calls helper method to setup cell */ public init(textMessageString: String, currentViewController: UIViewController, bubbleConfiguration: BubbleConfigurationProtocol? = nil) { super.init(bubbleConfiguration: bubbleConfiguration) self.currentViewController = currentViewController self.setupTextNode(textMessageString) } // MARK: Initialiser helper method /** Creates the text to be display in the cell. Finds links and phone number in the string and creates atrributed string. - parameter textMessageString: Must be String. Sets text for cell. */ fileprivate func setupTextNode(_ textMessageString: String) { self.backgroundBubble = self.bubbleConfiguration.getBubble() textMessageNode.delegate = self textMessageNode.isUserInteractionEnabled = true textMessageNode.linkAttributeNames = ["LinkAttribute","PhoneNumberAttribute"] let fontAndSizeAndTextColor = [ NSFontAttributeName: self.isIncomingMessage ? incomingTextFont : outgoingTextFont, NSForegroundColorAttributeName: self.isIncomingMessage ? incomingTextColor : outgoingTextColor] let outputString = NSMutableAttributedString(string: textMessageString, attributes: fontAndSizeAndTextColor ) let types: NSTextCheckingResult.CheckingType = [.link, .phoneNumber] let detector = try! NSDataDetector(types: types.rawValue) let matches = detector.matches(in: textMessageString, options: [], range: NSMakeRange(0, textMessageString.characters.count)) for match in matches { if let url = match.url { outputString.addAttribute("LinkAttribute", value: url, range: match.range) outputString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: match.range) outputString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: match.range) } if let phoneNumber = match.phoneNumber { outputString.addAttribute("PhoneNumberAttribute", value: phoneNumber, range: match.range) outputString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: match.range) outputString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: match.range) } } self.textMessageNode.attributedText = outputString self.textMessageNode.accessibilityIdentifier = "labelMessage" self.textMessageNode.isAccessibilityElement = true self.addSubnode(textMessageNode) } //MARK: Helper Methods /** Updates the attributed string to the correct incoming/outgoing settings and lays out the component again*/ fileprivate func updateAttributedText() { let tmpString = NSMutableAttributedString(attributedString: self.textMessageNode.attributedText!) tmpString.addAttributes([NSForegroundColorAttributeName: isIncomingMessage ? incomingTextColor : outgoingTextColor, NSFontAttributeName: isIncomingMessage ? incomingTextFont : outgoingTextFont], range: NSMakeRange(0, tmpString.length)) self.textMessageNode.attributedText = tmpString setNeedsLayout() } // MARK: Override AsycDisaplyKit Methods /** Overriding layoutSpecThatFits to specifiy relatiohsips between elements in the cell */ override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let width = constrainedSize.max.width - self.insets.left - self.insets.right textMessageNode.style.maxWidth = ASDimension(unit: .points, value: width) textMessageNode.style.maxHeight = ASDimension(unit: .fraction, value: 1) let textMessageSize = ASAbsoluteLayoutSpec() textMessageSize.sizing = .sizeToFit textMessageSize.children = [self.textMessageNode] return ASInsetLayoutSpec(insets: insets, child: textMessageSize) } // MARK: ASTextNodeDelegate /** Implementing shouldHighlightLinkAttribute - returning true for both link and phone numbers */ public func textNode(_ textNode: ASTextNode, shouldHighlightLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool { if attribute == "LinkAttribute" { return true } else if attribute == "PhoneNumberAttribute" { return true } return false } /*open func textNode(_ textNode: ASTextNode, shouldHighlightLinkAttribute attribute: String, value: AnyObject, at point: CGPoint) -> Bool { if attribute == "LinkAttribute" { return true } else if attribute == "PhoneNumberAttribute" { return true } return false }*/ /** Implementing tappedLinkAttribute - handle tap event on links and phone numbers */ //open func textNode(_ textNode: ASTextNode, tappedLinkAttribute attribute: String, value: AnyObject, at point: CGPoint, textRange: NSRange) { public func textNode(_ textNode: ASTextNode, tappedLinkAttribute attribute: String, value: Any, at point: CGPoint, textRange: NSRange) { if attribute == "LinkAttribute" { if !self.lockKey { if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.lightGray, range: textRange) self.textMessageNode.attributedText = attributedString UIApplication.shared.openURL(value as! URL) delay(0.4) { if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.removeAttribute(NSBackgroundColorAttributeName, range: textRange) self.textMessageNode.attributedText = attributedString } } } } } else if attribute == "PhoneNumberAttribute" { let phoneNumber = value as! String UIApplication.shared.openURL(URL(string: "tel://\(phoneNumber)")!) } } /** Implementing shouldLongPressLinkAttribute - returning true for both link and phone numbers */ //open func textNode(_ textNode: ASTextNode, shouldLongPressLinkAttribute attribute: String, value: AnyObject, at point: CGPoint) -> Bool { public func textNode(_ textNode: ASTextNode, shouldLongPressLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool { if attribute == "LinkAttribute" { return true } else if attribute == "PhoneNumberAttribute" { return true } return false } /** Implementing longPressedLinkAttribute - handles long tap event on links and phone numbers */ //open func textNode(_ textNode: ASTextNode, longPressedLinkAttribute attribute: String, value: AnyObject, at point: CGPoint, textRange: NSRange) { public func textNode(_ textNode: ASTextNode, longPressedLinkAttribute attribute: String, value: Any, at point: CGPoint, textRange: NSRange) { if attribute == "LinkAttribute" { self.lockKey = true if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.lightGray, range: textRange) self.textMessageNode.attributedText = attributedString let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let openAction = UIAlertAction(title: "Open", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let addToReadingListAction = UIAlertAction(title: "Add to Reading List", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let copyAction = UIAlertAction(title: "Copy", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) optionMenu.addAction(openAction) optionMenu.addAction(addToReadingListAction) optionMenu.addAction(copyAction) optionMenu.addAction(cancelAction) if let tmpCurrentViewController = self.currentViewController { DispatchQueue.main.async(execute: { () -> Void in tmpCurrentViewController.present(optionMenu, animated: true, completion: nil) }) } } delay(0.4) { if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.removeAttribute(NSBackgroundColorAttributeName, range: textRange) self.textMessageNode.attributedText = attributedString } } } else if attribute == "PhoneNumberAttribute" { let phoneNumber = value as! String self.lockKey = true if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.lightGray, range: textRange) self.textMessageNode.attributedText = attributedString let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let callPhoneNumberAction = UIAlertAction(title: "Call \(phoneNumber)", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let facetimeAudioAction = UIAlertAction(title: "Facetime Audio", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let sendMessageAction = UIAlertAction(title: "Send Message", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let addToContactsAction = UIAlertAction(title: "Add to Contacts", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let copyAction = UIAlertAction(title: "Copy", style: .default, handler: { (alert: UIAlertAction) -> Void in self.lockKey = false }) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (alert: UIAlertAction) -> Void in //print("Cancelled") self.lockKey = false }) optionMenu.addAction(callPhoneNumberAction) optionMenu.addAction(facetimeAudioAction) optionMenu.addAction(sendMessageAction) optionMenu.addAction(addToContactsAction) optionMenu.addAction(copyAction) optionMenu.addAction(cancelAction) if let tmpCurrentViewController = self.currentViewController { DispatchQueue.main.async(execute: { () -> Void in tmpCurrentViewController.present(optionMenu, animated: true, completion: nil) }) } } delay(0.4) { if let tmpString = self.textMessageNode.attributedText { let attributedString = NSMutableAttributedString(attributedString: tmpString) attributedString.removeAttribute(NSBackgroundColorAttributeName, range: textRange) self.textMessageNode.attributedText = attributedString } } } } // MARK: UILongPressGestureRecognizer Selector Methods /** Overriding canBecomeFirstResponder to make cell first responder */ override open func canBecomeFirstResponder() -> Bool { return true } /** Overriding resignFirstResponder to resign responder */ override open func resignFirstResponder() -> Bool { return view.resignFirstResponder() } /** Override method from superclass */ open override func messageNodeLongPressSelector(_ recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { let touchLocation = recognizer.location(in: view) if self.textMessageNode.frame.contains(touchLocation) { becomeFirstResponder() delay(0.1, closure: { let menuController = UIMenuController.shared menuController.menuItems = [UIMenuItem(title: "Copy", action: #selector(TextContentNode.copySelector))] menuController.setTargetRect(self.textMessageNode.frame, in: self.view) menuController.setMenuVisible(true, animated:true) }) } } } /** Copy Selector for UIMenuController */ open func copySelector() { UIPasteboard.general.string = self.textMessageNode.attributedText!.string } }
mit
567654ba640f902dad1e3259fefaf410
43.345154
463
0.620695
5.694596
false
false
false
false
krzysztofzablocki/Sourcery
SourceryTests/Models/MethodSpec.swift
1
8667
import Quick import Nimble #if SWIFT_PACKAGE import Foundation @testable import SourceryLib #else @testable import Sourcery #endif @testable import SourceryRuntime class MethodSpec: QuickSpec { override func spec() { describe("Method") { var sut: SourceryMethod? beforeEach { sut = Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName(name: "Int"))], definedInTypeName: TypeName(name: "Bar")) } afterEach { sut = nil } it("reports short name properly") { expect(sut?.shortName).to(equal("foo")) } it("reports definedInTypeName propertly") { expect(Method(name: "foo()", definedInTypeName: TypeName(name: "BarAlias", actualTypeName: TypeName(name: "Bar"))).definedInTypeName).to(equal(TypeName(name: "BarAlias"))) expect(Method(name: "foo()", definedInTypeName: TypeName(name: "Foo")).definedInTypeName).to(equal(TypeName(name: "Foo"))) } it("reports actualDefinedInTypeName propertly") { expect(Method(name: "foo()", definedInTypeName: TypeName(name: "BarAlias", actualTypeName: TypeName(name: "Bar"))).actualDefinedInTypeName).to(equal(TypeName(name: "Bar"))) } it("reports isDeinitializer properly") { expect(sut?.isDeinitializer).to(beFalse()) expect(Method(name: "deinitObjects() {}").isDeinitializer).to(beFalse()) expect(Method(name: "deinit").isDeinitializer).to(beTrue()) } it("reports isInitializer properly") { expect(sut?.isInitializer).to(beFalse()) expect(Method(name: "init()").isInitializer).to(beTrue()) } it("reports failable initializer return type as optional") { expect(Method(name: "init()", isFailableInitializer: true).isOptionalReturnType).to(beTrue()) } it("reports generic method") { expect(Method(name: "foo<T>()").isGeneric).to(beTrue()) expect(Method(name: "foo()").isGeneric).to(beFalse()) } describe("When testing equality") { context("given same items") { it("is equal") { expect(sut).to(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName(name: "Int"))], definedInTypeName: TypeName(name: "Bar")))) } } context("given different items") { var mockMethodParameters: [MethodParameter]! beforeEach { mockMethodParameters = [MethodParameter(name: "some", typeName: TypeName(name: "Int"))] } it("is not equal") { expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName(name: "Int"))], definedInTypeName: TypeName(name: "Baz")))) expect(sut).toNot(equal(Method(name: "bar(some: Int)", selectorName: "bar(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: [], returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "String"), accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), throws: true, accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .public, isStatic: false, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: true, isClass: false, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: false, isClass: true, isFailableInitializer: false, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: true, annotations: [:]))) expect(sut).toNot(equal(Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: mockMethodParameters, returnTypeName: TypeName(name: "Void"), accessLevel: .internal, isStatic: false, isClass: false, isFailableInitializer: false, annotations: ["some": NSNumber(value: true)]))) } } } } describe("MethodParameter") { var sut: MethodParameter! context("given default initializer parameters") { beforeEach { sut = MethodParameter(typeName: TypeName(name: "Int")) } it("has empty name") { expect(sut.name).to(equal("")) } it("has empty argumentLabel") { expect(sut.argumentLabel).to(equal("")) } it("has no type") { expect(sut.type).to(beNil()) } it("has not default value") { expect(sut.defaultValue).to(beNil()) } it("has no annotations") { expect(sut.annotations).to(equal([:])) } it("is not inout") { expect(sut.inout).to(beFalse()) } } context("given method parameter with attributes") { beforeEach { sut = MethodParameter(typeName: TypeName(name: "ConversationApiResponse", attributes: ["escaping": [Attribute(name: "escaping")]])) } it("returns unwrapped type name") { expect(sut.unwrappedTypeName).to(equal("ConversationApiResponse")) } } context("when inout") { beforeEach { sut = MethodParameter(typeName: TypeName(name: "Bar"), isInout: true) } it("is inout") { expect(sut.inout).to(beTrue()) } } describe("when testing equality") { beforeEach { sut = MethodParameter(name: "foo", typeName: TypeName(name: "Int")) } context("given same items") { it("is equal") { expect(sut).to(equal(MethodParameter(name: "foo", typeName: TypeName(name: "Int")))) } } context("given different items") { it("is not equal") { expect(sut).toNot(equal(MethodParameter(name: "bar", typeName: TypeName(name: "Int")))) expect(sut).toNot(equal(MethodParameter(argumentLabel: "bar", name: "foo", typeName: TypeName(name: "Int")))) expect(sut).toNot(equal(MethodParameter(name: "foo", typeName: TypeName(name: "String")))) expect(sut).toNot(equal(MethodParameter(name: "foo", typeName: TypeName(name: "String"), isInout: true))) } } } } } }
mit
72015c5e69951bc863e17f6c7c1e1e88
50.898204
315
0.559594
4.780474
false
false
false
false
PedroTrujilloV/TIY-Assignments
22--And-Then?/Forecaster/Forecaster/ZipCodeViewController.swift
1
4245
// // ZipCodeViewController.swift // Forecaster // // Created by Ben Gohlke on 11/2/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreLocation class ZipCodeViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate { @IBOutlet weak var locationTextField: UITextField! @IBOutlet weak var currentLocationButton: UIButton! @IBOutlet weak var searchButton: UIButton! let locationManager = CLLocationManager() let geocoder = CLGeocoder() var delegate: ZipCodeViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() configureLocationManager() currentLocationButton.enabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITextField delegate func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.text != "" { findLocationForZipCode(textField.text!) } return true } // MARK: - CLLocation related methods func configureLocationManager() { if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined { locationManager.requestAlwaysAuthorization() } else { currentLocationButton.enabled = true } } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.AuthorizedWhenInUse { currentLocationButton.enabled = true } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error.localizedDescription) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last geocoder.reverseGeocodeLocation(location!, completionHandler: {(placemark: [CLPlacemark]?, error: NSError?) -> Void in if error != nil { print(error?.localizedDescription) } else { self.locationManager.stopUpdatingLocation() let cityName = placemark?[0].locality let zipCode = placemark?[0].postalCode self.locationTextField.text = zipCode! let lat = location?.coordinate.latitude let lng = location?.coordinate.longitude let aCity = City(name: cityName!, zip: zipCode!, lat: lat!, lng: lng!) self.delegate?.cityWasFound(aCity) } }) } // MARK: - Action Handlers @IBAction func useLocationTapped(sender: UIButton) { locationManager.startUpdatingLocation() } @IBAction func searchTapped(sender: UIButton) { if locationTextField.text != "" { findLocationForZipCode(locationTextField.text!) } } // MARK: - Misc. func findLocationForZipCode(zipCode: String) { geocoder.geocodeAddressString(zipCode, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in if error != nil { print(error?.localizedDescription) } else { let cityName = placemarks?[0].locality let lat = placemarks?[0].location?.coordinate.latitude let lng = placemarks?[0].location?.coordinate.longitude let aCity = City(name: cityName!, zip: zipCode, lat: lat!, lng: lng!) self.delegate?.cityWasFound(aCity) } }) } }
cc0-1.0
ddeb1086da343cff02c6742b2bb0e643
29.539568
161
0.602262
5.943978
false
false
false
false
omgpuppy/TouchSparks
TouchSparks/GameViewController.swift
1
1284
// // GameViewController.swift // TouchSparks // // Created by Alan Browning on 10/10/15. // Copyright (c) 2015 Garbanzo. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
cc0-1.0
025030738b6b6c0ae62c1955d4ebb228
22.777778
88
0.662773
5.035294
false
false
false
false
nathawes/swift
test/Interop/Cxx/operators/non-member-inline-typechecker.swift
7
764
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop import NonMemberInline var lhs = IntBox(value: 42) var rhs = IntBox(value: 23) let resultPlus = lhs + rhs let resultMinus = lhs - rhs let resultStar = lhs * rhs let resultSlash = lhs / rhs let resultPercent = lhs % rhs let resultAmp = lhs & rhs let resultPipe = lhs | rhs let resultLessLess = lhs << rhs let resultGreaterGreater = lhs >> rhs let resultLess = lhs < rhs let resultGreater = lhs > rhs let resultEqualEqual = lhs == rhs let resultExclaimEqual = lhs != rhs let resultLessEqual = lhs <= rhs let resultGreaterEqual = lhs >= rhs var lhsBool = BoolBox(value: true) var rhsBool = BoolBox(value: false) let resultAmpAmp = lhsBool && rhsBool let resultPipePipe = lhsBool && rhsBool
apache-2.0
dce9d804855ff9de6b288db3ce33e892
26.285714
71
0.730366
3.365639
false
false
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/General/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotateMultiple.swift
57
3097
// // NVActivityIndicatorAnimationBallClipRotateMultiple.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/23/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallClipRotateMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let shortDuration: CFTimeInterval = 0.5 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) circleOf(shape: .RingTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .RingTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } func createAnimationIn(# duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if (!reverse) { rotateAnimation.values = [0, M_PI, 2 * M_PI] } else { rotateAnimation.values = [0, -M_PI, -2 * M_PI] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false return animation } func circleOf(# shape: NVActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) { let circle = shape.createLayerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } }
apache-2.0
7d5feeba83ee10511ea412d51d171539
38.705128
181
0.650307
5.267007
false
false
false
false
ashare80/ASTextInputAccessoryView
Example/ASTextInputAccessoryView/MessagesExample/MessagesFlowLayout.swift
1
2461
// // MessagesFlowLayout.swift // ASTextInputAccessoryView // // Created by Adam J Share on 4/19/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit public extension UICollectionViewLayoutAttributes { func alignFrameWithInset(inset: UIEdgeInsets) { var frame = self.frame frame.origin.x = inset.left self.frame = frame } } public protocol LayoutAlignment { func insetsForIndexPath(indexPath: NSIndexPath) -> UIEdgeInsets } class MessagesFlowLayout: UICollectionViewFlowLayout { override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let originalAttributes = super.layoutAttributesForElementsInRect(rect) else { return nil } var updatedAttributes = originalAttributes for attributes in originalAttributes { if attributes.representedElementKind != nil { continue } if let index = updatedAttributes.indexOf(attributes), let layout = layoutAttributesForItemAtIndexPath(attributes.indexPath) { updatedAttributes[index] = layout } } return updatedAttributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let currentItemAttributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes let sectionInset = evaluatedSectionInsetForItemAtIndexPath(indexPath) currentItemAttributes?.alignFrameWithInset(sectionInset) return currentItemAttributes } func evaluatedMinimumInteritemSpacingForItemAtIndex(index: Int) -> CGFloat { if let delegate = collectionView?.delegate as? UICollectionViewDelegateFlowLayout, let spacing = delegate.collectionView?(collectionView!, layout:self, minimumInteritemSpacingForSectionAtIndex: index) { return spacing } return self.minimumInteritemSpacing } func evaluatedSectionInsetForItemAtIndexPath(indexPath: NSIndexPath) -> UIEdgeInsets { if let inset = (collectionView?.delegate as? LayoutAlignment)?.insetsForIndexPath(indexPath) { return inset } return UIEdgeInsetsZero } }
mit
186aeff8287a44dd807f0e989afe4405
31.368421
132
0.671545
6.473684
false
false
false
false
yankodimitrov/Meerkat-Swift-Signals
CitiesToVisit/CitiesToVisit/ViewModels/CityViewModel.swift
1
2674
// // CityViewModel.swift // CitiesToVisit // // Created by Yanko Dimitrov on 1/4/15. // Copyright (c) 2015 Yanko Dimitrov. All rights reserved. // import Foundation import MapKit class CityViewModel: CityViewModelProtocol { let cityDidChange = ObserversDispatcher<CityViewModelProtocol>() var enableNextCityButton: Bool { return repository.citiesCount > 0 } var cityName: String { return repository.currentCity?.name ?? "" } var countryName: String { return repository.currentCity?.country ?? "" } var cityNumber: String { if repository.citiesCount <= 0 { return "00/00" } let currentCity = formatCityNumber(repository.currentCityIndex + 1) let citiesCount = formatCityNumber(repository.citiesCount) return "\(currentCity)/\(citiesCount)" } var cityAnnotation: MKAnnotation { let annotation = MKPointAnnotation() annotation.coordinate = cityLocation annotation.title = cityName annotation.subtitle = countryName return annotation } var mapRegion: MKCoordinateRegion { return MKCoordinateRegionMakeWithDistance(cityLocation, 8000, 8000) } var cityLocation: CLLocationCoordinate2D { if let city = repository.currentCity { return CLLocationCoordinate2D(latitude: city.latitude, longitude: city.longitude) } return CLLocationCoordinate2D(latitude: 0, longitude: 0) } private let repository: CitiesRepository /////////////////////////////////////////////////////// // MARK: - Initializers /////////////////////////////////////////////////////// init(repository: CitiesRepository) { self.repository = repository repository.currentCityDidChange.addObserver(self, withCallback: { [weak self] sender in if let sender = self { sender.cityDidChange.dispatchWithSender(sender) } }) } deinit { repository.currentCityDidChange.removeObserver(self) } /////////////////////////////////////////////////////// // MARK: - Methods /////////////////////////////////////////////////////// func nextCity() { repository.next() } private func formatCityNumber(number: Int) -> String { if number < 10 { return "0\(number)" } return "\(number)" } }
mit
ee3ea098abf496784dc2a9088796d660
23.990654
93
0.5273
5.738197
false
false
false
false
IngmarStein/swift
stdlib/public/core/Existential.swift
4
1686
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file contains "existentials" for the protocols defined in // Policy.swift. Similar components should usually be defined next to // their respective protocols. internal struct _CollectionOf< IndexType : Strideable, Element > : Collection { internal init( _startIndex: IndexType, endIndex: IndexType, _ subscriptImpl: @escaping (IndexType) -> Element ) { self.startIndex = _startIndex self.endIndex = endIndex self._subscriptImpl = subscriptImpl } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). func makeIterator() -> AnyIterator<Element> { var index = startIndex return AnyIterator { () -> Element? in if _fastPath(index != self.endIndex) { self.formIndex(after: &index) return self._subscriptImpl(index) } return nil } } internal let startIndex: IndexType internal let endIndex: IndexType internal func index(after i: IndexType) -> IndexType { return i.advanced(by: 1) } internal subscript(i: IndexType) -> Element { return _subscriptImpl(i) } internal let _subscriptImpl: (IndexType) -> Element }
apache-2.0
b9347c5f9faa374a0a53415425ed36c6
28.068966
80
0.623369
4.606557
false
false
false
false
dche/GLMath
Sources/Boolean.swift
1
1986
// // GLMath - Boolean.swift // // Boolean vectors. // // Copyright (c) 2017 The GLMath authors. // Licensed under MIT License. public struct bvec2: Vector2 { public typealias Dim = Dimension2 public typealias Component = Bool public typealias ArrayLiteralElement = Bool public var x, y: Bool public init (_ x: Bool, _ y: Bool) { self.x = x self.y = y } public init (_ components: [Bool]) { let x = components.count > 0 ? components[0] : false let y = components.count > 1 ? components[1] : false self.init(x, y) } } public struct bvec3: Vector3 { public typealias Dim = Dimension3 public typealias Component = Bool public typealias AssociatedVector2 = bvec2 public typealias ArrayLiteralElement = Bool public var x, y, z: Bool private let _w = false public init (_ x: Bool, _ y: Bool, _ z: Bool) { self.x = x self.y = y self.z = z } public init (_ components: [Bool]) { let x = components.count > 0 ? components[0] : false let y = components.count > 1 ? components[1] : false let z = components.count > 2 ? components[2] : false self.init(x, y, z) } } public struct bvec4: Vector4 { public typealias Dim = Dimension4 public typealias Component = Bool public typealias AssociatedVector2 = bvec2 public typealias AssociatedVector3 = bvec3 public typealias ArrayLiteralElement = Bool public var x, y, z, w: Bool public init (_ x: Bool, _ y: Bool, _ z: Bool, _ w: Bool) { self.x = x self.y = y self.z = z self.w = w } public init (_ components: [Bool]) { let x = components.count > 0 ? components[0] : false let y = components.count > 1 ? components[1] : false let z = components.count > 2 ? components[2] : false let w = components.count > 3 ? components[3] : false self.init(x, y, z, w) } }
mit
4d5200a760351602064af29d2bed475e
24.461538
62
0.590131
3.733083
false
false
false
false
Igor-Palaguta/YoutubeEngine
Source/YoutubeEngine/Parser/NSDateComponents+ISO8601.swift
1
2331
import Foundation extension DateComponents { init(ISO8601String: String) throws { guard let unitValues = ISO8601String.durationUnitValues else { throw ISO8601DateComponentsFormatError() } self.init() for (unit, value) in unitValues { setValue(value, for: unit) } } } struct ISO8601DateComponentsFormatError: Error {} private extension String { private static let dateUnitMapping: [Character: Calendar.Component] = [ "Y": .year, "M": .month, "W": .weekOfYear, "D": .day ] private static let timeUnitMapping: [Character: Calendar.Component] = [ "H": .hour, "M": .minute, "S": .second ] var durationUnitValues: [(Calendar.Component, Int)]? { guard hasPrefix("P") else { return nil } let duration = String(dropFirst()) guard let separatorRange = duration.range(of: "T") else { return duration.unitValues(withMapping: String.dateUnitMapping) } let date = String(duration[..<separatorRange.lowerBound]) let time = String(duration[separatorRange.upperBound...]) guard let dateUnits = date.unitValues(withMapping: String.dateUnitMapping), let timeUnits = time.unitValues(withMapping: String.timeUnitMapping) else { return nil } return dateUnits + timeUnits } func unitValues(withMapping mapping: [Character: Calendar.Component]) -> [(Calendar.Component, Int)]? { if isEmpty { return [] } var components: [(Calendar.Component, Int)] = [] let identifiersSet = CharacterSet(charactersIn: String(mapping.keys)) let scanner = Scanner(string: self) while !scanner.isAtEnd { var value: Int = 0 if !scanner.scanInt(&value) { return nil } var identifier: NSString? if !scanner.scanCharacters(from: identifiersSet, into: &identifier) || identifier?.length != 1 { return nil } // swiftlint:disable:next force_unwrapping let unit = mapping[Character(identifier! as String)]! components.append((unit, value)) } return components } }
mit
157c9f57887b48e0e35ae7f0397debf1
28.506329
108
0.586015
4.634195
false
false
false
false
ncalexan/firefox-ios
Providers/PocketFeed.swift
2
5329
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Alamofire import Shared import Deferred import Storage private let PocketEnvAPIKey = "PocketEnvironmentAPIKey" private let PocketGlobalFeed = "https://getpocket.com/v3/firefox/global-recs" private let MaxCacheAge: Timestamp = OneMinuteInMilliseconds * 60 // 1 hour in milliseconds /*s The Pocket class is used to fetch stories from the Pocked API. Right now this only supports the global feed For a sample feed item check ClientTests/pocketglobalfeed.json */ struct PocketStory { let url: URL let title: String let storyDescription: String let imageURL: URL let domain: String let dedupeURL: URL static func parseJSON(list: Array<[String: Any]>) -> [PocketStory] { return list.flatMap({ (storyDict) -> PocketStory? in guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String, let dedupe_URL = storyDict["dedupe_url"] as? String, let imageURLS = storyDict["image_src"] as? String, let title = storyDict["title"] as? String, let description = storyDict["excerpt"] as? String else { return nil } guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS), let dedupeURL = URL(string: dedupe_URL) else { return nil } return PocketStory(url: url, title: title, storyDescription: description, imageURL: imageURL, domain: domain, dedupeURL: dedupeURL) }) } } private class PocketError: MaybeErrorType { var description = "Failed to load from API" } class Pocket { private let pocketGlobalFeed: String // Allow endPoint to be overriden for testing init(endPoint: String? = nil) { pocketGlobalFeed = endPoint ?? PocketGlobalFeed } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.fxaUserAgent //TODO: use a different UA let configuration = URLSessionConfiguration.default return SessionManager.managerWithUserAgent(ua, configuration: configuration) }() private func findCachedResponse(for request: URLRequest) -> [String: Any]? { let cachedResponse = URLCache.shared.cachedResponse(for: request) guard let cachedAtTime = cachedResponse?.userInfo?["cache-time"] as? Timestamp, (Date.now() - cachedAtTime) < MaxCacheAge else { return nil } guard let data = cachedResponse?.data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else { return nil } return json as? [String: Any] } private func cache(response: HTTPURLResponse?, for request: URLRequest, with data: Data?) { guard let resp = response, let data = data else { return } let metadata = ["cache-time": Date.now()] let cachedResp = CachedURLResponse(response: resp, data: data, userInfo: metadata, storagePolicy: .allowed) URLCache.shared.removeCachedResponse(for: request) URLCache.shared.storeCachedResponse(cachedResp, for: request) } // Fetch items from the global pocket feed func globalFeed(items: Int = 2) -> Deferred<Array<PocketStory>> { let deferred = Deferred<Array<PocketStory>>() guard let request = createGlobalFeedRequest(items: items) else { deferred.fill([]) return deferred } if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["list"] as? Array<[String: Any]> { deferred.fill(PocketStory.parseJSON(list: items)) return deferred } alamofire.request(request).validate(contentType: ["application/json"]).responseJSON { response in guard response.error == nil, let result = response.result.value as? [String: Any] else { return deferred.fill([]) } self.cache(response: response.response, for: request, with: response.data) guard let items = result["list"] as? Array<[String: Any]> else { return deferred.fill([]) } return deferred.fill(PocketStory.parseJSON(list: items)) } return deferred } // Create the URL request to query the Pocket API. The max items that the query can return is 20 private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? { guard items > 0 && items <= 20 else { return nil } guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParam("count", value: "\(items)") else { return nil } let apiURL = addAPIKey(url: feedURL) return URLRequest(url: apiURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5) } private func addAPIKey(url: URL) -> URL { let bundle = Bundle.main guard let api_key = bundle.object(forInfoDictionaryKey: PocketEnvAPIKey) as? String else { return url } return url.withQueryParam("consumer_key", value: api_key) } }
mpl-2.0
9dd6313c2bc7056a096bf75a69b4297c
38.183824
143
0.646087
4.613853
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/LinearEquations/Solution/Strategy/MLinearEquationsSolutionStrategyReduction.swift
1
5164
import Foundation class MLinearEquationsSolutionStrategyReduction:MLinearEquationsSolutionStrategy { class func reducible(step:MLinearEquationsSolutionStep) -> MLinearEquationsSolutionStrategyReduction? { var indexEquation:Int = 0 for equation:MLinearEquationsSolutionEquation in step.equations { let countPolynomials:Int = equation.items.count for indexPolynomial:Int in 0 ..< countPolynomials { let rawItem:MLinearEquationsSolutionEquationItem = equation.items[indexPolynomial] if let _:MLinearEquationsSolutionEquationItemConstant = rawItem as? MLinearEquationsSolutionEquationItemConstant { for indexComparison:Int in indexPolynomial + 1 ..< countPolynomials { let rawComparing:MLinearEquationsSolutionEquationItem = equation.items[indexComparison] if let _:MLinearEquationsSolutionEquationItemConstant = rawComparing as? MLinearEquationsSolutionEquationItemConstant { let strategy:MLinearEquationsSolutionStrategyReduction = MLinearEquationsSolutionStrategyReductionConstants( step:step, indexEquation:indexEquation, indexPolynomialA:indexPolynomial, indexPolynomialB:indexComparison) return strategy } } if let _:MLinearEquationsSolutionEquationItemConstant = equation.result as? MLinearEquationsSolutionEquationItemConstant { let strategy:MLinearEquationsSolutionStrategyReduction = MLinearEquationsSolutionStrategyReductionConstants( step:step, indexEquation:indexEquation, indexPolynomialA:indexPolynomial, indexPolynomialB:countPolynomials) return strategy } } else if let polynomial:MLinearEquationsSolutionEquationItemPolynomial = rawItem as? MLinearEquationsSolutionEquationItemPolynomial { for indexComparison:Int in indexPolynomial + 1 ..< countPolynomials { let rawComparing:MLinearEquationsSolutionEquationItem = equation.items[indexComparison] if let polynomialCompare:MLinearEquationsSolutionEquationItemPolynomial = rawComparing as? MLinearEquationsSolutionEquationItemPolynomial { if polynomial.indeterminate === polynomialCompare.indeterminate { let strategy:MLinearEquationsSolutionStrategyReduction = MLinearEquationsSolutionStrategyReductionIndeterminates( step:step, indexEquation:indexEquation, indexPolynomialA:indexPolynomial, indexPolynomialB:indexComparison) return strategy } } } if let resultCompare:MLinearEquationsSolutionEquationItemPolynomial = equation.result as? MLinearEquationsSolutionEquationItemPolynomial { if polynomial.indeterminate === resultCompare.indeterminate { let strategy:MLinearEquationsSolutionStrategyReduction = MLinearEquationsSolutionStrategyReductionIndeterminates( step:step, indexEquation:indexEquation, indexPolynomialA:indexPolynomial, indexPolynomialB:countPolynomials) return strategy } } } } indexEquation += 1 } return nil } let indexEquation:Int let indexPolynomialA:Int let indexPolynomialB:Int init( step:MLinearEquationsSolutionStep, indexEquation:Int, indexPolynomialA:Int, indexPolynomialB:Int) { self.indexEquation = indexEquation self.indexPolynomialA = indexPolynomialA self.indexPolynomialB = indexPolynomialB super.init(step:step) } override func process(delegate:MLinearEquationsSolutionStrategyDelegate) { super.process(delegate:delegate) reduction() } //MARK: public public func reduction() { } }
mit
2e5b8ccb03edc32a4e6c6c80d804d902
43.136752
161
0.5366
7.516739
false
false
false
false
pocketworks/Dollar.swift
Dollar/Dollar/Dollar.swift
1
49936
// // ___ ___ __ ___ ________ _________ // _|\ \__|\ \ |\ \|\ \|\ _____\\___ ___\ // |\ ____\ \ \ \ \ \ \ \ \ \__/\|___ \ \_| // \ \ \___|\ \ \ __\ \ \ \ \ \ __\ \ \ \ // \ \_____ \ \ \|\__\_\ \ \ \ \ \_| \ \ \ // \|____|\ \ \____________\ \__\ \__\ \ \__\ // ____\_\ \|____________|\|__|\|__| \|__| // |\___ __\ // \|___|\__\_| // \|__| // // Dollar.swift // $ - A functional tool-belt for Swift Language // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation public class $ { /// ___ ___ _______ ___ ________ _______ ________ /// |\ \|\ \|\ ___ \ |\ \ |\ __ \|\ ___ \ |\ __ \ /// \ \ \\\ \ \ __/|\ \ \ \ \ \|\ \ \ __/|\ \ \|\ \ /// \ \ __ \ \ \_|/_\ \ \ \ \ ____\ \ \_|/_\ \ _ _\ /// \ \ \ \ \ \ \_|\ \ \ \____\ \ \___|\ \ \_|\ \ \ \\ \| /// \ \__\ \__\ \_______\ \_______\ \__\ \ \_______\ \__\\ _\ /// \|__|\|__|\|_______|\|_______|\|__| \|_______|\|__|\|__| /// /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that takes params. /// :return Function that can be called n times after which the callback function is called. public class func after<T, E>(n: Int, function: (T...) -> E) -> ((T...) -> E?) { var counter = n return { (params: T...) -> E? in typealias Function = [T] -> E if --counter <= 0 { let f = unsafeBitCast(function, Function.self) return f(params) } return .None } } /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that does not take any params. /// :return Function that can be called n times after which the callback function is called. public class func after<T>(n: Int, function: () -> T) -> (() -> T?) { let f = self.after(n) { (params: Any?...) -> T in return function() } return { f() } } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: Int...) -> [T] { return self.at(array, indexes: indexes) } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: [Int]) -> [T] { var result: [T] = [] for index in indexes { result.append(array[index]) } return result } /// Creates a function that, when called, invokes func with the binding of arguments provided. /// /// :param function Function to be bound. /// :param parameters Parameters to be passed into the function when being invoked. /// :return A new function that when called will invoked the passed function with the parameters specified. public class func bind<T, E>(function: (T...) -> E, _ parameters: T...) -> (() -> E) { return { () -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters) } } /// Creates an array with all nil values removed. /// /// :param array Array to be compacted. /// :return A new array that doesnt have any nil values. public class func compact<T>(array: [T?]) -> [T] { var result: [T] = [] for elem in array { if let val = elem { result.append(val) } } return result } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with variadic parameters of values public class func compose<T>(functions: ((T...) -> [T])...) -> ((T...) -> [T]) { typealias Function = [T] -> [T] return { var result = $0 for fun in functions { let f = unsafeBitCast(fun, Function.self) result = f(result) } return result } } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with array of values public class func compose<T>(functions: ([T] -> [T])...) -> ([T] -> [T]) { return { var result = $0 for fun in functions { result = fun(result) } return result } } /// Checks if a given value is present in the array. /// /// :param array The array to check against. /// :param value The value to check. /// :return Whether value is in the array. public class func contains<T : Equatable>(array: [T], value: T) -> Bool { return array.contains(value) } /// Create a copy of an array /// /// :param array The array to copy /// :return New copy of array public class func copy<T>(array: [T]) -> [T] { var newArr : [T] = [] for elem in array { newArr.append(elem) } return newArr } /// Cycles through the array indefinetly passing each element into the callback function /// /// :param array to cycle through /// :param callback function to call with the element public class func cycle<T, U>(array: [T], callback: (T) -> (U)) { while true { for elem in array { callback(elem) } } } /// Cycles through the array n times passing each element into the callback function /// /// :param array to cycle through /// :param times Number of times to cycle through the array /// :param callback function to call with the element public class func cycle<T, U>(array: [T], _ times: Int, callback: (T) -> (U)) { var i = 0 while i++ < times { for elem in array { callback(elem) } } } /// Creates an array excluding all values of the provided arrays. /// /// :param arrays The arrays to difference between. /// :return The difference between the first array and all the remaining arrays from the arrays params. public class func difference<T : Hashable>(arrays: [T]...) -> [T] { var result : [T] = [] var map : [T: Int] = [T: Int]() let firstArr : [T] = self.first(arrays)! let restArr : [[T]] = self.rest(arrays) as [[T]] for elem in firstArr { if let val = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } for arr in restArr { for elem in arr { map.removeValueForKey(elem) } } for (key, count) in map { for _ in 0..<count { result.append(key) } } return result } /// Call the callback passing each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array /// :return The array passed public class func each<T>(array: [T], callback: (T) -> ()) -> [T] { for elem in array { callback(elem) } return array } /// Call the callback passing index of the element and each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array with its index /// :return The array passed public class func each<T>(array: [T], callback: (Int, T) -> ()) -> [T] { for (index, elem): (Int, T) in array.enumerate() { callback(index, elem) } return array } /// Checks if two optionals containing Equatable types are equal. /// /// :param value The first optional to check. /// :param other The second optional to check. /// :return: true if the optionals contain two equal values, or both are nil; false otherwise. public class func equal<T: Equatable>(value: T?, _ other: T?) -> Bool { switch (value, other) { case (.None, .None): return true case (.None, .Some(_)): return false case (.Some(_), .None): return false case (.Some(let unwrappedValue), .Some(let otherUnwrappedValue)): return unwrappedValue == otherUnwrappedValue } } /// Checks if the given callback returns true value for all items in the array. /// /// :param array The array to check. /// :param callback Check whether element value is true or false. /// :return First element from the array. public class func every<T>(array: [T], callback: (T) -> Bool) -> Bool { for elem in array { if !callback(elem) { return false } } return true } /// Get element from an array at the given index which can be negative /// to find elements from the end of the array /// /// :param array The array to fetch from /// :param index Can be positive or negative to find from end of the array /// :param orElse Default value to use if index is out of bounds /// :return Element fetched from the array or the default value passed in orElse public class func fetch<T>(array: [T], _ index: Int, orElse: T? = .None) -> T! { if index < 0 && -index < array.count { return array[array.count + index] } else if index < array.count { return array[index] } else { return orElse } } /// Iterates over elements of an array and returning the first element /// that the callback returns true for. /// /// :param array The array to search for the element in. /// :param callback The callback function to tell whether element is found. /// :return Optional containing either found element or nil. public class func find<T>(array: [T], callback: (T) -> Bool) -> T? { for elem in array { let result = callback(elem) if result { return elem } } return .None } /// This method is like find except that it returns the index of the first element /// that passes the callback check. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return First element's index from the array found using the callback. public class func findIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { for (index, elem): (Int, T) in array.enumerate() { if callback(elem) { return index } } return .None } /// This method is like findIndex except that it iterates over elements of the array /// from right to left. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return Last element's index from the array found using the callback. public class func findLastIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { let count = array.count for (index, _) in array.enumerate() { let reverseIndex = count - (index + 1) let elem : T = array[reverseIndex] if callback(elem) { return reverseIndex } } return .None } /// Gets the first element in the array. /// /// :param array The array to wrap. /// :return First element from the array. public class func first<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[0] } } /// Gets the second element in the array. /// /// :param array The array to wrap. /// :return Second element from the array. public class func second<T>(array: [T]) -> T? { if array.count < 2 { return .None } else { return array[1] } } /// Gets the third element in the array. /// /// :param array The array to wrap. /// :return Third element from the array. public class func third<T>(array: [T]) -> T? { if array.count < 3 { return .None } else { return array[2] } } /// Flattens a nested array of any depth. /// /// :param array The array to flatten. /// :return Flattened array. public class func flatten<T>(array: [T]) -> [T] { var resultArr: [T] = [] for elem : T in array { if let val = elem as? [T] { resultArr += self.flatten(val) } else { resultArr.append(elem) } } return resultArr } /// Maps a function that converts elements to a list and then concatenates them. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(array: [T], f: (T) -> ([U])) -> [U] { return array.map(f).reduce([], combine: +) } /// Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(value: T?, f: (T) -> (U?)) -> U? { if let unwrapped = value.map(f) { return unwrapped } else { return .None } } /// Randomly shuffles the elements of an array. /// /// :param array The array to shuffle. /// :return Shuffled array public class func shuffle<T>(array: [T]) -> [T] { var newArr = self.copy(array) // Implementation of Fisher-Yates shuffle // http://en.wikipedia.org/wiki/Fisher-Yates_Shuffle for index in 0..<array.count { let randIndex = self.random(index) // We use in-out parameters to swap the internals of the array Swift.swap(&newArr[index], &newArr[randIndex]) } return newArr } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. /// /// :param array The array to source from. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T>(array: [T]) -> [T: Int] { return self.frequencies(array) { $0 } } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. If passed a function it returns /// a frequency table of the results of the given function on the arrays elements. /// /// :param array The array to source from. /// :param function The function to get value of the key for each element to group by. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T, U: Equatable>(array: [T], function: (T) -> U) -> [U: Int] { var result = [U: Int]() for elem in array { let key = function(elem) if let freq = result[key] { result[key] = freq + 1 } else { result[key] = 1 } } return result } /// The identity function. Returns the argument it is given. /// /// :param arg Value to return /// :return Argument that was passed public class func id<T>(arg: T) -> T { return arg } /// Gets the index at which the first occurrence of value is found. /// /// :param array The array to source from. /// :param value Value whose index needs to be found. /// :return Index of the element otherwise returns nil if not found. public class func indexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findIndex(array) { $0 == value } } /// Gets all but the last element or last n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to ignore in the end. /// :return Array of initial values. public class func initial<T>(array: [T], numElements: Int = 1) -> [T] { var result: [T] = [] if (array.count > numElements) { for index in 0..<(array.count - numElements) { result.append(array[index]) } } return result } /// Creates an array of unique values present in all provided arrays. /// /// :param arrays The arrays to perform an intersection on. /// :return Intersection of all arrays passed. public class func intersection<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Int] = [T: Int]() for arr in arrays { for elem in arr { if let val : Int = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } } var result : [T] = [] let count = arrays.count for (key, value) in map { if value == count { result.append(key) } } return result } /// Joins the elements in the array to create a concatenated element of the same type. /// /// :param array The array to join the elements of. /// :param separator The separator to join the elements with. /// :return Joined element from the array of elements. public class func join(array: [String], separator: String) -> String { return array.joinWithSeparator(separator) } /// Creates an array of keys given a dictionary. /// /// :param dictionary The dictionary to source from. /// :return Array of keys from dictionary. public class func keys<T, U>(dictionary: [T: U]) -> [T] { var result : [T] = [] for key in dictionary.keys { result.append(key) } return result } /// Gets the last element from the array. /// /// :param array The array to source from. /// :return Last element from the array. public class func last<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[array.count - 1] } } /// Gets the index at which the last occurrence of value is found. /// /// param: array:: The array to source from. /// :param value The value whose last index needs to be found. /// :return Last index of element if found otherwise returns nil. public class func lastIndexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findLastIndex(array) { $0 == value } } /// Maps each element to new value based on the map function passed /// /// :param collection The collection to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : CollectionType, E>(collection: T, transform: (T.Generator.Element) -> E) -> [E] { return collection.map(transform) } /// Maps each element to new value based on the map function passed /// /// :param sequence The sequence to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : SequenceType, E>(sequence: T, transform: (T.Generator.Element) -> E) -> [E] { return sequence.map(transform) } /// Retrieves the maximum value in an array. /// /// :param array The array to source from. /// :return Maximum element in array. public class func max<T : Comparable>(array: [T]) -> T? { if var maxVal = array.first { for elem in array { if maxVal < elem { maxVal = elem } } return maxVal } return .None } /// Get memoized function to improve performance /// /// :param function The function to memoize. /// :return Memoized function public class func memoize<T: Hashable, U>(function: ((T -> U), T) -> U) -> (T -> U) { var cache = [T: U]() var funcRef: (T -> U)! funcRef = { (param : T) -> U in if let cacheVal = cache[param] { return cacheVal } else { cache[param] = function(funcRef, param) return cache[param]! } } return funcRef } /// Merge dictionaries together, later dictionaries overiding earlier values of keys. /// /// :param dictionaries The dictionaries to source from. /// :return Merged dictionary with all of its keys and values. public class func merge<T, U>(dictionaries: [T: U]...) -> [T: U] { var result = [T: U]() for dict in dictionaries { for (key, value) in dict { result[key] = value } } return result } /// Merge arrays together in the supplied order. /// /// :param arrays The arrays to source from. /// :return Array with all values merged, including duplicates. public class func merge<T>(arrays: [T]...) -> [T] { var result = [T]() for arr in arrays { result += arr } return result } /// Retrieves the minimum value in an array. /// /// :param array The array to source from. /// :return Minimum value from array. public class func min<T : Comparable>(array: [T]) -> T? { if var minVal = array.first { for elem in array { if minVal > elem { minVal = elem } } return minVal } return .None } /// A no-operation function. /// /// :return nil. public class func noop() -> () { } /// Creates a shallow clone of a dictionary excluding the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to omit from returning dictionary. /// :return Dictionary with the keys specified omitted. public class func omit<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for (key, value) in dictionary { if !self.contains(keys, value: key) { result[key] = value } } return result } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<T, U>(function: (T...) -> U) -> (T...) -> U { var result: U? let onceFunc = { (params: T...) -> U in typealias Function = [T] -> U if let returnVal = result { return returnVal } else { let f = unsafeBitCast(function, Function.self) result = f(params) return result! } } return onceFunc } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<U>(function: () -> U) -> () -> U { var result: U? let onceFunc = { () -> U in if let returnVal = result { return returnVal } else { result = function() return result! } } return onceFunc } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return First element from the array. public class func partial<T, E> (function: (T...) -> E, _ parameters: T...) -> ((T...) -> E) { return { (params: T...) -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters + params) } } /// Produces an array of arrays, each containing n elements, each offset by step. /// If the final partition is not n elements long it is dropped. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > array.count { return [[]] } for i in self.range(from: 0, through: array.count - n, incrementBy: step!) { result.append(Array(array[i..<(i+n)] as ArraySlice<T>)) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :param pad An array of elements to pad the last partition if it is not long enough to /// contain n elements. If nil is passed or there are not enough pad elements /// the last partition may less than n elements long. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(var array: [T], var n: Int, var step: Int? = .None, pad: [T]?) -> [[T]] { var result : [[T]] = [] if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) if end != i+n { break } } if let padding = pad { let remain = array.count % n let end = padding.count > remain ? remain : padding.count result[result.count - 1] += Array(padding[0..<end] as ArraySlice<T>) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partitionAll<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) } return result } /// Applies function to each element in array, splitting it each time function returns a new value. /// /// :param array The array to partition. /// :param function Function which takes an element and produces an equatable result. /// :return Array partitioned in order, splitting via results of function. public class func partitionBy<T, U: Equatable>(array: [T], function: (T) -> U) -> [[T]] { var result = [[T]]() var lastValue: U? = .None for item in array { let value = function(item) if value == lastValue { result[result.count-1].append(item) } else { result.append([item]) lastValue = value } } return result } /// Creates a shallow clone of a dictionary composed of the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to pick values from. /// :return Dictionary with the key and values picked from the keys specified. public class func pick<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for key in keys { result[key] = dictionary[key] } return result } /// Retrieves the value of a specified property from all elements in the array. /// /// :param array The array to source from. /// :param value The property on object to pull out value from. /// :return Array of values from array of objects with property of value. public class func pluck<T, E>(array: [[T: E]], value: T) -> [E] { var result : [E] = [] for obj in array { if let val = obj[value] { result.append(val) } } return result } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :param values The values to remove. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: [T]) -> [T] { return array.filter { !self.contains(values, value: $0) } } public class func random(upperBound: Int) -> Int { return Int(arc4random_uniform(UInt32(upperBound))) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param endVal End value of range. /// :return Array of elements based on the sequence starting from 0 to endVal and incremented by 1. public class func range<T : Strideable where T : IntegerLiteralConvertible>(endVal: T) -> [T] { return self.range(from: 0, to: endVal) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param to End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, to endVal: T) -> [T] { return self.range(from: startVal, to: endVal, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param to End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, to endVal: T, incrementBy: T.Stride) -> [T] { let range = startVal.stride(to: endVal, by: incrementBy) return self.sequence(range) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param through End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, through endVal: T) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param through End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, through endVal: T, incrementBy: T.Stride) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: incrementBy) } /// Reduce function that will resolve to one value after performing combine function on all elements /// /// :param array The array to source from. /// :param initial Initial value to seed the reduce function with /// :param combine Function that will combine the passed value with element in the array /// :return The result of reducing all of the elements in the array into one value public class func reduce<U, T>(array: [T], initial: U, combine: (U, T) -> U) -> U { return array.reduce(initial, combine: combine) } /// Creates an array of an arbitrary sequence. Especially useful with builtin ranges. /// /// :param seq The sequence to generate from. /// :return Array of elements generated from the sequence. public class func sequence<S : SequenceType>(seq: S) -> [S.Generator.Element] { return Array<S.Generator.Element>(seq) } /// Removes all elements from an array that the callback returns true. /// /// :param array The array to wrap. /// :param callback Remove elements for which callback returns true. /// :return Array with elements filtered out. public class func remove<T>(array: [T], callback: (T) -> Bool) -> [T] { return array.filter { !callback($0) } } /// The opposite of initial this method gets all but the first element or first n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to exclude from the beginning. /// :return The rest of the elements. public class func rest<T>(array: [T], numElements: Int = 1) -> [T] { var result : [T] = [] if (numElements < array.count) { for index in numElements..<array.count { result.append(array[index]) } } return result } /// Returns a sample from the array. /// /// :param array The array to sample from. /// :return Random element from array. public class func sample<T>(array: [T]) -> T { return array[self.random(array.count)] } /// Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array. /// /// :param array The array to slice. /// :param start Start index. /// :param end End index. /// :return First element from the array. public class func slice<T>(array: [T], start: Int, end: Int = 0) -> [T] { var uend = end; if (uend == 0) { uend = array.count; } if end > array.count || start > array.count || uend < start { return []; } else { return Array(array[start..<uend]); } } /// Gives the smallest index at which a value should be inserted into a given the array is sorted. /// /// :param array The array to source from. /// :param value Find sorted index of this value. /// :return Index of where the elemnt should be inserted. public class func sortedIndex<T : Comparable>(array: [T], value: T) -> Int { for (index, elem) in array.enumerate() { if elem > value { return index } } return array.count } /// Invokes interceptor with the object and then returns object. /// /// :param object Object to tap into. /// :param function Callback function to invoke. /// :return Returns the object back. public class func tap<T>(object: T, function: (T) -> ()) -> T { function(object) return object } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. /// :return Values returned from callback function. public class func times<T>(n: Int, function: () -> T) -> [T] { return self.times(n) { (index: Int) -> T in return function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. public class func times(n: Int, function: () -> ()) { self.times(n) { (index: Int) -> () in function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time that takes index. /// :return Values returned from callback function. public class func times<T>(n: Int, function: (Int) -> T) -> [T] { var result : [T] = [] for index in (0..<n) { result.append(function(index)) } return result } /// Creates an array of unique values, in order, of the provided arrays. /// /// :param arrays The arrays to perform union on. /// :return Resulting array after union. public class func union<T : Hashable>(arrays: [T]...) -> [T] { var result : [T] = [] for arr in arrays { result += arr } return self.uniq(result) } /// Creates a duplicate-value-free version of an array. /// /// :param array The array to source from. /// :return An array with unique values. public class func uniq<T : Hashable>(array: [T]) -> [T] { var result: [T] = [] var map: [T: Bool] = [T: Bool]() for elem in array { if map[elem] == .None { result.append(elem) } map[elem] = true } return result } /// Create a duplicate-value-free version of an array based on the condition. /// Uses the last value generated by the condition function /// /// :param array The array to source from. /// :param condition Called per iteration /// :return An array with unique values. public class func uniq<T: Hashable, U: Hashable>(array: [T], by condition: (T) -> U) -> [T] { var result: [T] = [] var map : [U: Bool] = [U: Bool]() for elem in array { let val = condition(elem) if map[val] == .None { result.append(elem) } map[val] = true } return result } /// Creates an array of values of a given dictionary. /// /// :param dictionary The dictionary to source from. /// :return An array of values from the dictionary. public class func values<T, U>(dictionary: [T: U]) -> [U] { var result : [U] = [] for value in dictionary.values { result.append(value) } return result } /// Creates an array excluding all provided values. /// /// :param array The array to source from. /// :param values Values to exclude. /// :return Array excluding provided values. public class func without<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Creates an array that is the symmetric difference of the provided arrays. /// /// :param arrays The arrays to perform xor on in order. /// :return Resulting array after performing xor. public class func xor<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Bool] = [T: Bool]() for arr in arrays { for elem in arr { map[elem] = !(map[elem] ?? false) } } var result : [T] = [] for (key, value) in map { if value { result.append(key) } } return result } /// Creates an array of grouped elements, the first of which contains the first elements /// of the given arrays. /// /// :param arrays The arrays to be grouped. /// :return An array of grouped elements. public class func zip<T>(arrays: [T]...) -> [[T]] { var result: [[T]] = [] for _ in self.first(arrays)! as [T] { result.append([] as [T]) } for (index, array) in arrays.enumerate() { for (elemIndex, elem): (Int, T) in array.enumerate() { result[elemIndex].append(elem) } } return result } /// Creates an object composed from arrays of keys and values. /// /// :param keys The array of keys. /// :param values The array of values. /// :return Dictionary based on the keys and values passed in order. public class func zipObject<T, E>(keys: [T], values: [E]) -> [T: E] { var result = [T: E]() for (index, key) in keys.enumerate() { result[key] = values[index] } return result } /// Returns the collection wrapped in the chain object /// /// :param collection of elements /// :return Chain object public class func chain<T>(collection: [T]) -> Chain<T> { return Chain(collection) } } // ________ ___ ___ ________ ___ ________ // |\ ____\|\ \|\ \|\ __ \|\ \|\ ___ \ // \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \\ \ \ // \ \ \ \ \ __ \ \ __ \ \ \ \ \\ \ \ // \ \ \____\ \ \ \ \ \ \ \ \ \ \ \ \\ \ \ // \ \_______\ \__\ \__\ \__\ \__\ \__\ \__\\ \__\ // \|_______|\|__|\|__|\|__|\|__|\|__|\|__| \|__| // public class Chain<C> { private var result: Wrapper<[C]> private var funcQueue: [Wrapper<[C]> -> Wrapper<[C]>] = [] public var value: [C] { get { var result: Wrapper<[C]> = self.result for function in self.funcQueue { result = function(result) } return result.value } } /// Initializer of the wrapper object for chaining. /// /// :param array The array to wrap. public init(_ collection: [C]) { self.result = Wrapper(collection) } /// Get the first object in the wrapper object. /// /// :return First element from the array. public func first() -> C? { return $.first(self.value) } /// Get the second object in the wrapper object. /// /// :return Second element from the array. public func second() -> C? { return $.first(self.value) } /// Get the third object in the wrapper object. /// /// :return Third element from the array. public func third() -> C? { return $.first(self.value) } /// Flattens nested array. /// /// :return The wrapper object. public func flatten() -> Chain { return self.queue { return Wrapper($.flatten($0.value)) } } /// Keeps all the elements except last one. /// /// :return The wrapper object. public func initial() -> Chain { return self.initial(1) } /// Keeps all the elements except last n elements. /// /// :param numElements Number of items to remove from the end of the array. /// :return The wrapper object. public func initial(numElements: Int) -> Chain { return self.queue { return Wrapper($.initial($0.value, numElements: numElements)) } } /// Maps elements to new elements. /// /// :param function Function to map. /// :return The wrapper object. public func map(function: C -> C) -> Chain { return self.queue { var result: [C] = [] for elem: C in $0.value { result.append(function(elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func map(function: (Int, C) -> C) -> Chain { return self.queue { var result: [C] = [] for (index, elem) in $0.value.enumerate() { result.append(function(index, elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (C) -> ()) -> Chain { return self.queue { for elem in $0.value { function(elem) } return $0 } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (Int, C) -> ()) -> Chain { return self.queue { for (index, elem) in $0.value.enumerate() { function(index, elem) } return $0 } } /// Filter elements based on the function passed. /// /// :param function Function to tell whether to keep an element or remove. /// :return The wrapper object. public func filter(function: (C) -> Bool) -> Chain { return self.queue { return Wrapper(($0.value).filter(function)) } } /// Returns if all elements in array are true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether all elements are true according to func function. public func all(function: (C) -> Bool) -> Bool { return $.every(self.value, callback: function) } /// Returns if any element in array is true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether any one element is true according to func function in the array. public func any(function: (C) -> Bool) -> Bool { let resultArr = self.value for elem in resultArr { if function(elem) { return true } } return false } /// Slice the array into smaller size based on start and end value. /// /// :param start Start index to start slicing from. /// :param end End index to stop slicing to and not including element at that index. /// :return The wrapper object. public func slice(start: Int, end: Int = 0) -> Chain { return self.queue { return Wrapper($.slice($0.value, start: start, end: end)) } } private func queue(function: Wrapper<[C]> -> Wrapper<[C]>) -> Chain { funcQueue.append(function) return self } } private struct Wrapper<V> { let value: V init(_ value: V) { self.value = value } }
mit
ebc839ab4f16544d7eac93d7ae8fd0c7
35.798821
138
0.550545
4.260387
false
false
false
false
richardpiazza/SOSwift
Tests/SOSwiftTests/AudienceTests.swift
1
1646
import XCTest @testable import SOSwift class AudienceTests: XCTestCase { static var allTests = [ ("testSchema", testSchema), ("testDecode", testDecode), ("testEncode", testEncode), ] public static let _audienceType = "Programmers" public static let _geographicArea = "5ft of a computer" public static var audience: Audience { let audience = Audience() audience.audienceType = _audienceType let geographicArea = AdministrativeArea() geographicArea.name = _geographicArea audience.geographicArea = geographicArea return audience } func testSchema() throws { XCTAssertEqual(Audience.schemaName, "Audience") } func testDecode() throws { let json = """ { "audienceType": "All", "geographicArea": { "name": "Here" } } """ let audience = try Audience.make(with: json) XCTAssertEqual(audience.audienceType, "All") XCTAssertEqual(audience.geographicArea?.name, "Here") } func testEncode() throws { let dictionary = try AudienceTests.audience.asDictionary() let audienceType = dictionary[Audience.AudienceCodingKeys.audienceType.rawValue] as? String let geographicArea = dictionary[Audience.AudienceCodingKeys.geographicArea.rawValue] as? [String : Any] XCTAssertEqual(audienceType, AudienceTests._audienceType) XCTAssertEqual(geographicArea?["name"] as? String, AudienceTests._geographicArea) } }
mit
5d73333460992224a29459aa566e593c
28.392857
111
0.613001
4.942943
false
true
false
false
s-aska/Justaway-for-iOS
Justaway/ErrorAlert.swift
1
1176
// // ErrorAlert.swift // Justaway // // Created by Shinichiro Aska on 1/17/15. // Copyright (c) 2015 Shinichiro Aska. All rights reserved. // import UIKit class ErrorAlert { class func show(_ title: String, message: String? = nil) { let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .alert) actionSheet.addAction(UIAlertAction( title: "Close", style: .cancel, handler: { action in actionSheet.dismiss(animated: true, completion: nil) })) AlertController.showViewController(actionSheet) } class func show(_ error: NSError) { let title = error.localizedFailureReason ?? error.localizedDescription let message = error.localizedRecoverySuggestion let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .alert) actionSheet.addAction(UIAlertAction( title: "Close", style: .cancel, handler: { action in actionSheet.dismiss(animated: true, completion: nil) })) AlertController.showViewController(actionSheet) } }
mit
4e5a33cafcfba3ce00d6b483fe20dbc0
32.6
99
0.638605
4.941176
false
false
false
false
fgengine/quickly
Quickly/Views/Pagebar/QPagebar.swift
1
7648
// // Quickly // open class QPagebarItem : QCollectionItem { } open class QPagebarCell< Item: QPagebarItem > : QCollectionCell< Item > { } open class QPagebar : QView { public typealias ItemType = IQCollectionController.Cell public weak var delegate: QPagebarDelegate? public var edgeInsets: UIEdgeInsets = UIEdgeInsets() { didSet(oldValue) { if self.edgeInsets != oldValue { self.setNeedsUpdateConstraints() } } } public private(set) var cellTypes: [ItemType.Type] public var itemsSpacing: CGFloat { set(value) { self._collectionLayout.minimumInteritemSpacing = value } get { return self._collectionLayout.minimumInteritemSpacing } } public var items: [QPagebarItem] { set(value) { self._collectionSection.setItems(value) self._collectionController.reload() } get { return self._collectionSection.items as! [QPagebarItem] } } public var selectedItem: QPagebarItem? { get { return self._collectionController.selectedItems.first as? QPagebarItem } } private lazy var _collectionView: QCollectionView = { let view = QCollectionView(frame: self.bounds.inset(by: self.edgeInsets), collectionViewLayout: self._collectionLayout) view.translatesAutoresizingMaskIntoConstraints = false view.showsHorizontalScrollIndicator = false view.showsVerticalScrollIndicator = false view.allowsMultipleSelection = false view.collectionController = self._collectionController return view }() private lazy var _collectionLayout: CollectionLayout = { let layout = CollectionLayout() layout.scrollDirection = .horizontal return layout }() private lazy var _collectionController: CollectionController = { let controller = CollectionController(self, cells: self.cellTypes) controller.sections = [ self._collectionSection ] return controller }() private lazy var _collectionSection: QCollectionSection = { return QCollectionSection(items: []) }() private var _constraints: [NSLayoutConstraint] = [] { willSet { self.removeConstraints(self._constraints) } didSet { self.addConstraints(self._constraints) } } public required init() { fatalError("init(coder:) has not been implemented") } public init( cellTypes: [ItemType.Type] ) { self.cellTypes = cellTypes super.init( frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44) ) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func setup() { super.setup() self.backgroundColor = UIColor.clear self.addSubview(self._collectionView) } open override func updateConstraints() { super.updateConstraints() self._constraints = [ self._collectionView.topLayout == self.topLayout.offset(self.edgeInsets.top), self._collectionView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left), self._collectionView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right), self._collectionView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom) ] } public func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) { self._collectionController.performBatchUpdates(updates, completion: completion) } public func prependItem(_ item: QPagebarItem) { self._collectionSection.prependItem(item) } public func prependItem(_ items: [QPagebarItem]) { self._collectionSection.prependItem(items) } public func appendItem(_ item: QPagebarItem) { self._collectionSection.appendItem(item) } public func appendItem(_ items: [QPagebarItem]) { self._collectionSection.appendItem(items) } public func insertItem(_ item: QPagebarItem, index: Int) { self._collectionSection.insertItem(item, index: index) } public func insertItem(_ items: [QPagebarItem], index: Int) { self._collectionSection.insertItem(items, index: index) } public func deleteItem(_ item: QPagebarItem) { self._collectionSection.deleteItem(item) } public func deleteItem(_ items: [QPagebarItem]) { self._collectionSection.deleteItem(items) } public func replaceItem(_ item: QPagebarItem, index: Int) { self._collectionSection.replaceItem(item, index: index) } public func reloadItem(_ item: QPagebarItem) { self._collectionSection.reloadItem(item) } public func reloadItem(_ items: [QPagebarItem]) { self._collectionSection.reloadItem(items) } public func setSelectedItem(_ selectedItem: QPagebarItem?, animated: Bool) { if let item = selectedItem { if self._collectionController.isSelected(item: item) == false { self._collectionController.select(item: item, scroll: [ .centeredHorizontally, .centeredVertically ], animated: animated) } } else { self._collectionController.selectedItems = [] } } private class CollectionLayout : UICollectionViewFlowLayout { public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let collectionView = self.collectionView, let superAttributes = super.layoutAttributesForElements(in: rect), let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil } let contentSize = self.collectionViewContentSize let boundsSize = collectionView.bounds.size if (contentSize.width < boundsSize.width) || (contentSize.height < boundsSize.height) { let offset = CGPoint( x: (boundsSize.width - contentSize.width) / 2, y: (boundsSize.height - contentSize.height) / 2 ) attributes.forEach({ layoutAttribute in layoutAttribute.frame = layoutAttribute.frame.offsetBy(dx: offset.x, dy: offset.y) }) } attributes.forEach({ layoutAttribute in layoutAttribute.frame = CGRect( origin: layoutAttribute.frame.origin, size: CGSize( width: layoutAttribute.frame.width, height: boundsSize.height ) ) }) return attributes } } private class CollectionController : QCollectionController { public private(set) weak var pagebar: QPagebar? public init(_ pagebar: QPagebar, cells: [ItemType.Type]) { self.pagebar = pagebar super.init(cells: cells) } @objc public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let pagebar = self.pagebar, let delegate = pagebar.delegate else { return } collectionView.scrollToItem(at: indexPath, at: [ .centeredHorizontally, .centeredVertically ], animated: true) delegate.pagebar(pagebar, didSelectItem: pagebar.selectedItem!) } } } public protocol QPagebarDelegate : class { func pagebar(_ pagebar: QPagebar, didSelectItem: QPagebarItem) }
mit
03f2729966663031501fdb96c03d2a8b
34.906103
137
0.640952
4.969461
false
false
false
false
sync/NearbyTrams
NearbyTramsKit/Source/RoutesRepository.swift
1
1256
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import Foundation public protocol RoutesRepositoryDelegate { func routesRepositoryLoadingStateDidChange(repository: RoutesRepository, isLoading loading: Bool) -> Void func routesRepositoryDidFinsishLoading(repository: RoutesRepository, error: NSError?) -> Void } public class RoutesRepository { public var delegate: RoutesRepositoryDelegate? let routesProvider: RoutesProvider let managedObjectContext: NSManagedObjectContext public var isLoading: Bool { willSet { self.delegate?.routesRepositoryLoadingStateDidChange(self, isLoading: newValue) } } public init (routesProvider: RoutesProvider, managedObjectContext: NSManagedObjectContext) { self.routesProvider = routesProvider self.managedObjectContext = managedObjectContext self.isLoading = false } public func update() -> Void { self.isLoading = true routesProvider.getAllRoutesWithManagedObjectContext(managedObjectContext) { routeObjectIds, error -> Void in self.isLoading = false self.delegate?.routesRepositoryDidFinsishLoading(self, error: error) } } }
mit
d77159c6e2a078d0b1fae7177ebde355
28.904762
109
0.707803
5.25523
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPIGeofence/PIUnprotectedPreferences.swift
1
3014
/** * IBMPIGeofence * PIUnprotectedPreferences.swift * * Performs all communication to the PI Rest API. * * © Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 class PIUnprotectedPreferences { let name:String private var dict:NSMutableDictionary static let sharedInstance = PIUnprotectedPreferences(name: "IBMPIUnprotectedPreferences") private static var applicationLibraryDirectory:NSURL { return NSFileManager.defaultManager().URLsForDirectory(.LibraryDirectory, inDomains: .UserDomainMask).first! as NSURL } init(name:String) { self.name = name let url = self.dynamicType.applicationLibraryDirectory.URLByAppendingPathComponent("\(name).plist") if let dict = NSMutableDictionary(contentsOfURL: url) { self.dict = dict } else { dict = NSMutableDictionary() } } func synchronize() { let url = self.dynamicType.applicationLibraryDirectory.URLByAppendingPathComponent("\(name).plist") self.dict.writeToURL(url, atomically: true) do { try NSFileManager.defaultManager().setAttributes([NSFileProtectionKey:NSFileProtectionNone], ofItemAtPath: url.path!) } catch { print(error) } } func objectForKey(defaultName: String) -> AnyObject? { return self.dict[defaultName] } func setObject(value: AnyObject?, forKey defaultName: String) { if let value = value { self.dict[defaultName] = value } else { self.dict.removeObjectForKey(defaultName) } } func removeObjectForKey(defaultName: String) { self.dict.removeObjectForKey(defaultName) } func stringForKey(defaultName: String) -> String? { return self.dict[defaultName] as? String } func integerForKey(defaultName: String) -> Int? { return self.dict[defaultName] as? Int } func floatForKey(defaultName: String) -> Float? { return self.dict[defaultName] as? Float } func doubleForKey(defaultName: String) -> Double? { return self.dict[defaultName] as? Double } func boolForKey(defaultName: String) -> Bool? { return self.dict[defaultName] as? Bool } func setInteger(value: Int, forKey defaultName: String) { self.dict[defaultName] = NSNumber(integer: value) } func setFloat(value: Float, forKey defaultName: String) { self.dict[defaultName] = NSNumber(float: value) } func setDouble(value: Double, forKey defaultName: String) { self.dict[defaultName] = NSNumber(double: value) } func setBool(value: Bool, forKey defaultName: String) { self.dict[defaultName] = NSNumber(bool: value) } }
epl-1.0
3e46834c4a7e59ce68d5cd4cbd0e5268
26.153153
120
0.743777
3.867779
false
false
false
false
Arcovv/CleanArchitectureRxSwift
CleanArchitectureRxSwift/Scenes/EditPost/EditPostViewModel.swift
1
1956
import Domain import RxSwift import RxCocoa final class EditPostViewModel: ViewModelType { private let post: Post private let useCase: PostsUseCase init(post: Post, useCase: PostsUseCase) { self.post = post self.useCase = useCase } func transform(input: Input) -> Output { let errorTracker = ErrorTracker() let editing = input.editTrigger.scan(false) { editing, _ in return !editing }.startWith(false) let saveTrigger = editing.skip(1) //we dont need initial state .filter { $0 == false } .mapToVoid() let titleAndDetails = Driver.combineLatest(input.title, input.details) { $0 } let post = Driver.combineLatest(Driver.just(self.post), titleAndDetails) { (post, titleAndDetails) -> Post in return Post(body: titleAndDetails.1, title: titleAndDetails.0, uid: "7", userId: "8") }.startWith(self.post) let editButtonTitle = editing.map { editing -> String in return editing == true ? "Save" : "Edit" } let savePost = saveTrigger.withLatestFrom(post) .flatMapLatest { post in return self.useCase.save(post: post) .trackError(errorTracker) .asDriverOnErrorJustComplete() } return Output(editButtonTitle: editButtonTitle, save: savePost, editing: editing, post: post, error: errorTracker.asDriver()) } } extension EditPostViewModel { struct Input { let editTrigger: Driver<Void> let title: Driver<String> let details: Driver<String> } struct Output { let editButtonTitle: Driver<String> let save: Driver<Void> let editing: Driver<Bool> let post: Driver<Post> let error: Driver<Error> } }
mit
ce70d87279cd47dbe423010161ee0cfc
31.6
117
0.577198
4.559441
false
true
false
false
MiniDOM/MiniDOM
Examples/FeedViewer/FeedViewer/Feed.swift
1
2184
// // Feed.swift // FeedViewer // // Copyright 2017-2020 Anodized Software, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation import MiniDOM struct Feed { let title: String let items: [Item] init?(document: Document) { var document = document document.normalize() guard let title = document.evaluate(path: ["rss", "channel", "title", "#text"]).first(ofType: Text.self)?.nodeValue else { return nil } let itemElements = document.evaluate(path: ["rss", "channel", "item"]).only(ofType: Element.self) let items = itemElements.compactMap({ Item(element: $0) }) self.title = title self.items = items } } struct Item { let title: String let link: URL init?(element: Element) { guard let linkText = element.evaluate(path: ["link", "#text"]).first?.nodeValue, let link = URL(string: linkText), let title = element.evaluate(path: ["title", "#text"]).first?.nodeValue else { return nil } self.title = title self.link = link } }
mit
3f9f61eb5505bd1c3af54f931955fa24
33.125
130
0.667125
4.240777
false
false
false
false
dzenbot/Iconic
Samples/Tests/IconImageViewSnapshotTests.swift
1
2046
// // IconImageViewTests.swift // Iconic // // Copyright © 2019 The Home Assistant Authors // Licensed under the Apache 2.0 license // For more information see https://github.com/home-assistant/Iconic class IconImageViewTests: BaseSnapshotTestCase { let defaultIcon = FontAwesomeIcon.refreshIcon let defaultFrame = CGRect(x: 0, y: 0, width: 30, height: 30) override func setUp() { super.setUp() // Toggle on for recording a new snapshot. Remember to turn it back off to validate the test. self.recordMode = false } override func tearDown() { super.tearDown() } func testImageViewIconUpdate() { let imageView = IconImageView(frame: defaultFrame) imageView.iconDrawable = FontAwesomeIcon.paperClipIcon self.verifyView(imageView, withIdentifier: "") } func testImageViewColorUpdate() { let imageView = IconImageView(frame: defaultFrame) imageView.iconDrawable = defaultIcon imageView.tintColor = .orange self.verifyView(imageView, withIdentifier: "") } func testImageViewSizeUpdate() { let rect = CGRect(x: 0, y: 0, width: 60, height: 60) let imageView = IconImageView(frame: rect) imageView.iconDrawable = defaultIcon imageView.frame = defaultFrame self.verifyView(imageView, withIdentifier: "") } func testImageViewNoIcon() { let imageView = IconImageView(frame: defaultFrame) XCTAssertNil(imageView.iconDrawable) XCTAssertNil(imageView.image) } func testImageViewEmtpyFrame() { let imageView = IconImageView() imageView.iconDrawable = defaultIcon XCTAssertTrue(imageView.frame.isEmpty) // No image update when the frame is empty XCTAssertNotNil(imageView.iconDrawable) XCTAssertNil(imageView.image) imageView.frame = defaultFrame // Image should not be nil at this point, with a valid frame XCTAssertNotNil(imageView.image) } }
mit
3a1cb850841a0bb8f05235e052b2fe1b
25.558442
101
0.667971
4.690367
false
true
false
false
klundberg/swift-corelibs-foundation
Foundation/CharacterSet.swift
1
19368
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// private func _utfRangeToNSRange(_ inRange : Range<UnicodeScalar>) -> NSRange { return NSMakeRange(Int(inRange.lowerBound.value), Int(inRange.upperBound.value - inRange.lowerBound.value)) } internal final class _SwiftNSCharacterSet : NSCharacterSet, _SwiftNativeFoundationType { internal typealias ImmutableType = NSCharacterSet internal typealias MutableType = NSMutableCharacterSet var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType> init(immutableObject: AnyObject) { // Take ownership. __wrapped = .Immutable(Unmanaged.passRetained(_unsafeReferenceCast(immutableObject, to: ImmutableType.self))) super.init() } init(mutableObject: AnyObject) { // Take ownership. __wrapped = .Mutable(Unmanaged.passRetained(_unsafeReferenceCast(mutableObject, to: MutableType.self))) super.init() } internal required init(unmanagedImmutableObject: Unmanaged<ImmutableType>) { // Take ownership. __wrapped = .Immutable(unmanagedImmutableObject) super.init() } internal required init(unmanagedMutableObject: Unmanaged<MutableType>) { // Take ownership. __wrapped = .Mutable(unmanagedMutableObject) super.init() } convenience required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { releaseWrappedObject() } // These for some reason cause a crash in the compiler // Stubs // ----- // Immutable override var bitmapRepresentation: Data { return _mapUnmanaged { $0.bitmapRepresentation } } override var inverted : CharacterSet { return _mapUnmanaged { $0.inverted } } override func hasMember(inPlane plane: UInt8) -> Bool { return _mapUnmanaged {$0.hasMember(inPlane: plane) } } override func characterIsMember(_ member: unichar) -> Bool { return _mapUnmanaged { $0.characterIsMember(member) } } override func longCharacterIsMember(_ member: UInt32) -> Bool { return _mapUnmanaged { $0.longCharacterIsMember(member) } } override func isSuperset(of other: CharacterSet) -> Bool { return _mapUnmanaged { $0.isSuperset(of: other) } } } /** A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search. This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class. */ public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra, _MutablePairBoxing { public typealias ReferenceType = NSCharacterSet internal typealias SwiftNSWrapping = _SwiftNSCharacterSet internal typealias ImmutableType = SwiftNSWrapping.ImmutableType internal typealias MutableType = SwiftNSWrapping.MutableType internal var _wrapped : _SwiftNSCharacterSet // MARK: Init methods internal init(_bridged characterSet: NSCharacterSet) { // We must copy the input because it might be mutable; just like storing a value type in ObjC _wrapped = _SwiftNSCharacterSet(immutableObject: characterSet.copy()) } /// Initialize an empty instance. public init() { _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet()) } /// Initialize with a range of integers. /// /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired. public init(charactersIn range: Range<UnicodeScalar>) { _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range))) } /// Initialize with a closed range of integers. /// /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired. public init(charactersIn range: ClosedRange<UnicodeScalar>) { let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1) _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(halfOpenRange))) } /// Initialize with the characters in the given string. /// /// - parameter string: The string content to inspect for characters. public init(charactersIn string: String) { _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(charactersIn: string)) } /// Initialize with a bitmap representation. /// /// This method is useful for creating a character set object with data from a file or other external data source. /// - parameter data: The bitmap representation. public init(bitmapRepresentation data: Data) { _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(bitmapRepresentation: data)) } /// Initialize with the contents of a file. /// /// Returns `nil` if there was an error reading the file. /// - parameter file: The file to read. public init?(contentsOfFile file: String) { if let interior = NSCharacterSet(contentsOfFile: file) { _wrapped = _SwiftNSCharacterSet(immutableObject: interior) } else { return nil } } public var hashValue: Int { return _mapUnmanaged { $0.hashValue } } public var description: String { return _mapUnmanaged { $0.description } } public var debugDescription: String { return _mapUnmanaged { $0.debugDescription } } private init(reference: NSCharacterSet) { _wrapped = _SwiftNSCharacterSet(immutableObject: reference) } // MARK: Static functions /// Returns a character set containing the characters in Unicode General Category Cc and Cf. public static var controlCharacters : CharacterSet { return NSCharacterSet.controlCharacters() } /// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`. public static var whitespaces : CharacterSet { return NSCharacterSet.whitespaces() } /// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`. public static var whitespacesAndNewlines : CharacterSet { return NSCharacterSet.whitespacesAndNewlines() } /// Returns a character set containing the characters in the category of Decimal Numbers. public static var decimalDigits : CharacterSet { return NSCharacterSet.decimalDigits() } /// Returns a character set containing the characters in Unicode General Category L* & M*. public static var letters : CharacterSet { return NSCharacterSet.letters() } /// Returns a character set containing the characters in Unicode General Category Ll. public static var lowercaseLetters : CharacterSet { return NSCharacterSet.lowercaseLetters() } /// Returns a character set containing the characters in Unicode General Category Lu and Lt. public static var uppercaseLetters : CharacterSet { return NSCharacterSet.uppercaseLetters() } /// Returns a character set containing the characters in Unicode General Category M*. public static var nonBaseCharacters : CharacterSet { return NSCharacterSet.nonBaseCharacters() } /// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*. public static var alphanumerics : CharacterSet { return NSCharacterSet.alphanumerics() } /// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of “standard decomposition” in version 3.2 of the Unicode character encoding standard. public static var decomposables : CharacterSet { return NSCharacterSet.decomposables() } /// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard. public static var illegalCharacters : CharacterSet { return NSCharacterSet.illegalCharacters() } /// Returns a character set containing the characters in Unicode General Category P*. public static var punctuation : CharacterSet { return NSCharacterSet.punctuation() } /// Returns a character set containing the characters in Unicode General Category Lt. public static var capitalizedLetters : CharacterSet { return NSCharacterSet.capitalizedLetters() } /// Returns a character set containing the characters in Unicode General Category S*. public static var symbols : CharacterSet { return NSCharacterSet.symbols() } /// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`). public static var newlines : CharacterSet { return NSCharacterSet.newlines() } // MARK: Static functions, from NSURL /// Returns the character set for characters allowed in a user URL subcomponent. public static var urlUserAllowed : CharacterSet { return NSCharacterSet.urlUserAllowed } /// Returns the character set for characters allowed in a password URL subcomponent. public static var urlPasswordAllowed : CharacterSet { return NSCharacterSet.urlPasswordAllowed } /// Returns the character set for characters allowed in a host URL subcomponent. public static var urlHostAllowed : CharacterSet { return NSCharacterSet.urlHostAllowed } /// Returns the character set for characters allowed in a path URL component. public static var urlPathAllowed : CharacterSet { return NSCharacterSet.urlPathAllowed } /// Returns the character set for characters allowed in a query URL component. public static var urlQueryAllowed : CharacterSet { return NSCharacterSet.urlQueryAllowed } /// Returns the character set for characters allowed in a fragment URL component. public static var urlFragmentAllowed : CharacterSet { return NSCharacterSet.urlFragmentAllowed } // MARK: Immutable functions /// Returns a representation of the `CharacterSet` in binary format. public var bitmapRepresentation: Data { return _mapUnmanaged { $0.bitmapRepresentation } } /// Returns an inverted copy of the receiver. public var inverted : CharacterSet { return _mapUnmanaged { $0.inverted } } /// Returns true if the `CharacterSet` has a member in the specified plane. /// /// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0. public func hasMember(inPlane plane: UInt8) -> Bool { return _mapUnmanaged { $0.hasMember(inPlane: plane) } } // MARK: Mutable functions /// Insert a range of integer values in the `CharacterSet`. /// /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired. public mutating func insert(charactersIn range: Range<UnicodeScalar>) { let nsRange = _utfRangeToNSRange(range) _applyUnmanagedMutation { $0.addCharacters(in: nsRange) } } /// Insert a closed range of integer values in the `CharacterSet`. /// /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired. public mutating func insert(charactersIn range: ClosedRange<UnicodeScalar>) { let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1) let nsRange = _utfRangeToNSRange(halfOpenRange) _applyUnmanagedMutation { $0.addCharacters(in: nsRange) } } /// Remove a range of integer values from the `CharacterSet`. public mutating func remove(charactersIn range: Range<UnicodeScalar>) { let nsRange = _utfRangeToNSRange(range) _applyUnmanagedMutation { $0.removeCharacters(in: nsRange) } } /// Remove a closed range of integer values from the `CharacterSet`. public mutating func remove(charactersIn range: ClosedRange<UnicodeScalar>) { let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1) let nsRange = _utfRangeToNSRange(halfOpenRange) _applyUnmanagedMutation { $0.removeCharacters(in: nsRange) } } /// Insert the values from the specified string into the `CharacterSet`. public mutating func insert(charactersIn string: String) { _applyUnmanagedMutation { $0.addCharacters(in: string) } } /// Remove the values from the specified string from the `CharacterSet`. public mutating func remove(charactersIn string: String) { _applyUnmanagedMutation { $0.removeCharacters(in: string) } } /// Invert the contents of the `CharacterSet`. public mutating func invert() { _applyUnmanagedMutation { $0.invert() } } // ----- // MARK: - // MARK: SetAlgebraType /// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`. /// /// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func insert(_ character: UnicodeScalar) -> (inserted: Bool, memberAfterInsert: UnicodeScalar) { let nsRange = NSMakeRange(Int(character.value), 1) _applyUnmanagedMutation { $0.addCharacters(in: nsRange) } // TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet return (true, character) } /// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`. /// /// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func update(with character: UnicodeScalar) -> UnicodeScalar? { let nsRange = NSMakeRange(Int(character.value), 1) _applyUnmanagedMutation { $0.addCharacters(in: nsRange) } // TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet return character } /// Remove a `UnicodeScalar` representation of a character from the `CharacterSet`. /// /// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func remove(_ character: UnicodeScalar) -> UnicodeScalar? { // TODO: Add method to NSCharacterSet to do this in one call let result : UnicodeScalar? = contains(character) ? character : nil let r = NSMakeRange(Int(character.value), 1) _applyUnmanagedMutation { $0.removeCharacters(in: r) } return result } /// Test for membership of a particular `UnicodeScalar` in the `CharacterSet`. public func contains(_ member: UnicodeScalar) -> Bool { return _mapUnmanaged { $0.longCharacterIsMember(member.value) } } /// Returns a union of the `CharacterSet` with another `CharacterSet`. public func union(_ other: CharacterSet) -> CharacterSet { // The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here var result = self result.formUnion(other) return result } /// Sets the value to a union of the `CharacterSet` with another `CharacterSet`. public mutating func formUnion(_ other: CharacterSet) { _applyUnmanagedMutation { $0.formUnion(with: other) } } /// Returns an intersection of the `CharacterSet` with another `CharacterSet`. public func intersection(_ other: CharacterSet) -> CharacterSet { // The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here var result = self result.formIntersection(other) return result } /// Sets the value to the intersection of the `CharacterSet` with another `CharacterSet`. public mutating func formIntersection(_ other: CharacterSet) { _applyUnmanagedMutation { $0.formIntersection(with: other) } } /// Returns the exclusive or of the `CharacterSet` with another `CharacterSet`. public func symmetricDifference(_ other: CharacterSet) -> CharacterSet { return union(other).subtracting(intersection(other)) } /// Sets the value to the exclusive or of the `CharacterSet` with another `CharacterSet`. public mutating func formSymmetricDifference(_ other: CharacterSet) { self = symmetricDifference(other) } /// Returns true if `self` is a superset of `other`. public func isSuperset(of other: CharacterSet) -> Bool { return _mapUnmanaged { $0.isSuperset(of: other) } } } /// Returns true if the two `CharacterSet`s are equal. public func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool { return lhs._wrapped.isEqual(rhs._bridgeToObjectiveC()) } // MARK: Objective-C Bridging extension CharacterSet { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSCharacterSet.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSCharacterSet { return unsafeBitCast(_wrapped, to: NSCharacterSet.self) } public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) { result = CharacterSet(_bridged: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool { result = CharacterSet(_bridged: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet { return CharacterSet(_bridged: source!) } } extension CharacterSet { public func contains(_ member: unichar) -> Bool { return contains(UnicodeScalar(member)) } }
apache-2.0
1f2945d720d9e7adf9a757f3123042dc
38.27789
274
0.675687
5.27342
false
false
false
false
thanegill/RxSwift
RxExample/RxExample/Examples/GitHubSearchRepositories/UINavigationController+Extensions.swift
4
1172
// // UINavigationController+Extensions.swift // RxExample // // Created by Krunoslav Zaher on 12/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif struct Colors { static let OfflineColor = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0) static let OnlineColor = nil as UIColor? } extension UINavigationController { var rx_serviceState: AnyObserver<ServiceState?> { return AnyObserver { event in switch event { case .Next(let maybeServiceState): // if nil is being bound, then don't change color, it's not perfect, but :) if let serviceState = maybeServiceState { let isOffline = serviceState ?? .Online == .Offline self.navigationBar.backgroundColor = isOffline ? Colors.OfflineColor : Colors.OnlineColor } case .Error(let error): bindingErrorToInterface(error) case .Completed: break } } } }
mit
b0dc2e170a85760fcf75440e29589a85
27.560976
91
0.584116
4.684
false
false
false
false