repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jinMaoHuiHui/WhiteBoard
WhiteBoard/WhiteBoard/Canvas/Canvas/Array+Remove.swift
1
600
// // Array+Remove.swift // WhiteBoard // // Created by jinmao on 2016/12/15. // Copyright © 2016年 jinmao. All rights reserved. // import Foundation extension Array where Element: Equatable { mutating func removeEqualItems(_ item: Element) { self = self.filter(){ return $0 != item } } mutating func removeFirstEqualItem(item: Element) { guard var currentItem = self.first else { return } var index = 0 while currentItem != item { index += 1 currentItem = self[index] } self.remove(at: index) } }
mit
f585058b03cb79552c506fdef7049894
21.961538
58
0.596315
4.006711
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 15 - AnimatedSplash/AnimatedSplash/AppDelegate.swift
1
4364
// // AppDelegate.swift // AnimatedSplash <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/21. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CAAnimationDelegate { var window: UIWindow? var mask: CALayer? var imageView: UIImageView? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = UIViewController() let imageView = UIImageView(frame: self.window!.frame) imageView.image = UIImage(named: "screen") self.window!.addSubview(imageView) self.mask = CALayer() self.mask!.contents = UIImage(named: "twitter")?.cgImage self.mask!.contentsGravity = kCAGravityResizeAspect self.mask!.bounds = CGRect(x: 0, y: 0, width: 100, height: 81) self.mask!.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.mask!.position = CGPoint(x: imageView.frame.size.width / 2, y: imageView.frame.size.height / 2) imageView.layer.mask = mask self.imageView = imageView animateMask() self.window!.backgroundColor = UIColor(red:0.117, green:0.631, blue:0.949, alpha:1) self.window!.makeKeyAndVisible() UIApplication.shared.isStatusBarHidden = true return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func animateMask() { let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 0.6 keyFrameAnimation.beginTime = CACurrentMediaTime() + 0.5 keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)] let initalBounds = NSValue(cgRect: mask!.bounds) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 90, height: 73)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 1600, height: 1300)) keyFrameAnimation.values = [initalBounds, secondBounds, finalBounds] keyFrameAnimation.keyTimes = [0, 0.3, 1] self.mask!.add(keyFrameAnimation, forKey: "bounds") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.imageView!.layer.mask = nil } }
mit
f065bf03de9ac2298e5919ee1aed7b3e
46.402174
285
0.703508
4.978311
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/LessonMenuViewController.swift
1
1962
// // LessonMenuViewController.swift // SwiftGL // // Created by jerry on 2016/4/28. // Copyright © 2016年 Jerry Chan. All rights reserved. // import UIKit class LessonMenuViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { /* func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { }*/ //number of section func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } // cell num in section func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //self.collectionView = collectionView return 10 } //get cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "lessonCell", for: indexPath) return cell } //select cell func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let lessonDetailVC = splitViewController?.viewControllers.last as!LessonMenuDetailViewController } @IBAction func exitLesson(_ sender: UIBarButtonItem) { presentingViewController?.dismiss(animated: true, completion:nil) print("exit") } @IBAction func startLessonButtonTouched(_ sender: UIButton) { print("...") /* PaintViewController.courseTitle = "upsidedown" let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate let rootViewController = appdelegate.window?.rootViewController print(rootViewController) rootViewController?.showViewController(getViewController("paintView"), sender: nil) */ } }
mit
8db0e1d4fe1c90bd7356fa720544ad21
32.20339
171
0.694232
5.936364
false
false
false
false
mmiroslav/LinEqua
Example/LinEqua/Data/Data.swift
1
1934
// // Data.swift // LinEqua // // Created by Miroslav Milivojevic on 7/5/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import LinEqua class Data: NSObject { static let shared = Data() var matrix: Matrix? { if insertedMatrix != nil { return insertedMatrix } return generatedMatrix } var generatedMatrix: Matrix? var insertedMatrix: Matrix? var resultsGauss: [Double]? = [] var resultsGaussJordan: [Double]? = [] private override init() {} func calculateGausError() -> Double { guard let resultsGauss = resultsGauss else { return 0.0 } let gaussResultsVector = Vector(withArray: resultsGauss) guard let matrix = generatedMatrix else {return 0.0} var sumGausErrors = 0.0 for row in matrix.elements { let rowVector = Vector(withArray: row) let result = rowVector.popLast() sumGausErrors += result! - (rowVector * gaussResultsVector).sum() } let rv = sumGausErrors / Double(gaussResultsVector.count) print("Gauss error: \(rv)") return abs(rv) } func calculateGausJordanError() -> Double { guard let resultsGauss = resultsGaussJordan else { return 0.0 } let gaussJordanResultsVector = Vector(withArray: resultsGauss) guard let matrix = generatedMatrix else {return 0.0} var sumGausJordanErrors = 0.0 for row in matrix.elements { let rowVector = Vector(withArray: row) let result = rowVector.popLast() sumGausJordanErrors += result! - (rowVector * gaussJordanResultsVector).sum() } let rv = sumGausJordanErrors / Double(gaussJordanResultsVector.count) print("Gauss Jordan error: \(rv)") return abs(rv) } }
mit
7464f939c5f83f95d0004b6c9b9711cf
27.850746
89
0.595965
4.095339
false
false
false
false
LogTenSafe/MacOSX
LogTenSafe/Source/Delegates and Controllers/Main View/MainViewController.swift
1
11036
import Combine import Dispatch import Foundation import Alamofire import Defaults /** * An enum representing which sheet is being shown over the main window. Since * only one sheet view is associated with a window, this enum is used to * determine which subview is rendered into that view. */ enum MainViewSheet { /** The generic "error occurred" sheet. */ case error /** The login form sheet. */ case login /** The upload progress bar sheet. */ case uploadProgress /** The download progress bar sheet. */ case downloadProgress /** No sheet is currently being displayed. */ case none } /** * This hefty class is the primary controller between the main view (the list of * backups and all primary application controls) and the various services that * communicate with the filesystem and backend (APIService, LogbookService, * etc.). * * This class mainly exposes reactive bindings that views can use to bind to * data received by the services, and listens for reactive changes to UI * controls, updating backend services as necessary. * * Because ObservableObject requires one object be shared by all views in a view * hierarchy, this class overfloweth with functionality, providing any and all * bindings that any subview might need to render itself or expose its * functionality. */ @available(OSX 11.0, *) @objc class MainViewController: NSObject, ObservableObject { /** The API service to use. */ let APIService: APIService /** The local logbook file service to use. */ let logbookService: LogbookService /** The automatic backup service to use. */ let autoBackupService: AutoBackupService /** The Action Cable WebSockets client to use. */ var backupWSService: ActionCableService<Backup>? = nil /** Publisher that pipes whether or not the user is logged in. */ @Published var loggedIn = false /** Publisher that pipes the auto-backup setting to the UI. */ @Published var disableAutoBackup = false /** Publisher that pipes to the progress spinner on the login sheet. */ @Published var loggingIn = false /** * Publisher that pipes to the login sheet's error text when a login error * occurs. */ @Published var loginError: Error? = nil /** Publisher that pipes to the progress spinner in the main backup list. */ @Published var loadingBackups = false /** Publisher that pipes the list of Backups to the main view. */ @Published var backups: Array<Backup> = [] /** * Publisher that indicates if the current network operation is an upload. */ @Published var makingBackup = false /** * Publisher that indicates if the current network operation is a download. */ @Published var restoringBackup = false //TODO can be combined with the progress var? /** Publisher that pipes upload progress to the progress sheet. */ @Published var backupProgress: Progress? = nil /** Publisher that pipes download progress to the progress sheet. */ @Published var downloadProgress: Progress? = nil /** Publisher that pipes an error to the generic error sheet. */ @Published var error: Error? = nil /** Publisher that pipes to the view which sheet is shown (if any). */ @Published var currentSheet: MainViewSheet = .none /** Publisher that pipes to the view whether a sheet should be displayed. */ @Published var sheetActive = false private var cancellables = Set<AnyCancellable>() /** * Creates an instance with the default service classes. */ convenience override init() { self.init(APIService: .init(), logbookService: .init()) } /** * Creates an instance with the given service classes. */ required init(APIService: APIService, logbookService: LogbookService) { self.APIService = APIService self.logbookService = logbookService self.autoBackupService = AutoBackupService(logbookService: logbookService, APIService: APIService) super.init() Defaults.publisher(.JWT) .map { $0.newValue != nil } .receive(on: RunLoop.main).assign(to: &$loggedIn) //TODO do we need the whole big-ass type annotation here? let sheetPublisher: Publishers.Map<Publishers.CombineLatest4<AnyPublisher<Defaults.KeyChange<String?>, Never>, Published<Progress?>.Publisher, Published<Progress?>.Publisher, Published<Error?>.Publisher>, MainViewSheet> = Defaults.publisher(.JWT).combineLatest($backupProgress, $downloadProgress, $error).map { JWT, backupProgress, downloadProgress, error in if error != nil { return .error } if JWT.newValue == nil { return .login } if backupProgress != nil { return .uploadProgress } if downloadProgress != nil { return .downloadProgress } return .none } sheetPublisher.receive(on: RunLoop.main).assign(to: &$currentSheet) sheetPublisher.map { $0 != .none }.receive(on: RunLoop.main).assign(to: &$sheetActive) autoBackupService.started = Defaults[.autoBackup] Defaults.publisher(.autoBackup) .map { $0.newValue } .receive(on: RunLoop.main).assign(to: \.started, on: autoBackupService) .store(in: &cancellables) Defaults.publisher(.logbookData) .map { $0.newValue == nil } .receive(on: RunLoop.main).assign(to: &$disableAutoBackup) Defaults.publisher(.JWT).map { $0.newValue }.receive(on: RunLoop.main).sink { [weak self] JWT in if let JWT = JWT { self?.backupWSService?.stop() self?.backupWSService = ActionCableService(URL: websocketsURL, receive: { [weak self] message in switch message { case .success(let backup): self?.receiveBackup(backup) case .failure(let error): self?.error = error } }) _ = self?.backupWSService!.start(JWT: JWT, channel: "BackupsChannel") } else { self?.backupWSService?.stop() } }.store(in: &cancellables) } deinit { for c in cancellables { c.cancel() } } /** * Called when the user requests a login. Attempts to log the user in and * load their backup list. */ func logIn(email: String, password: String) { loginError = nil loggingIn = true do { try APIService.logIn(login: Login(email: email, password: password)) { [weak self] result in DispatchQueue.main.async { switch result { case .success(): self?.loadBackups() case .failure(let error): if isAuthorizationError(error) { self?.loginError = LogTenSafeError.invalidLogin } else { self?.loginError = error } } self?.loggingIn = false } } } catch (let error) { loginError = error loggingIn = false } } /** * Called when the user requests a logout. Logs the user out, deletes the * JWT, and clears the Backup list from memory. */ func logOut() { APIService.logOut() self.backups.removeAll() } /** * Uses the API service to load a list of backups. */ func loadBackups() { loadingBackups = true error = nil APIService.loadBackups { [weak self] result in DispatchQueue.main.async { switch result { case .success(let backups): self?.backups = backups case .failure(let error): if !isAuthorizationError(error) { self?.error = error } } self?.loadingBackups = false } } } private func receiveBackup(_ backup: Backup) { if backup.isDestroyed { backups.removeAll { $0 == backup } } else { if let existingIndex = backups.firstIndex(of: backup) { backups[existingIndex] = backup } else { backups.append(backup) } backups.sort { $1.createdAt! < $0.createdAt! } } } func clearError() { error = nil } func addBackup() { do { try _ = logbookService.loadLogbook { logbookURL, finished in DispatchQueue.main.async { [weak self] in self?.makingBackup = true } let hostname: String = Host.current().localizedName ?? "unknown" let backup = DraftBackup(hostname: hostname, logbook: logbookURL) APIService.addBackup(backup, progressHandler: { [weak self] in self?.backupProgress = $0}) { [weak self] result in DispatchQueue.main.async { switch result { case .success: break case .failure(let error): if !isAuthorizationError(error) { self?.error = error } } self?.makingBackup = false self?.backupProgress = nil finished() } } } } catch (let error) { self.makingBackup = false self.backupProgress = nil self.error = error } } func restoreBackup(_ backup: Backup) { do { try _ = logbookService.loadLogbook { logbookURL, finished in DispatchQueue.main.async { [weak self] in self?.restoringBackup = true } APIService.downloadBackup(backup, destination: { _, _ in (logbookURL, [.removePreviousFile]) }, progressHandler: { [weak self] in self?.downloadProgress = $0 }) { [weak self] result in switch result { case .failure(let error): if !isAuthorizationError(error) { self?.error = error } default: break } DispatchQueue.main.async { [weak self] in self?.restoringBackup = false self?.downloadProgress = nil finished() } } } } catch (let error) { self.restoringBackup = false self.downloadProgress = nil self.error = error } } }
mit
9258d91c5facdae0e6bcb439a9cbcde4
36.158249
366
0.566872
5.00272
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ContextSwitchPeerRowItem.swift
1
2990
// // ContextSwitchPeerRowItem.swift // TelegramMac // // Created by keepcoder on 13/01/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit import Postbox class ContextSwitchPeerRowItem: TableRowItem { fileprivate let account:Account fileprivate let peerId:PeerId fileprivate let switchPeer:ChatContextResultSwitchPeer fileprivate let layout:TextViewLayout fileprivate let callback:()->Void init(_ initialSize:NSSize, peerId:PeerId, switchPeer:ChatContextResultSwitchPeer, account:Account, callback:@escaping()->Void) { self.account = account self.peerId = peerId self.switchPeer = switchPeer self.callback = callback layout = TextViewLayout(.initialize(string: switchPeer.text, color: theme.colors.link, font: .normal(.text)), maximumNumberOfLines: 1, truncationType: .end) layout.measure(width: initialSize.width - 40) super.init(initialSize) } override func makeSize(_ width: CGFloat, oldWidth:CGFloat) -> Bool { let success = super.makeSize(width, oldWidth: oldWidth) layout.measure(width: width - 40) return success } override func viewClass() -> AnyClass { return ContextSwitchPeerRowView.self } override var height: CGFloat { return 40 } } class ContextSwitchPeerRowView: TableRowView { private let textView:TextView = TextView() private let overlay:OverlayControl = OverlayControl() required init(frame frameRect: NSRect) { super.init(frame: frameRect) layerContentsRedrawPolicy = .onSetNeedsDisplay textView.userInteractionEnabled = false addSubview(overlay) addSubview(textView) textView.backgroundColor = theme.colors.background overlay.set(handler: { [weak self] _ in if let item = self?.item as? ContextSwitchPeerRowItem { item.callback() } }, for: .Click) } override func set(item: TableRowItem, animated: Bool) { super.set(item: item, animated: animated) needsDisplay = true needsLayout = true } override func layout() { super.layout() if let item = item as? ContextSwitchPeerRowItem { overlay.setFrameSize(frame.size) textView.update(item.layout) textView.center() } } override func draw(_ layer: CALayer, in ctx: CGContext) { super.draw(layer, in: ctx) if let item = item, let table = item.table { if item.index != table.count - 1 { ctx.setFillColor(theme.colors.border.cgColor) ctx.fill(NSMakeRect(0, frame.height - .borderSize, frame.width, .borderSize)) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
dea1be71d27c30a44bffe3a431889e24
30.463158
164
0.639344
4.634109
false
false
false
false
ps2/rileylink_ios
OmniKit/OmnipodCommon/MessageBlocks/VersionResponse.swift
1
8235
// // VersionResponse.swift // OmniKit // // Created by Pete Schwamb on 2/12/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import Foundation fileprivate let assignAddressVersionLength: UInt8 = 0x15 fileprivate let setupPodVersionLength: UInt8 = 0x1B public struct VersionResponse : MessageBlock { public struct FirmwareVersion : CustomStringConvertible { let major: UInt8 let minor: UInt8 let patch: UInt8 public init(encodedData: Data) { major = encodedData[0] minor = encodedData[1] patch = encodedData[2] } public var description: String { return "\(major).\(minor).\(patch)" } } public let blockType: MessageBlockType = .versionResponse public let firmwareVersion: FirmwareVersion // for Eros (PM) 2.x.y, for NXP Dash 3.x.y, for TWI Dash 4.x.y public let iFirmwareVersion: FirmwareVersion // for Eros (PI) same as PM, for Dash BLE firmware version # public let productId: UInt8 // 02 for Eros, 04 for Dash, perhaps 05 for Omnipod 5 public let lot: UInt32 public let tid: UInt32 public let address: UInt32 public let podProgressStatus: PodProgressStatus // These values only included in the shorter 0x15 VersionResponse for the AssignAddress command for Eros. public let gain: UInt8? // 2-bit value, max gain is at 0, min gain is at 2 public let rssi: UInt8? // 6-bit value, max rssi seen 61 // These values only included in the longer 0x1B VersionResponse for the SetupPod command. public let pulseSize: Double? // VVVV / 100,000, must be 0x1388 / 100,000 = 0.05U public let secondsPerBolusPulse: Double? // BR / 8, nominally 0x10 / 8 = 2 seconds per pulse public let secondsPerPrimePulse: Double? // PR / 8, nominally 0x08 / 8 = 1 seconds per priming pulse public let primeUnits: Double? // PP / pulsesPerUnit, nominally 0x34 / 20 = 2.6U public let cannulaInsertionUnits: Double? // CP / pulsesPerUnit, nominally 0x0A / 20 = 0.5U public let serviceDuration: TimeInterval? // PL hours, nominally 0x50 = 80 hours public let data: Data public init(encodedData: Data) throws { let responseLength = encodedData[1] data = encodedData.subdata(in: 0..<Int(responseLength + 2)) switch responseLength { case assignAddressVersionLength: // This is the shorter 0x15 response for the 07 AssignAddress command. // 0 1 2 5 8 9 10 14 18 19 // 01 LL MXMYMZ IXIYIZ ID 0J LLLLLLLL TTTTTTTT GS IIIIIIII // 01 15 020700 020700 02 02 0000a377 0003ab37 9f 1f00ee87 // // LL = 0x15 (assignAddressVersionLength) // PM MX.MY.MZ = 02.07.02 (for PM 2.7.0) // PI IX.IY.IZ = 02.07.02 (for PI 2.7.0) // ID = Product Id (02 for Eros, 04 for Dash, and perhaps 05 for Omnnipod 5) // 0J = Pod progress state (typically 02 for this particular response) // LLLLLLLL = Lot // TTTTTTTT = Tid // GS = ggssssss (Gain/RSSI for Eros only) // IIIIIIII = connection ID address firmwareVersion = FirmwareVersion(encodedData: encodedData.subdata(in: 2..<5)) iFirmwareVersion = FirmwareVersion(encodedData: encodedData.subdata(in: 5..<8)) productId = encodedData[8] guard let progressStatus = PodProgressStatus(rawValue: encodedData[9]) else { throw MessageBlockError.parseError } podProgressStatus = progressStatus lot = encodedData[10...].toBigEndian(UInt32.self) tid = encodedData[14...].toBigEndian(UInt32.self) gain = (encodedData[18] & 0xc0) >> 6 rssi = encodedData[18] & 0x3f address = encodedData[19...].toBigEndian(UInt32.self) // These values only included in the longer 0x1B VersionResponse for the 03 SetupPod command. pulseSize = nil secondsPerBolusPulse = nil secondsPerPrimePulse = nil primeUnits = nil cannulaInsertionUnits = nil serviceDuration = nil case setupPodVersionLength: // This is the longer 0x1B response for the 03 SetupPod command. // 0 1 2 4 5 6 7 8 9 12 15 16 17 21 25 // 01 LL VVVV BR PR PP CP PL MXMYMZ IXIYIZ ID 0J LLLLLLLL TTTTTTTT IIIIIIII // 01 1b 1388 10 08 34 0a 50 020700 020700 02 03 0000a62b 00044794 1f00ee87 // // LL = 0x1b (setupPodVersionMessageLength) // VVVV = 0x1388, pulse Volume in micro-units of U100 insulin per tenth of pulse (5000/100000 = 0.05U per pulse) // BR = 0x10, Basic pulse Rate in # of eighth secs per pulse (16/8 = 2 seconds per pulse) // PR = 0x08, Prime pulse Rate in # of eighth secs per pulse for priming boluses (8/8 = 1 second per priming pulse) // PP = 0x34 = 52, # of Prime Pulses (52 pulses x 0.05U/pulse = 2.6U) // CP = 0x0A = 10, # of Cannula insertion Pulses (10 pulses x 0.05U/pulse = 0.5U) // PL = 0x50 = 80, # of hours maximum Pod Life // PM = MX.MY.MZ = 02.07.02 (for PM 2.7.0 for Eros) // PI = IX.IY.IZ = 02.07.02 (for PI 2.7.0 for Eros) // ID = Product Id (02 for Eros, 04 for Dash, and perhaps 05 for Omnnipod 5) // 0J = Pod progress state (should be 03 for this particular response) // LLLLLLLL = Lot // TTTTTTTT = Tid // IIIIIIII = connection ID address firmwareVersion = FirmwareVersion(encodedData: encodedData.subdata(in: 9..<12)) iFirmwareVersion = FirmwareVersion(encodedData: encodedData.subdata(in: 12..<15)) productId = encodedData[15] guard let progressStatus = PodProgressStatus(rawValue: encodedData[16]) else { throw MessageBlockError.parseError } podProgressStatus = progressStatus lot = encodedData[17...].toBigEndian(UInt32.self) tid = encodedData[21...].toBigEndian(UInt32.self) address = encodedData[25...].toBigEndian(UInt32.self) // These values should be verified elsewhere and appropriately handled. pulseSize = Double(encodedData[2...].toBigEndian(UInt16.self)) / 100000 secondsPerBolusPulse = Double(encodedData[4]) / 8 secondsPerPrimePulse = Double(encodedData[5]) / 8 primeUnits = Double(encodedData[6]) / Pod.pulsesPerUnit cannulaInsertionUnits = Double(encodedData[7]) / Pod.pulsesPerUnit serviceDuration = TimeInterval.hours(Double(encodedData[8])) // These values only included in the shorter 0x15 VersionResponse for the AssignAddress command for Eros. gain = nil rssi = nil default: throw MessageBlockError.parseError } } public var isAssignAddressVersionResponse: Bool { return self.data.count == assignAddressVersionLength + 2 } public var isSetupPodVersionResponse: Bool { return self.data.count == setupPodVersionLength + 2 } } extension VersionResponse: CustomDebugStringConvertible { public var debugDescription: String { return "VersionResponse(lot:\(lot), tid:\(tid), address:\(Data(bigEndian: address).hexadecimalString), firmwareVersion:\(firmwareVersion), iFirmwareVersion:\(iFirmwareVersion), productId:\(productId), podProgressStatus:\(podProgressStatus), gain:\(gain?.description ?? "NA"), rssi:\(rssi?.description ?? "NA"), pulseSize:\(pulseSize?.description ?? "NA"), secondsPerBolusPulse:\(secondsPerBolusPulse?.description ?? "NA"), secondsPerPrimePulse:\(secondsPerPrimePulse?.description ?? "NA"), primeUnits:\(primeUnits?.description ?? "NA"), cannulaInsertionUnits:\(cannulaInsertionUnits?.description ?? "NA"), serviceDuration:\(serviceDuration?.description ?? "NA"), )" } }
mit
b071f15d3a7ab7b4f6b87f7745813003
50.142857
673
0.621326
4.164896
false
false
false
false
xiaoyouPrince/WeiBo
WeiBo/WeiBo/Classes/Tools/HttpTool/HttpTools.swift
1
1325
// // HttpTools.swift // WeiBo // // Created by 渠晓友 on 2017/6/12. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // import UIKit import AFNetworking class HttpTools: NSObject { static let manager = AFHTTPSessionManager() /// 发送带图片的微博 /// /// - Parameters: /// - statusText: 微博内容 /// - image: image /// - finishCallBack: 回调 class func sendStatus(statusText : String ,image : UIImage , finishCallBack : @escaping (_ isSuccess : Bool) -> ()) { let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json" let accessToken = UserAccountViewModel.shareInstance.account?.access_token let params = ["access_token" : accessToken , "status" : statusText] manager.post(urlStr, parameters: params, headers: nil, constructingBodyWith: { (formData) in let imageData = image.jpegData(compressionQuality: 0.5) formData.appendPart(withFileData: imageData!, name: "pic", fileName: "123.png", mimeType: "image/png") }, progress: nil, success: { (_, _) in finishCallBack(true) }) { (_, error) in finishCallBack(false) print(error) } } }
mit
78ca27b6d095206a1e5e7d9c4db7c035
27.622222
121
0.575311
4.395904
false
false
false
false
cnbin/QRCodeReader.swift
QRCodeReader/QRCodeReader.swift
1
8269
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit import AVFoundation /// Reader object base on the `AVCaptureDevice` to read / scan 1D and 2D codes. public final class QRCodeReader: NSObject, AVCaptureMetadataOutputObjectsDelegate { private var defaultDevice: AVCaptureDevice? = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) private var frontDevice: AVCaptureDevice? = { for device in AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) { if let _device = device as? AVCaptureDevice { if _device.position == AVCaptureDevicePosition.Front { return _device } } } return nil }() private lazy var defaultDeviceInput: AVCaptureDeviceInput? = { if let _defaultDevice = self.defaultDevice { do { return try AVCaptureDeviceInput(device: _defaultDevice) } catch _ { return nil } } return nil }() private lazy var frontDeviceInput: AVCaptureDeviceInput? = { if let _frontDevice = self.frontDevice { do { return try AVCaptureDeviceInput(device: _frontDevice) } catch _ { return nil } } return nil }() private var metadataOutput = AVCaptureMetadataOutput() private var session = AVCaptureSession() // MARK: - Managing the Properties /// CALayer that you use to display video as it is being captured by an input device. public lazy var previewLayer: AVCaptureVideoPreviewLayer = { return AVCaptureVideoPreviewLayer(session: self.session) }() /// An array of strings identifying the types of metadata objects to process. public let metadataObjectTypes: [String] // MARK: - Managing the Completion Block /// Block is executing when a QRCode or when the user did stopped the scan. public var completionBlock: ((String?) -> ())? // MARK: - Creating the Code Reader /** Initializes the code reader with an array of metadata object types. - parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process. */ public init(metadataObjectTypes types: [String]) { metadataObjectTypes = types super.init() configureDefaultComponents() } // MARK: - Initializing the AV Components private func configureDefaultComponents() { session.addOutput(metadataOutput) if let _defaultDeviceInput = defaultDeviceInput { session.addInput(_defaultDeviceInput) } metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) metadataOutput.metadataObjectTypes = metadataObjectTypes previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill } /// Switch between the back and the front camera. public func switchDeviceInput() { if let _frontDeviceInput = frontDeviceInput { session.beginConfiguration() if let _currentInput = session.inputs.first as? AVCaptureDeviceInput { session.removeInput(_currentInput) let newDeviceInput = (_currentInput.device.position == .Front) ? defaultDeviceInput : _frontDeviceInput session.addInput(newDeviceInput) } session.commitConfiguration() } } // MARK: - Controlling Reader /// Starts scanning the codes. public func startScanning() { if !session.running { session.startRunning() } } /// Stops scanning the codes. public func stopScanning() { if session.running { session.stopRunning() } } /** Indicates whether the session is currently running. The value of this property is a Bool indicating whether the receiver is running. Clients can key value observe the value of this property to be notified when the session automatically starts or stops running. */ public var running: Bool { get { return session.running } } /** Returns true whether a front device is available. - returns: true whether the device has a front device. */ public func hasFrontDevice() -> Bool { return frontDevice != nil } // MARK: - Managing the Orientation /** Returns the video orientation correspongind to the given interface orientation. - parameter orientation: The orientation of the app's user interface. */ public class func videoOrientationFromInterfaceOrientation(orientation: UIInterfaceOrientation) -> AVCaptureVideoOrientation { switch (orientation) { case .LandscapeLeft: return .LandscapeLeft case .LandscapeRight: return .LandscapeRight case .Portrait: return .Portrait default: return .PortraitUpsideDown } } // MARK: - Checking the Reader Availabilities /** Checks whether the reader is available. - returns: A boolean value that indicates whether the reader is available. */ class func isAvailable() -> Bool { let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) if videoDevices.count == 0 { return false } let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) as AVCaptureDevice do { let _ = try AVCaptureDeviceInput(device: captureDevice) return true } catch _ { return false } } /** Checks and return whether the given metadata object types are supported by the current device. - parameter metadataTypes: An array of strings identifying the types of metadata objects to check. - returns: A boolean value that indicates whether the device supports the given metadata object types. */ public class func supportsMetadataObjectTypes(metadataTypes: [String]? = nil) -> Bool { if !isAvailable() { return false } // Setup components let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) as AVCaptureDevice let deviceInput = try! AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput let output = AVCaptureMetadataOutput() let session = AVCaptureSession() session.addInput(deviceInput) session.addOutput(output) var metadataObjectTypes = metadataTypes if metadataObjectTypes == nil || metadataObjectTypes?.count == 0 { // Check the QRCode metadata object type by default metadataObjectTypes = [AVMetadataObjectTypeQRCode] } for metadataObjectType in metadataObjectTypes! { if !output.availableMetadataObjectTypes.contains({ $0 as! String == metadataObjectType }) { return false } } return true } // MARK: - AVCaptureMetadataOutputObjects Delegate Methods public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { for current in metadataObjects { if let _readableCodeObject = current as? AVMetadataMachineReadableCodeObject { if metadataObjectTypes.contains(_readableCodeObject.type) { stopScanning() let scannedResult = _readableCodeObject.stringValue if let _completionBlock = completionBlock { _completionBlock(scannedResult) } } } } } }
mit
a309f17e55978758d1fd04f669c8bae0
30.32197
167
0.712541
5.317685
false
false
false
false
zhxnlai/simple-twitter-client
twitter/twitter/TWSearchTableViewController.swift
1
9041
// // TWSearchTableViewController.swift // twitter // // Created by Zhixuan Lai on 1/20/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit import Accounts import Social import ReactiveUI import SwiftyJSON import CoreData class TWSearchTableViewController: TWTweetsTableViewController, UISearchBarDelegate { var searchBar = UISearchBar() var managedObjectContext: NSManagedObjectContext! var twitterAccount: ACAccount? override func viewDidLoad() { super.viewDidLoad() searchBar.placeholder = "Search for Tweets" searchBar.delegate = self navigationItem.titleView = searchBar navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel) {_ in self.dismissViewControllerAnimated(true, completion: nil) } let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate managedObjectContext = appDelegate.managedObjectContext! var accountStore = ACAccountStore() var accountTypeTwitter = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccountsWithType(accountTypeTwitter, options: nil) { granted, error in if error == nil { if granted { if let account = accountStore.accountsWithAccountType(accountTypeTwitter).first as? ACAccount { self.twitterAccount = account dispatch_async(dispatch_get_main_queue()) { self.searchBar.becomeFirstResponder() return } } else { println("no twitter account avialable") let alertController = UIAlertController(title: "No Twitter account available", message: "No Twitter account is currently available. Go to settings -> Twitter to login or create one.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .Default) { action in self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(OKAction) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alertController, animated: true, completion: nil) } } } else { let alertController = UIAlertController(title: "Access not granted", message: "Twitter access is not granted. Go to settings -> Twitter to enable it. Do you want to do it now?", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "Sure", style: .Default) { action in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) self.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(OKAction) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alertController, animated: true, completion: nil) } } } else { println(error) } } } // MARK: - UISearchBarDelegate func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { resetRequest() timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "sendRequest", userInfo: nil, repeats: false) } // MARK: - UIScrollViewDelegate override func scrollViewDidScroll(scrollView: UIScrollView) { var bottomY = scrollView.contentOffset.y + scrollView.bounds.height - scrollView.contentInset.bottom if scrollView.contentSize.height <= bottomY + TWTweetTableViewCell.heightForCell() { sendRequest() } } // MARK: - SLRequest var sinceId = -1 var maxId = 0 var loading = false var results = [JSON]() var timer: NSTimer? func resetRequest() { sinceId = -1 maxId = 0 loading = false results = [JSON]() timer?.invalidate() } func sendRequest() { if loading || maxId == sinceId { return } var url = NSURL(string: "https://api.twitter.com/1.1/search/tweets.json") var parameters = [ "max_id": maxId, "since_id": sinceId, "q": searchBar.text ] sinceId = maxId var request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: url, parameters: parameters) request.account = twitterAccount loading = true request.performRequestWithHandler({ data, response, error in if error == nil { let result = JSON(data: data) self.results.append(result) self.sinceId = result["search_metadata"]["max_id"].intValue if let next_url = result["search_metadata"]["next_results"].string { self.maxId = next_url.substringFromIndex(advance(next_url.startIndex, 1)).componentsSeparatedByString("&").reduce(0, { acc, s in var pair = s.componentsSeparatedByString("=") if pair.first! == "max_id" { return Int(NSNumberFormatter().numberFromString(pair.last!)!) } else { return acc } }) } // println("since: \(self.sinceId) max: \(self.maxId)") dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.loading = false } } else { println(error) } }) } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return results.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results[section]["statuses"].arrayValue.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: TWTweetTableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? TWTweetTableViewCell if cell == nil { cell = TWTweetTableViewCell(style: .Default, reuseIdentifier: cellIdentifier) } let json = results[indexPath.section]["statuses"][indexPath.row] cell.setupWithJSON(json) cell.defaultColor = UIColor(red: 227.0 / 255.0, green: 227.0 / 255.0, blue: 227.0 / 255.0, alpha: 1.0) let greenColor = UIColor(red: 85.0 / 255.0, green: 213.0 / 255.0, blue: 80.0 / 255.0, alpha: 1.0) let saveView = viewWithImageNamed("IconDownloadSelected"); cell.setSwipeGestureWithView(saveView, color: greenColor, mode: .Switch, state: .State3) { cell, state, mode in self.saveTweet(json) return } return cell } // MARK: - () func saveTweet(json: JSON) { let (succeed, message) = Tweet.addTweetFromJSON(json, toManagedObjectContext: managedObjectContext) if succeed { var error: NSError? if !managedObjectContext.save(&error) { println("Could not save \(error), \(error?.userInfo)") } } else { let alertController = UIAlertController(title: "Cannot save Tweet", message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .Default) { action in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: nil) } } }
mit
391ab887a6b7e55542a47e28c55afe60
39.725225
231
0.569738
5.594678
false
false
false
false
takeo-asai/math-puzzle
problems/25.swift
1
4548
/* 0 - 3 3 - 1 は交差する 0 - 3 1 - 3 はしない i - j i+a - j-b はする(a, b > 0) start: 左上 end: 右上 */ extension Array { // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // // https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift // https://github.com/pNre/ExSwift/blob/master/LICENSE /** - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } return permutations } } private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0 let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } return endArray } func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]} var combinations: [[Element]] = [] let offset = self.count - indexes.count while true { var combination: [Element] = [] for index in indexes { combination.append(self[index]) } combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { i-- } if i < 0 { break } i++ let start = indexes[i-1] + 1 for j in (i-1)..<indexes.count { indexes[j] = start + j - i + 1 } } return combinations } /** - parameter length: The length of each permutations - returns: All of the permutations of this array of a given length, allowing repeats */ func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } var indexes: [[Int]] = [] indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes) return indexes.map({ $0.map({ i in self[i] }) }) } private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) { if seed.count == length { indexes.append(seed) return } for i in (0..<arrayLength) { var newSeed: [Int] = seed newSeed.append(i) self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes) } } } func isCrossed(x: (Int, Int), _ y: (Int, Int)) -> Bool { let a = x.0 > y.0 ? x : y let b = x.0 > y.0 ? y : x return a.0 > b.0 && a.1 < b.1 } func edgesFromTour(tour: [Int]) -> [(Int, Int)] { var edges: [(Int, Int)] = [] var rest = tour + [0] var present = 0 while let next = rest.first { edges.append((present, next)) present = next rest.removeAtIndex(0) } return edges } func countCrossed(edges: [(Int, Int)]) -> Int { var count = 0 var e = edges while let e0 = e.first { e.removeAtIndex(0) for e1 in e { if isCrossed(e0, e1) { count++ } } } return count } let n = 6 var positions: [Int] = [] positions += (1 ... n).map {$0} positions += (1 ... n).map {$0} // n = 5 ,45 var max = 0 var maxEdges: [(Int, Int)] = [] for tour in positions.permutation(positions.count) { let edges = edgesFromTour(tour) let count = countCrossed(edges) if max < count { max = count maxEdges = edges } } print(max) print(maxEdges) do { assert(true, "assert check") assert(isCrossed((1, 0), (0, 1))) assert(isCrossed((0, 1), (1, 0))) assert(!isCrossed((0, 1), (0, 4))) assert(isCrossed((1, 1), (0, 4))) }
mit
c68bfecff7f5ce9c68d12b90dc66d507
25.564706
112
0.528344
3.457887
false
false
false
false
PokeMapCommunity/PokeMap-iOS
PokeMap/Helpers/JSONHelper.swift
1
884
// // JSONHelper.swift // PokeMap // // Created by Ivan Bruel on 20/07/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation class JSONHelper { class func flatJSON(json: [String: AnyObject?]?) -> [String: AnyObject]? { guard let json = json else { return nil } return json.flatMap({ (pair) -> (String, AnyObject)? in guard let value = pair.1 else { return nil } return (pair.0, value) }).reduce([:], combine: { (dict, pair) -> [String: AnyObject] in var dict = dict dict[pair.0] = pair.1 return dict }) } class func containsKeys(json: [String: AnyObject]?, keys: [String]) -> Bool { guard keys.count > 0 else { return true } guard let json = json else { return false } return keys.reduce(true) { $0.0 && json.keys.contains($0.1) } } }
mit
177ebf68f56c65b8d2bb727258b8a6dc
21.075
79
0.582106
3.574899
false
false
false
false
omise/omise-ios
OmiseSDK/CreditCardFormViewController.swift
1
38684
// swiftlint:disable file_length import UIKit import os.log public protocol CreditCardFormViewControllerDelegate: AnyObject { /// Delegate method for receiving token data when card tokenization succeeds. /// - parameter token: `OmiseToken` instance created from supplied credit card data. /// - seealso: [Tokens API](https://www.omise.co/tokens-api) func creditCardFormViewController(_ controller: CreditCardFormViewController, didSucceedWithToken token: Token) /// Delegate method for receiving error information when card tokenization failed. /// This allows you to have fine-grained control over error handling when setting /// `handleErrors` to `false`. /// - parameter error: The error that occurred during tokenization. /// - note: This delegate method will *never* be called if `handleErrors` property is set to `true`. func creditCardFormViewController(_ controller: CreditCardFormViewController, didFailWithError error: Error) func creditCardFormViewControllerDidCancel(_ controller: CreditCardFormViewController) } /// Delegate to receive card tokenization events. @available(*, deprecated, renamed: "CreditCardFormViewControllerDelegate") public typealias CreditCardFormControllerDelegate = CreditCardFormViewControllerDelegate @available(*, unavailable, renamed: "CreditCardFormViewControllerDelegate") public protocol CreditCardFormDelegate: CreditCardFormViewControllerDelegate { @available(*, deprecated, renamed: "CreditCardFormViewControllerDelegate.creditCardFormViewController(_:didSucceedWithToken:)") func creditCardForm(_ controller: CreditCardFormController, didSucceedWithToken token: Token) @available(*, deprecated, renamed: "CreditCardFormViewControllerDelegate.creditCardFormViewController(_:didFailWithError:)") func creditCardForm(_ controller: CreditCardFormController, didFailWithError error: Error) } @available(*, deprecated, message: "This delegate name is deprecated. Please use the new name of `OMSCreditCardFormViewControllerDelegate`", renamed: "OMSCreditCardFormViewControllerDelegate") @objc public protocol OMSCreditCardFormDelegate: OMSCreditCardFormViewControllerDelegate {} @objc public protocol OMSCreditCardFormViewControllerDelegate: AnyObject { /// Delegate method for receiving token data when card tokenization succeeds. /// - parameter token: `OmiseToken` instance created from supplied credit card data. /// - seealso: [Tokens API](https://www.omise.co/tokens-api) @objc func creditCardFormViewController(_ controller: CreditCardFormViewController, didSucceedWithToken token: __OmiseToken) /// Delegate method for receiving error information when card tokenization failed. /// This allows you to have fine-grained control over error handling when setting /// `handleErrors` to `false`. /// - parameter error: The error that occurred during tokenization. /// - note: This delegate method will *never* be called if `handleErrors` property is set to `true`. @objc func creditCardFormViewController(_ controller: CreditCardFormViewController, didFailWithError error: NSError) @objc optional func creditCardFormViewControllerDidCancel(_ controller: CreditCardFormViewController) @available(*, unavailable, message: "Implement the new -[OMSCreditCardFormViewControllerDelegate creditCardFormViewController:didSucceedWithToken:] instead", renamed: "creditCardFormViewController(_:didSucceedWithToken:)") @objc func creditCardForm(_ controller: CreditCardFormViewController, didSucceedWithToken token: __OmiseToken) @available(*, unavailable, message: "Implement the new -[OMSCreditCardFormViewControllerDelegate creditCardFormViewController:didFailWithError:] instead", renamed: "creditCardFormViewController(_:didFailWithError:)") @objc func creditCardForm(_ controller: CreditCardFormViewController, didFailWithError error: NSError) } @available(*, deprecated, renamed: "CreditCardFormViewController") public typealias CreditCardFormController = CreditCardFormViewController // swiftlint:disable type_body_length /// Drop-in credit card input form view controller that automatically tokenizes credit /// card information. @objc(OMSCreditCardFormViewController) public class CreditCardFormViewController: UIViewController, PaymentChooserUI, PaymentFormUIController { /// Omise public key for calling tokenization API. @objc public var publicKey: String? /// Delegate to receive CreditCardFormController result. public weak var delegate: CreditCardFormViewControllerDelegate? /// Delegate to receive CreditCardFormController result. @objc(delegate) public weak var __delegate: OMSCreditCardFormViewControllerDelegate? // swiftlint:disable:this identifier_name /// A boolean flag to enables/disables automatic error handling. Defaults to `true`. @objc public var handleErrors = true @IBInspectable public var preferredPrimaryColor: UIColor? { didSet { applyPrimaryColor() } } @IBInspectable public var preferredSecondaryColor: UIColor? { didSet { applySecondaryColor() } } @IBInspectable public var errorMessageTextColor: UIColor! = CreditCardFormViewController.defaultErrorMessageTextColor { didSet { if errorMessageTextColor == nil { errorMessageTextColor = CreditCardFormViewController.defaultErrorMessageTextColor } if isViewLoaded { errorLabels.forEach { $0.textColor = errorMessageTextColor } } } } // swiftlint:disable:next weak_delegate private lazy var overlayTransitionDelegate = OverlayPanelTransitioningDelegate() var isInputDataValid: Bool { return formFields.reduce(into: true) { (valid, field) in valid = valid && field.isValid } } var currentEditingTextField: OmiseTextField? private var hasErrorMessage = false @IBOutlet var formFields: [OmiseTextField]! @IBOutlet var formLabels: [UILabel]! @IBOutlet var errorLabels: [UILabel]! @IBOutlet var contentView: UIScrollView! @IBOutlet private var cardNumberTextField: CardNumberTextField! @IBOutlet private var cardNameTextField: CardNameTextField! @IBOutlet private var expiryDateTextField: CardExpiryDateTextField! @IBOutlet private var secureCodeTextField: CardCVVTextField! @IBOutlet private var confirmButton: MainActionButton! @IBOutlet var formFieldsAccessoryView: UIToolbar! @IBOutlet var gotoPreviousFieldBarButtonItem: UIBarButtonItem! @IBOutlet var gotoNextFieldBarButtonItem: UIBarButtonItem! @IBOutlet var doneEditingBarButtonItem: UIBarButtonItem! @IBOutlet private var creditCardNumberErrorLabel: UILabel! @IBOutlet private var cardHolderNameErrorLabel: UILabel! @IBOutlet private var cardExpiryDateErrorLabel: UILabel! @IBOutlet private var cardSecurityCodeErrorLabel: UILabel! @IBOutlet private var errorBannerView: UIView! @IBOutlet private var errorTitleLabel: UILabel! @IBOutlet private var errorMessageLabel: UILabel! @IBOutlet private var hidingErrorBannerConstraint: NSLayoutConstraint! @IBOutlet private var emptyErrorMessageConstraint: NSLayoutConstraint! @IBOutlet private var cardBrandIconImageView: UIImageView! @IBOutlet private var cvvInfoButton: UIButton! @IBOutlet private var requestingIndicatorView: UIActivityIndicatorView! @objc public static let defaultErrorMessageTextColor = UIColor.error /// A boolean flag that enables/disables Card.IO integration. @available(*, unavailable, message: "Built in support for Card.ios was removed. You can implement it in your app and call the setCreditCardInformation(number:name:expiration:) method") // swiftlint:disable:this line_length @objc public var cardIOEnabled = true /// Factory method for creating CreditCardFormController with given public key. /// - parameter publicKey: Omise public key. @objc(creditCardFormViewControllerWithPublicKey:) public static func makeCreditCardFormViewController(withPublicKey publicKey: String) -> CreditCardFormViewController { let storyboard = UIStoryboard(name: "OmiseSDK", bundle: .module) // swiftlint:disable:next force_cast let creditCardForm = storyboard.instantiateInitialViewController() as! CreditCardFormViewController creditCardForm.publicKey = publicKey return creditCardForm } @available(*, deprecated, message: "Please use the new method that confrom to Objective-C convention +[OMSCreditCardFormViewController creditCardFormViewControllerWithPublicKey:] as of this method will be removed in the future release.", // swiftlint:disable:this line_length renamed: "makeCreditCardFormViewController(withPublicKey:)") @objc(makeCreditCardFormWithPublicKey:) public static func __makeCreditCardForm(withPublicKey publicKey: String) -> CreditCardFormViewController { // swiftlint:disable:this identifier_name return CreditCardFormViewController.makeCreditCardFormViewController(withPublicKey: publicKey) } public func setCreditCardInformationWith(number: String?, name: String?, expiration: (month: Int, year: Int)?) { cardNumberTextField.text = number cardNameTextField.text = name if let expiration = expiration, 1...12 ~= expiration.month, expiration.year > 0 { expiryDateTextField.text = String(format: "%02d/%d", expiration.month, expiration.year % 100) } updateSupplementaryUI() os_log("The custom credit card information was set - %{private}@", log: uiLogObject, type: .debug, String((number ?? "").suffix(4))) } @objc(setCreditCardInformationWithNumber:name:expirationMonth:expirationYear:) public func __setCreditCardInformation(number: String, name: String, expirationMonth: Int, expirationYear: Int) { // swiftlint:disable:this identifier_name let month: Int? let year: Int? if Calendar.validExpirationMonthRange ~= expirationMonth { month = expirationMonth } else { month = nil } if expirationYear > 0 && expirationYear != NSNotFound { year = expirationYear } else { year = nil } let expiration: (month: Int, year: Int)? if let month = month, let year = year { expiration = (month: month, year: year) } else { expiration = nil } self.setCreditCardInformationWith(number: number, name: name, expiration: expiration) } // need to refactor loadView, removing super results in crash // swiftlint:disable prohibited_super_call public override func loadView() { super.loadView() view.backgroundColor = UIColor.background confirmButton.defaultBackgroundColor = view.tintColor confirmButton.disabledBackgroundColor = .line cvvInfoButton.tintColor = .badgeBackground formFieldsAccessoryView.barTintColor = .formAccessoryBarTintColor #if compiler(>=5.1) if #available(iOS 13, *) { let appearance = navigationItem.standardAppearance ?? UINavigationBarAppearance(idiom: .phone) appearance.configureWithOpaqueBackground() appearance.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.headings ] appearance.largeTitleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.headings ] let renderer = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)) let image = renderer.image { (context) in context.cgContext.setFillColor(UIColor.line.cgColor) context.fill(CGRect(origin: .zero, size: CGSize(width: 1, height: 1))) } appearance.shadowImage = image.resizableImage(withCapInsets: UIEdgeInsets.zero) .withRenderingMode(.alwaysTemplate) appearance.shadowColor = preferredSecondaryColor ?? defaultPaymentChooserUISecondaryColor navigationItem.standardAppearance = appearance let scrollEdgeAppearance = appearance.copy() appearance.shadowColor = preferredSecondaryColor ?? defaultPaymentChooserUISecondaryColor navigationItem.scrollEdgeAppearance = scrollEdgeAppearance } #endif } public override func viewDidLoad() { super.viewDidLoad() applyPrimaryColor() applySecondaryColor() formFields.forEach { $0.inputAccessoryView = formFieldsAccessoryView } errorLabels.forEach { $0.textColor = errorMessageTextColor } formFields.forEach(self.updateAccessibilityValue) updateSupplementaryUI() configureAccessibility() formFields.forEach { $0.adjustsFontForContentSizeCategory = true } formLabels.forEach { $0.adjustsFontForContentSizeCategory = true } confirmButton.titleLabel?.adjustsFontForContentSizeCategory = true if #available(iOS 11, *) { // We'll leave the adjusting scroll view insets job for iOS 11 and later to the layoutMargins + safeAreaInsets here } else { automaticallyAdjustsScrollViewInsets = true } cardNumberTextField.rightView = cardBrandIconImageView secureCodeTextField.rightView = cvvInfoButton secureCodeTextField.rightViewMode = .always NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillChangeFrame(_:)), name: NotificationKeyboardWillChangeFrameNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: NotificationKeyboardWillHideFrameNotification, object: nil ) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if #available(iOS 11, *) { // There's a bug in iOS 10 and earlier which the text field's intrinsicContentSize is returned the value // that doesn't take the result of textRect(forBounds:) method into an account for the initial value // So we need to invalidate the intrinsic content size here to ask those text fields to calculate their // intrinsic content size again } else { formFields.forEach { $0.invalidateIntrinsicContentSize() } } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillAppear(_:)), name: NotificationKeyboardWillShowFrameNotification, object: nil ) } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter().removeObserver(self, name: NotificationKeyboardWillShowFrameNotification, object: nil) } public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { view.setNeedsUpdateConstraints() } } @IBAction private func displayMoreCVVInfo(_ sender: UIButton) { guard let viewController = storyboard?.instantiateViewController(withIdentifier: "MoreInformationOnCVVViewController"), let moreInformationOnCVVViewController = viewController as? MoreInformationOnCVVViewController else { return } moreInformationOnCVVViewController.preferredCardBrand = cardNumberTextField.cardBrand moreInformationOnCVVViewController.delegate = self moreInformationOnCVVViewController.modalPresentationStyle = .custom moreInformationOnCVVViewController.transitioningDelegate = overlayTransitionDelegate moreInformationOnCVVViewController.view.tintColor = view.tintColor present(moreInformationOnCVVViewController, animated: true, completion: nil) } @IBAction private func cancelForm() { performCancelingForm() } @discardableResult private func performCancelingForm() -> Bool { os_log("Credit Card Form dismissing requested, Asking the delegate what should the form controler do", log: uiLogObject, type: .default) if let delegate = self.delegate { delegate.creditCardFormViewControllerDidCancel(self) os_log("Canceling form delegate notified", log: uiLogObject, type: .default) return true } else if let delegateMethod = __delegate?.creditCardFormViewControllerDidCancel { delegateMethod(self) os_log("Canceling form delegate notified", log: uiLogObject, type: .default) return true } else { os_log("Credit Card Form dismissing requested but there is not delegate to ask. Ignore the request", log: uiLogObject, type: .default) return false } } @IBAction private func requestToken() { doneEditing(nil) UIAccessibility.post(notification: AccessibilityNotificationAnnouncement, argument: "Submitting payment, please wait") guard let publicKey = publicKey else { os_log("Missing or invalid public key information - %{private}@", log: uiLogObject, type: .error, self.publicKey ?? "") assertionFailure("Missing public key information. Please set the public key before request token.") return } os_log("Requesting to create token", log: uiLogObject, type: .info) startActivityIndicator() let request = Request<Token>( name: cardNameTextField.text ?? "", pan: cardNumberTextField.pan, expirationMonth: expiryDateTextField.selectedMonth ?? 0, expirationYear: expiryDateTextField.selectedYear ?? 0, securityCode: secureCodeTextField.text ?? "" ) let client = Client(publicKey: publicKey) client.send(request) { [weak self] (result) in guard let strongSelf = self else { return } strongSelf.stopActivityIndicator() switch result { case let .success(token): os_log("Credit Card Form's Request succeed %{private}@, trying to notify the delegate", log: uiLogObject, type: .default, token.id) if let delegate = strongSelf.delegate { delegate.creditCardFormViewController(strongSelf, didSucceedWithToken: token) os_log("Credit Card Form Create Token succeed delegate notified", log: uiLogObject, type: .default) } else if let delegate = strongSelf.__delegate { delegate.creditCardFormViewController(strongSelf, didSucceedWithToken: __OmiseToken(token: token)) os_log("Credit Card Form Create Token succeed delegate notified", log: uiLogObject, type: .default) } else { os_log("There is no Credit Card Form's delegate to notify about the created token", log: uiLogObject, type: .default) } case let .failure(err): strongSelf.handleError(err) } } } @objc private func keyboardWillAppear(_ notification: Notification) { if hasErrorMessage { hasErrorMessage = false dismissErrorMessage(animated: true, sender: self) } } @objc func keyboardWillChangeFrame(_ notification: NSNotification) { guard let frameEnd = notification.userInfo?[NotificationKeyboardFrameEndUserInfoKey] as? CGRect, let frameStart = notification.userInfo?[NotificationKeyboardFrameBeginUserInfoKey] as? CGRect, frameEnd != frameStart else { return } let intersectedFrame = contentView.convert(frameEnd, from: nil) contentView.contentInset.bottom = intersectedFrame.height let bottomScrollIndicatorInset: CGFloat if #available(iOS 11.0, *) { bottomScrollIndicatorInset = intersectedFrame.height - contentView.safeAreaInsets.bottom } else { bottomScrollIndicatorInset = intersectedFrame.height } contentView.scrollIndicatorInsets.bottom = bottomScrollIndicatorInset } @objc func keyboardWillHide(_ notification: NSNotification) { contentView.contentInset.bottom = 0.0 contentView.scrollIndicatorInsets.bottom = 0.0 } private func handleError(_ error: Error) { guard handleErrors else { os_log("Credit Card Form's Request failed %{private}@, automatically error handling turned off. Trying to notify the delegate", log: uiLogObject, type: .info, error.localizedDescription) if let delegate = self.delegate { delegate.creditCardFormViewController(self, didFailWithError: error) os_log("Error handling delegate notified", log: uiLogObject, type: .default) } else if let delegate = self.__delegate { delegate.creditCardFormViewController(self, didFailWithError: error as NSError) os_log("Error handling delegate notified", log: uiLogObject, type: .default) } else { os_log("There is no Credit Card Form's delegate to notify about the error", log: uiLogObject, type: .default) } return } os_log("Credit Card Form's Request failed %{private}@, automatically error handling turned on.", log: uiLogObject, type: .default, error.localizedDescription) displayError(error) hasErrorMessage = true } private func displayError(_ error: Error) { let targetController = targetViewController(forAction: #selector(UIViewController.displayErrorWith(title:message:animated:sender:)), sender: self) if let targetController = targetController, targetController !== self { if let error = error as? OmiseError { targetController.displayErrorWith(title: error.bannerErrorDescription, message: error.bannerErrorRecoverySuggestion, animated: true, sender: self) } else if let error = error as? LocalizedError { targetController.displayErrorWith(title: error.localizedDescription, message: error.recoverySuggestion, animated: true, sender: self) } else { targetController.displayErrorWith(title: error.localizedDescription, message: nil, animated: true, sender: self) } } else { let errorTitle: String let errorMessage: String? if let error = error as? OmiseError { errorTitle = error.bannerErrorDescription errorMessage = error.bannerErrorRecoverySuggestion } else if let error = error as? LocalizedError { errorTitle = error.localizedDescription errorMessage = error.recoverySuggestion } else { errorTitle = error.localizedDescription errorMessage = nil } errorTitleLabel.text = errorTitle errorMessageLabel.text = errorMessage errorMessageLabel.isHidden = errorMessage == nil emptyErrorMessageConstraint.priority = errorMessage == nil ? UILayoutPriority(999) : UILayoutPriority(1) errorBannerView.layoutIfNeeded() setShowsErrorBanner(true) } } private func setShowsErrorBanner(_ showsErrorBanner: Bool, animated: Bool = true) { hidingErrorBannerConstraint.isActive = !showsErrorBanner let animationBlock = { self.errorBannerView.alpha = showsErrorBanner ? 1.0 : 0.0 self.contentView.layoutIfNeeded() } if animated { UIView.animate(withDuration: TimeInterval(NavigationControllerHideShowBarDuration), delay: 0.0, options: [.layoutSubviews], animations: animationBlock) } else { animationBlock() } } @IBAction private func dismissErrorBanner(_ sender: Any) { setShowsErrorBanner(false) } private func updateSupplementaryUI() { let valid = isInputDataValid confirmButton?.isEnabled = valid if valid { confirmButton.accessibilityTraits.remove(UIAccessibilityTraits.notEnabled) } else { confirmButton.accessibilityTraits.insert(UIAccessibilityTraits.notEnabled) } let cardBrandIconName: String? switch cardNumberTextField.cardBrand { case .visa?: cardBrandIconName = "Visa" case .masterCard?: cardBrandIconName = "Mastercard" case .jcb?: cardBrandIconName = "JCB" case .amex?: cardBrandIconName = "AMEX" case .diners?: cardBrandIconName = "Diners" default: cardBrandIconName = nil } cardBrandIconImageView.image = cardBrandIconName.flatMap { UIImage(named: $0, in: .module, compatibleWith: nil) } cardNumberTextField.rightViewMode = cardBrandIconImageView.image != nil ? .always : .never } private func startActivityIndicator() { requestingIndicatorView.startAnimating() confirmButton.isEnabled = false view.isUserInteractionEnabled = false } private func stopActivityIndicator() { requestingIndicatorView.stopAnimating() confirmButton.isEnabled = true view.isUserInteractionEnabled = true } private func applyPrimaryColor() { guard isViewLoaded else { return } formFields.forEach { $0.textColor = currentPrimaryColor } formLabels.forEach { $0.textColor = currentPrimaryColor } } private func applySecondaryColor() { guard isViewLoaded else { return } formFields.forEach { $0.borderColor = currentSecondaryColor $0.placeholderTextColor = currentSecondaryColor } } fileprivate func associatedErrorLabelOf(_ textField: OmiseTextField) -> UILabel? { switch textField { case cardNumberTextField: return creditCardNumberErrorLabel case cardNameTextField: return cardHolderNameErrorLabel case expiryDateTextField: return cardExpiryDateErrorLabel case secureCodeTextField: return cardSecurityCodeErrorLabel default: return nil } } private func validateField(_ textField: OmiseTextField) { guard let errorLabel = associatedErrorLabelOf(textField) else { return } do { try textField.validate() errorLabel.alpha = 0.0 } catch { errorLabel.text = validationErrorText(for: textField, error: error) errorLabel.alpha = errorLabel.text != "-" ? 1.0 : 0.0 } } private func validationErrorText(for textField: UITextField, error: Error) -> String { switch (error, textField) { case (OmiseTextFieldValidationError.emptyText, _): return "-" // We need to set the error label some string in order to have it retains its height case (OmiseTextFieldValidationError.invalidData, cardNumberTextField): return NSLocalizedString( "credit-card-form.card-number-field.invalid-data.error.text", tableName: "Error", bundle: .module, value: "Credit card number is invalid", comment: "An error text displayed when the credit card number is invalid" ) case (OmiseTextFieldValidationError.invalidData, cardNameTextField): return NSLocalizedString( "credit-card-form.card-holder-name-field.invalid-data.error.text", tableName: "Error", bundle: .module, value: "Card holder name is invalid", comment: "An error text displayed when the card holder name is invalid" ) case (OmiseTextFieldValidationError.invalidData, expiryDateTextField): return NSLocalizedString( "credit-card-form.expiry-date-field.invalid-data.error.text", tableName: "Error", bundle: .module, value: "Card expiry date is invalid", comment: "An error text displayed when the expiry date is invalid" ) case (OmiseTextFieldValidationError.invalidData, secureCodeTextField): return NSLocalizedString( "credit-card-form.security-code-field.invalid-data.error.text", tableName: "Error", bundle: .module, value: "CVV code is invalid", comment: "An error text displayed when the security code is invalid" ) case (_, cardNumberTextField), (_, cardNameTextField), (_, expiryDateTextField), (_, secureCodeTextField): return error.localizedDescription default: return "-" } } } // MARK: - Fields Accessory methods extension CreditCardFormViewController { @IBAction private func validateTextFieldDataOf(_ sender: OmiseTextField) { let duration = TimeInterval(NavigationControllerHideShowBarDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) { self.validateField(sender) } sender.borderColor = currentSecondaryColor } @IBAction private func updateInputAccessoryViewFor(_ sender: OmiseTextField) { if let errorLabel = associatedErrorLabelOf(sender) { let duration = TimeInterval(NavigationControllerHideShowBarDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) { errorLabel.alpha = 0.0 } } sender.borderColor = view.tintColor updateInputAccessoryViewWithFirstResponder(sender) } @IBAction private func gotoPreviousField(_ button: UIBarButtonItem) { gotoPreviousField() } @IBAction private func gotoNextField(_ button: UIBarButtonItem) { gotoNextField() } @IBAction private func doneEditing(_ button: UIBarButtonItem?) { doneEditing() } } // MARK: - Accessibility extension CreditCardFormViewController { @IBAction private func updateAccessibilityValue(_ sender: OmiseTextField) { updateSupplementaryUI() } // swiftlint:disable function_body_length private func configureAccessibility() { formLabels.forEach { $0.adjustsFontForContentSizeCategory = true } formFields.forEach { $0.adjustsFontForContentSizeCategory = true } confirmButton.titleLabel?.adjustsFontForContentSizeCategory = true let fields = [ cardNumberTextField, cardNameTextField, expiryDateTextField, secureCodeTextField ] as [OmiseTextField] func accessiblityElementAfter( _ element: NSObjectProtocol?, matchingPredicate predicate: (OmiseTextField) -> Bool, direction: AccessibilityCustomRotorDirection ) -> NSObjectProtocol? { guard let element = element else { switch direction { case .previous: return fields.reversed().first(where: predicate)?.accessibilityElements?.last as? NSObjectProtocol ?? fields.reversed().first(where: predicate) case .next: fallthrough @unknown default: return fields.first(where: predicate)?.accessibilityElements?.first as? NSObjectProtocol ?? fields.first(where: predicate) } } let fieldOfElement = fields.first { field in guard let accessibilityElements = field.accessibilityElements as? [NSObjectProtocol] else { return element === field } return accessibilityElements.contains { $0 === element } } ?? cardNumberTextField! // swiftlint:disable:this force_unwrapping func filedAfter( _ field: OmiseTextField, matchingPredicate predicate: (OmiseTextField) -> Bool, direction: AccessibilityCustomRotorDirection ) -> OmiseTextField? { guard let indexOfField = fields.firstIndex(of: field) else { return nil } switch direction { case .previous: return fields[fields.startIndex..<indexOfField].reversed().first(where: predicate) case .next: fallthrough @unknown default: return fields[fields.index(after: indexOfField)...].first(where: predicate) } } let nextField = filedAfter(fieldOfElement, matchingPredicate: predicate, direction: direction) guard let currentAccessibilityElements = (fieldOfElement.accessibilityElements as? [NSObjectProtocol]), let indexOfAccessibilityElement = currentAccessibilityElements.firstIndex(where: { $0 === element }) else { switch direction { case .previous: return nextField?.accessibilityElements?.last as? NSObjectProtocol ?? nextField case .next: fallthrough @unknown default: return nextField?.accessibilityElements?.first as? NSObjectProtocol ?? nextField } } switch direction { case .previous: if predicate(fieldOfElement) && indexOfAccessibilityElement > currentAccessibilityElements.startIndex { return currentAccessibilityElements[currentAccessibilityElements.index(before: indexOfAccessibilityElement)] } else { return nextField?.accessibilityElements?.last as? NSObjectProtocol ?? nextField } case .next: fallthrough @unknown default: if predicate(fieldOfElement) && indexOfAccessibilityElement < currentAccessibilityElements.endIndex - 1 { return currentAccessibilityElements[currentAccessibilityElements.index(after: indexOfAccessibilityElement)] } else { return nextField?.accessibilityElements?.first as? NSObjectProtocol ?? nextField } } } accessibilityCustomRotors = [ UIAccessibilityCustomRotor(name: "Fields") { (predicate) -> UIAccessibilityCustomRotorItemResult? in return accessiblityElementAfter(predicate.currentItem.targetElement, matchingPredicate: { _ in true }, direction: predicate.searchDirection) .map { UIAccessibilityCustomRotorItemResult(targetElement: $0, targetRange: nil) } }, UIAccessibilityCustomRotor(name: "Invalid Data Fields") { (predicate) -> UIAccessibilityCustomRotorItemResult? in return accessiblityElementAfter(predicate.currentItem.targetElement, matchingPredicate: { !$0.isValid }, direction: predicate.searchDirection) .map { UIAccessibilityCustomRotorItemResult(targetElement: $0, targetRange: nil) } } ] } public override func accessibilityPerformMagicTap() -> Bool { guard isInputDataValid else { return false } requestToken() return true } public override func accessibilityPerformEscape() -> Bool { return performCancelingForm() } } extension CreditCardFormViewController: MoreInformationOnCVVViewControllerDelegate { func moreInformationOnCVVViewControllerDidAskToClose(_ controller: MoreInformationOnCVVViewController) { dismiss(animated: true, completion: nil) } }
mit
d5ffcdcc89bc52b700a4d9e862c0d771
43.009101
253
0.636827
5.958718
false
false
false
false
AlexLombry/SwiftMastery-iOS10
PlayGround/Collections-Array-Dictionary.playground/Contents.swift
1
3198
//: Playground - noun: a place where people can play import UIKit var arrayOfInts = [Int]() // Declared with type inference let arrayOfNames = ["Bob", "Jim", "John"] print("Names array contains \(arrayOfNames.count) elements") // Declared with type annotation let arrayOfMoreNames: Array<String> = ["Frank", "Tom", "Joe"] print("More names array contains \(arrayOfMoreNames.count) elements") arrayOfInts.append(7) // empty the array (still array of Int) arrayOfInts = [] var fourDoublesArray = Array(repeating: 3.14, count: 4) // Adding 2 arrays together var fiveDoubles = Array(repeating: 2.1, count: 5) var nineDoubles = fourDoublesArray + fiveDoubles // Declared type var cars: [String] = ["Ford", "Peugeot", "Honda"] // Inferred type var moreCars = ["Fiat", "Mazda"] var allCars = cars + moreCars if moreCars.isEmpty { print("No elements") } else { print("There's elements") } moreCars.append("Volkswagen") moreCars += ["Renault"] // Subscript syntax var secondItem = moreCars[1] moreCars [0...2] = ["GTO", "Charger", "Jeep"] print(moreCars) moreCars.insert("Yello VM Bug", at: 2) let muscleCars = moreCars.remove(at: 0) // runtime error if your try to remove undefined index let familyCar = moreCars.removeLast() print(moreCars) for item in moreCars { print(item) } // Enumerated returns the value and index from an array for (index, value) in moreCars.enumerated() { print("Item \(index + 1): \(value)") } if let match = moreCars.index(of: "Jeep") { moreCars.remove(at: match) } print(moreCars) // Multi Dimensional Array var multiArray: [[String]] = [ ["10", "20", "30"], ["1", "2", "3"] ] for column in multiArray { for row in column { print("\(row) : (column)") } } // Dictionary in swift it's like array key value in php var dictionary: [Int : String] var dictionary2: [Int : String] = [1 : "value 1", 2: "value 2"] var dictionary3 = [1 : "value 1", 2: "value 2"] var frenchNumbers = [Int: String]() frenchNumbers = [:] frenchNumbers = [1: "Un", 2: "Deux", 3: "Trois", 4: "Quatre", 5: "Cinq"] var mutable = ["someKey" : "someValue"] let immutable = ["someKey" : "somevalue"] if let oldValue = frenchNumbers.updateValue("Deux - is two", forKey: 2) { print("\(oldValue) \(frenchNumbers[2]!)") } print(frenchNumbers) // Dictionary is array with key value // To remove a key pair is to set key to nul frenchNumbers[1] = nil print(frenchNumbers) if let removedValue = frenchNumbers.removeValue(forKey: 2) { print("The removed numbers name is \(removedValue)") } else { print("Nothing to remove") } for (k, v) in frenchNumbers { print("\(k) : \(v)") } // Get only keys for numberKey in frenchNumbers.keys { print("French number key: \(numberKey)") } // Get only values for numberValue in frenchNumbers.values { print("French number key: \(numberValue)") } // Create array with dictionary key value let numberKeyArray = [Int](frenchNumbers.keys) let numberValueArray = [String](frenchNumbers.values) for key in frenchNumbers.keys.sorted(by: <) { print("French number key: \(key)") } for value in frenchNumbers.values.sorted(by: >) { print("French number key: \(value)") }
apache-2.0
852f11849952d0eb12843a2b54920703
20.755102
73
0.67167
3.283368
false
false
false
false
ozgur/TestApp
TestApp/Common/Helpers.swift
1
1221
// // Helpers.swift // TestApp // // Created by Ozgur on 19/01/2017. // Copyright © 2017 Ozgur. All rights reserved. // import Foundation import MapKit import SwiftMessages let kCLLocation2DInvalid = CLLocation( coordinate: kCLLocationCoordinate2DInvalid, altitude: -1.0, horizontalAccuracy: -1.0, verticalAccuracy: -1.0, course: -1.0, speed: -1.0, timestamp: Date() // Don't worry, we won't check this unless coordinate is valid. ) let kCLLocationCoordinate2DZero = CLLocationCoordinate2DMake(0, 0) // https://en.wikipedia.org/wiki/Geographical_centre_of_Earth let kCLLocationCoordinate2DCenter = CLLocationCoordinate2DMake(39.0, 34.0) extension CLLocationCoordinate2D { static let center = kCLLocationCoordinate2DCenter static let invalid = kCLLocationCoordinate2DInvalid static let zero = kCLLocationCoordinate2DZero } func CLLocation2DIsValid(_ loc: CLLocation) -> Bool { return CLLocationCoordinate2DIsValid(loc.coordinate) } func MKCoordinateRegionMakeWithDistance(_ coordinate: CLLocationCoordinate2D, _ distance: CLLocationDistance) -> MKCoordinateRegion { return MKCoordinateRegionMakeWithDistance(coordinate, distance, distance) }
gpl-3.0
8654c4bc93c736b8c4e9d59da8c9d57a
28.047619
83
0.754098
4.250871
false
false
false
false
svlaev/SVAlert
SVAlert/Classes/SVAlertView.swift
1
5784
// // ViewController.swift // SVAlertView // // Created by Stanislav Vlaev on 08/18/2016. // Copyright (c) 2016 Stanislav Vlaev. All rights reserved. // extension SVAlertView { // MARK: - Static methods class func defaultAlertView() -> SVAlertView { return Bundle(for: self.classForCoder()).loadNibNamed("SVAlertView", owner: nil, options: nil)!.first as! SVAlertView } // MARK: - Public methods func showButtons(_ btns: [(title: String, callback: () -> Void)]) { populateButtons(btns) } @objc func buttonTapped(_ btn: UIButton) { var tap: (()->Void)! = nil for b in buttonsArr { if b.btn.tag == btn.tag { tap = b.tapCallback break } } tap?() buttonTapCallback?() } func desiredHeight() -> CGFloat { return viewBtnsHolder.frame.maxY } } class SVAlertView: UIView { // MARK: - Public properties var title: String! = nil { didSet { lblTitle?.text = title } } var subtitle: String! = nil { didSet { lblSubtitle?.text = subtitle constrSubtitleTopMargin.constant = lblSubtitle?.text != nil ? constrTitleTopMargin.constant : 0.0 } } var buttonTapCallback: (() -> Void)! = nil // MARK: - Private static properties static let ButtonHeight: CGFloat = 50.0 // MARK: - Private properties fileprivate var buttonsArr: [(btn: UIButton, tapCallback: () -> Void)]! = [] // MARK: - Outlets @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblSubtitle: UILabel! @IBOutlet weak var viewBtnsHolder: UIView! @IBOutlet weak var constrTitleTopMargin: NSLayoutConstraint! @IBOutlet weak var constrSubtitleTopMargin: NSLayoutConstraint! @IBOutlet weak var constrButtonsHolderHeight: NSLayoutConstraint! } extension SVAlertView { // MARK: - Private methods fileprivate func populateButtons(_ btns: [(title: String, callback: () -> Void)]) { viewBtnsHolder.subviews.forEach { $0.removeFromSuperview() } buttonsArr.removeAll() var index = 0 for btnToBeAdded in btns { let btn = UIButton(type: .custom) btn.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0) btn.setTitle(btnToBeAdded.title, for: UIControlState()) btn.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) btn.tag = index btn.setTitleColor(UIColor(red: CGFloat(5.0/255.0), green: CGFloat(133.0/255.0), blue: 1.0, alpha: 1.0), for: UIControlState()) index += 1 btn.translatesAutoresizingMaskIntoConstraints = false buttonsArr.append((btn: btn, tapCallback: btnToBeAdded.callback)) viewBtnsHolder.addSubview(btn) } guard buttonsArr.count > 0 else { constrButtonsHolderHeight.constant = 0.0 return } constrButtonsHolderHeight.constant = buttonsArr.count > 2 ? CGFloat(buttonsArr.count) * SVAlertView.ButtonHeight : SVAlertView.ButtonHeight viewBtnsHolder.addConstraints(constraintsForButtons()) } fileprivate func constraintsForButtons() -> [NSLayoutConstraint] { switch buttonsArr.count { case 1: return constraintsForOnlyOneButton(buttonsArr.first!.btn) case 2: return constraintsForTwoButtons(button1: buttonsArr.first!.btn, button2: buttonsArr.last!.btn) case 3..<Int.max: return constraintsForThreeOrMoreButtons(buttonsArr.map { $0.btn }) default: return [] } } fileprivate func constraintsForOnlyOneButton(_ btn: UIButton) -> [NSLayoutConstraint] { let dict = ["btn" : btn] var arr = NSLayoutConstraint.visual("V:|-0-[btn]-0-|", views: dict) arr.append(contentsOf: NSLayoutConstraint.visual("H:|-0-[btn]-0-|", views: dict)) return arr } fileprivate func constraintsForTwoButtons(button1 b1: UIButton, button2 b2: UIButton) -> [NSLayoutConstraint] { let dict = ["b1" : b1, "b2" : b2] var arr = NSLayoutConstraint.visual("V:|-0-[b1]-0-|", views: dict) arr.append(contentsOf: NSLayoutConstraint.visual("V:|-0-[b2]-0-|", views: dict)) arr.append(contentsOf: NSLayoutConstraint.visual("H:|-0-[b1]", views: dict)) arr.append(contentsOf: NSLayoutConstraint.visual("H:[b2]-0-|", views: dict)) arr.append(contentsOf: NSLayoutConstraint.visual("H:[b1]-0-[b2]", views: dict)) arr.append(NSLayoutConstraint(item: b1, attribute: .width, relatedBy: .equal, toItem: b2, attribute: .width, multiplier: 1.0, constant: b1.frame.size.width)) return arr } fileprivate func constraintsForThreeOrMoreButtons(_ buttons: [UIButton]) -> [NSLayoutConstraint] { var arr: [NSLayoutConstraint] = [] var index = 0 let height = SVAlertView.ButtonHeight for b in buttons { arr.append(contentsOf: NSLayoutConstraint.visual("H:|-0-[btn]-0-|", views: ["btn" : b])) if index == 0 { arr.append(contentsOf: NSLayoutConstraint.visual("V:|-0-[btn(\(height))]", views: ["btn" : b])) } else { arr.append(contentsOf: NSLayoutConstraint.visual("V:[prevBtn]-0-[btn(\(height))]", views: ["prevBtn" : buttons[index-1], "btn" : b])) } index += 1 } return arr } } extension NSLayoutConstraint { class func visual(_ format: String, views: [String : Any]) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: views) } }
mit
94a167b51a736a38d940e5b748967e1c
38.081081
165
0.618084
4.329341
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/SearchBarController.swift
1
3879
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * 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 CosmicMind 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 @objc(SearchBarAlignment) public enum SearchBarAlignment: Int { case top case bottom } extension UIViewController { /** A convenience property that provides access to the SearchBarController. This is the recommended method of accessing the SearchBarController through child UIViewControllers. */ public var searchBarController: SearchBarController? { return traverseViewControllerHierarchyForClassType() } } open class SearchBarController: StatusBarController { /// Reference to the SearchBar. @IBInspectable open let searchBar = SearchBar() /// The searchBar alignment. open var searchBarAlignment = SearchBarAlignment.top { didSet { layoutSubviews() } } open override func layoutSubviews() { super.layoutSubviews() layoutSearchBar() layoutContainer() layoutRootViewController() } open override func prepare() { super.prepare() displayStyle = .partial prepareSearchBar() } } fileprivate extension SearchBarController { /// Prepares the searchBar. func prepareSearchBar() { searchBar.layer.zPosition = 1000 searchBar.depthPreset = .depth1 view.addSubview(searchBar) } } fileprivate extension SearchBarController { /// Layout the container. func layoutContainer() { switch displayStyle { case .partial: let p = searchBar.bounds.height let q = statusBarOffsetAdjustment let h = view.bounds.height - p - q switch searchBarAlignment { case .top: container.frame.origin.y = q + p container.frame.size.height = h case .bottom: container.frame.origin.y = q container.frame.size.height = h } container.frame.size.width = view.bounds.width case .full: container.frame = view.bounds } } /// Layout the searchBar. func layoutSearchBar() { searchBar.frame.origin.x = 0 searchBar.frame.origin.y = .top == searchBarAlignment ? statusBarOffsetAdjustment : view.bounds.height - searchBar.bounds.height searchBar.frame.size.width = view.bounds.width } /// Layout the rootViewController. func layoutRootViewController() { rootViewController.view.frame = container.bounds } }
bsd-3-clause
da58bc171273791e3b2ce0c9f8f3df59
30.536585
132
0.72132
4.66787
false
false
false
false
bravelocation/yeltzland-ios
yeltzland/ViewModels/YouTubeData.swift
1
2527
// // YeltzTVData.swift // Yeltzland // // Created by John Pollard on 17/10/2021. // Copyright © 2021 John Pollard. All rights reserved. // import Foundation #if canImport(SwiftUI) import SwiftUI import Combine #endif @available(iOS 13.0, tvOS 15.0, *) class YouTubeData: ObservableObject { let dataProvider: YouTubeDataProvider @Published private(set) var videos: [YouTubeVideo] = [] @Published private(set) var state: ViewLoadingState = ViewLoadingState.idle @Published private(set) var images: [String: UIImage] = [:] let imageCache: ExternalImageCache = ExternalImageCache() var imageSink: AnyCancellable? init(channelId: String) { self.dataProvider = YouTubeDataProvider(channelId: channelId) self.setupImageSink() self.refreshData() } public func refreshData() { print("Refreshing YouTube data ...") self.setState(.isLoading) // Fetch the data from the server self.dataProvider.refreshData() { [weak self] result in switch result { case .success(let videos): DispatchQueue.main.async { [self] in self?.videos = videos } self?.fetchVideoImages(videos) case .failure: print("Failed to fetch YouTube videos") } self?.setState(.loaded) } } func videoImage(_ video: YouTubeVideo) -> Image { let placeholder = self.imageCache.imageWithColor(color: .systemGray) return self.imageCache.currentImage(imageUrl: video.thumbnail, placeholderImage: placeholder) } private func setupImageSink() { // Setup subscriber for image updates self.imageSink = self.imageCache.$images.sink( receiveValue: { [self] updatedImages in self.updateImages(updatedImages) } ) } private func updateImages(_ updatedImages: [String: UIImage]) { DispatchQueue.main.async { self.images = updatedImages } } private func setState(_ state: ViewLoadingState) { DispatchQueue.main.async { self.state = state } } private func fetchVideoImages(_ videos: [YouTubeVideo]) { for video in videos { self.imageCache.fetchImage(imageUrl: video.thumbnail) } } }
mit
1d915ddf0256d563fee68262f71e4ac1
27.704545
79
0.583531
4.952941
false
false
false
false
crewupinc/vapor-postgresql
Sources/VaporPostgreSQL/Model.swift
1
7176
// The MIT License (MIT) // // Copyright (c) 2015 Formbound // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public struct ModelError: Error { public let description: String public init(description: String) { self.description = description } } public enum ModelChangeStatus { case unknown case changed case unchanged } public protocol Model { associatedtype Field: FieldProtocol associatedtype PrimaryKey: SQLDataConvertible static var fieldForPrimaryKey: Field { get } static var tableName: String { get } static var selectFields: [Field] { get } var primaryKey: PrimaryKey? { get } var changedFields: [Field]? { get set } var persistedValuesByField: [Field: SQLDataConvertible?] { get } func willSave() func didSave() func willUpdate() func didUpdate() func willInsert() func didInsert() func willDelete() func didDelete() func willRefresh() func didRefresh() func validate() throws init(row: Row) throws } extension Model { public static var declaredPrimaryKeyField: DeclaredField { return field(fieldForPrimaryKey) } public static var declaredSelectFields: [DeclaredField] { return selectFields.map { Self.field($0) } } public static var selectFields: [Field] { return [] } public static func field(_ field: Field) -> DeclaredField { return DeclaredField(name: field.rawValue, tableName: Self.tableName) } public static func field(_ field: String) -> DeclaredField { return DeclaredField(name: field, tableName: Self.tableName) } public static func columnName(_ field: Field) -> String { return field.rawValue } public static var selectQuery: ModelSelect<Self> { return ModelSelect() } public static var deleteQuery: ModelDelete<Self> { return ModelDelete() } public static func updateQuery(_ values: [Field: SQLDataConvertible?] = [:]) -> ModelUpdate<Self> { return ModelUpdate(values) } public static func insertQuery(values: [Field: SQLDataConvertible?]) -> ModelInsert<Self> { return ModelInsert(values) } public var changedFields: [Self.Field]? { get { return nil } set { return } } public var hasChanged: ModelChangeStatus { guard let changedFields = changedFields else { return .unknown } return changedFields.isEmpty ? .unchanged : .changed } public var changedValuesByField: [Field: SQLDataConvertible?]? { guard let changedFields = changedFields else { return nil } var dict = [Field: SQLDataConvertible?]() var values = persistedValuesByField for field in changedFields { dict[field] = values[field] } return dict } public var persistedFields: [Field] { return Array(persistedValuesByField.keys) } public var isPersisted: Bool { return primaryKey != nil } public mutating func setNeedsSave(field: Field) throws { guard var changedFields = changedFields else { throw ModelError(description: "Cannot set changed value, as property `changedFields` is nil") } guard !changedFields.contains(field) else { return } changedFields.append(field) self.changedFields = changedFields } public static func get(_ pk: Self.PrimaryKey, db: DatabaseConnection) throws -> Self? { return try selectQuery.filter(declaredPrimaryKeyField == pk).fetchOne(db) } public mutating func insert(_ db: DatabaseConnection) throws { guard !isPersisted else { throw ModelError(description: "Cannot create an already persisted model.") } try validate() let pk: PrimaryKey = try db.executeInsertQuery(query: type(of: self).insertQuery(values: persistedValuesByField), returningPrimaryKeyForField: type(of: self).declaredPrimaryKeyField) guard let newSelf = try type(of: self).get(pk, db: db) else { throw ModelError(description: "Failed to find model of supposedly inserted id \(pk)") } willSave() willInsert() self = newSelf didInsert() didSave() } public mutating func refresh(_ db: DatabaseConnection) throws { guard let pk = primaryKey, let newSelf = try Self.get(pk, db: db) else { throw ModelError(description: "Cannot refresh a non-persisted model. Please use insert() or save() first.") } willRefresh() self = newSelf didRefresh() } public mutating func update(_ db: DatabaseConnection) throws { guard let pk = primaryKey else { throw ModelError(description: "Cannot update a model that isn't persisted. Please use insert() first or save()") } let values = changedValuesByField ?? persistedValuesByField guard !values.isEmpty else { throw ModelError(description: "Nothing to save") } try validate() willSave() willUpdate() _ = try Self.updateQuery(values).filter(Self.declaredPrimaryKeyField == pk).execute(db) didUpdate() try self.refresh(db) didSave() } public mutating func delete(_ db: DatabaseConnection) throws { guard let pk = self.primaryKey else { throw ModelError(description: "Cannot delete a model that isn't persisted.") } willDelete() _ = try Self.deleteQuery.filter(Self.declaredPrimaryKeyField == pk).execute(db) didDelete() } public mutating func save(_ db: DatabaseConnection) throws { if isPersisted { try update(db) } else { try insert(db) guard isPersisted else { fatalError("Primary key not set after insert. This is a serious error in an SQL adapter. Please consult a developer.") } } } } extension Model { public func willSave() {} public func didSave() {} public func willUpdate() {} public func didUpdate() {} public func willInsert() {} public func didInsert() {} public func willDelete() {} public func didDelete() {} public func willRefresh() {} public func didRefresh() {} public func validate() throws {} }
mit
f13ee54010ce4e3125a045285a80dbb0
27.363636
186
0.677258
4.533165
false
false
false
false
AndreaMiotto/MovieNight
MovieNight/HomeViewController.swift
1
3677
// // HomeViewController.swift // MovieNight // // Created by Andrea Miotto on 09/11/16. // Copyright © 2016 Andrea Miotto. All rights reserved. // import UIKit /** This is the class for the Controller of the first view, the "Home View". From here the users can decide either to setup the filters or to show results for the movies */ class HomeViewController: UIViewController { // ------------------------------------- MARK: - Outlets @IBOutlet weak var bubble1Button: UIButton! @IBOutlet weak var bubble2Button: UIButton! // ------------------------------------- MARK: - Properties ///It's a tuple containing watcher1 and watcher2 objects var watchers: (Watcher?, Watcher?) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //if the watchers are nils if watchers.0 == nil { self.watchers.0 = Watcher(genres: [], type: .one) } if watchers.1 == nil { self.watchers.1 = Watcher(genres: [], type: .two) } //setting up the selected bubble if watchers.0!.genres.count > 0 { bubble1Button.setBackgroundImage(#imageLiteral(resourceName: "BubbleSelected"), for: .normal) } if watchers.1!.genres.count > 0 { bubble2Button.setBackgroundImage(#imageLiteral(resourceName: "BubbleSelected"), for: .normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ------------------------------------- MARK: - Methods /** Method that displays and alert */ func displayAlertWithTitle(title: String, andMessage message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } // ------------------------------------- MARK: - Navigation override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "showResults" { //this will prevent to show the results if watchers didn't set their preferences if (watchers.0!.genres.count > 0) && (watchers.1!.genres.count > 0) { return true } else { displayAlertWithTitle(title: "Missing Preferences", andMessage: "You need to set preferences for both watchers before viewing the results.") } } return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //going for watcher1 genres filter if segue.identifier == "watcher1" { let controller = (segue.destination) as! GenresListController controller.watchers = watchers controller.selectedWatcherType = watchers.0?.type } //going for watcher2 genres filter if segue.identifier == "watcher2" { let controller = (segue.destination) as! GenresListController controller.watchers = watchers controller.selectedWatcherType = watchers.1?.type } //going for movie results if segue.identifier == "showResults" { let controller = (segue.destination) as! MoviesListController controller.watchers = watchers } } }
apache-2.0
6978bec992eb87bca1323c155646e85d
33.037037
172
0.584875
5.105556
false
false
false
false
fedepo/phoneid_iOS
Example/phoneid_iOS/swift/StandardExampleViewController.swift
2
1565
// // StandardExampleViewController.swift // phoneid_iOS // // Created by Alyona on 4/6/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import phoneid_iOS class StandardExampleViewController: UIViewController, UITextFieldDelegate { @IBOutlet var phoneIdButton: PhoneIdLoginButton! var details:DetailsViewController! @IBAction func dismiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() details.presetNumber.addTarget(self, action: #selector(StandardExampleViewController.presetNumberChanged(_:)), for:.editingChanged) details.switchUserPresetNumber.addTarget(self, action: #selector(StandardExampleViewController.presetNumberSwitchChanged(_:)), for:.valueChanged) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "details" { details = segue.destination as? DetailsViewController } } @objc func presetNumberChanged(_ sender:UITextField){ phoneIdButton.phoneNumberE164 = details.switchUserPresetNumber.isOn ? sender.text : "" } @objc func presetNumberSwitchChanged(_ sender:UISwitch){ phoneIdButton.phoneNumberE164 = sender.isOn ? details.presetNumber.text : "" } }
apache-2.0
ce79a6cd05c73ca52a6b078629fcc170
30.918367
128
0.616368
5.301695
false
false
false
false
ReSwift/ReSwift-Todo-Example
ReSwift-TodoTests/Helpers.swift
1
527
// // Helpers.swift // ReSwift-Todo // // Created by Christian Tietze on 29/01/16. // Copyright © 2016 ReSwift. All rights reserved. // import Cocoa func forceLoadWindowController(_ controller: NSWindowController) { _ = controller.window } func forceLoadViewController(_ controller: NSViewController) { _ = controller.view } func button(_ button: NSButton?, isWiredToAction action: String, withTarget target: AnyObject) -> Bool { return button?.action == Selector(action) && button?.target === target }
mit
a829f4bcdb74650741bf1163e17853d0
20.916667
104
0.709125
4.015267
false
false
false
false
rmirabelli/UofD-Fall2017
RecipieReader/RecipieReader/ImageService.swift
1
1029
// // ImageService.swift // RecipieReader // // Created by Russell Mirabelli on 10/10/17. // Copyright © 2017 Russell Mirabelli. All rights reserved. // import UIKit class ImageService { static var shared = ImageService() var cache:[URL:UIImage] = [:] func imageForURL(url: URL?, completion: @escaping (UIImage?, URL?) -> ()) { guard let url = url else { completion(nil, nil); return } if let image = cache[url] { completion(image, url) return } let task = URLSession(configuration: .ephemeral).dataTask(with: url) { (data, response, error) in guard data != nil else { completion(nil, nil); return} if error != nil { completion(nil, nil); return } let image = UIImage(data: data!) if let img = image { self.cache[url] = img } DispatchQueue.main.async { completion(image, url) } } task.resume() } }
mit
ccc5323a9a00891f907aba66a26fe404
26.783784
105
0.541829
4.161943
false
false
false
false
uptech/Constraid
Tests/ConstraidTests/CupByMarginTests.swift
1
10441
import XCTest @testable import Constraid // This test is only available on iOS #if os(iOS) import UIKit class CupByMarginTests: XCTestCase { func testCupByLeadingMarginOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.cup(byLeadingMarginOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints[0] let constraintTwo = viewOne.constraints[1] let constraintThree = viewOne.constraints[2] XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.topMargin) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.leadingMargin) XCTAssertEqual(constraintTwo.constant, 10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintThree.isActive, true) XCTAssertEqual(constraintThree.firstItem as! View, viewOne) XCTAssertEqual(constraintThree.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintThree.relation, LayoutRelation.equal) XCTAssertEqual(constraintThree.secondItem as! View, viewTwo) XCTAssertEqual(constraintThree.secondAttribute, LayoutAttribute.bottomMargin) XCTAssertEqual(constraintThree.constant, -10.0) XCTAssertEqual(constraintThree.multiplier, 2.0) XCTAssertEqual(constraintThree.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testCupByTrailingMarginOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.cup(byTrailingMarginOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints[0] let constraintTwo = viewOne.constraints[1] let constraintThree = viewOne.constraints[2] XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.topMargin) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.trailingMargin) XCTAssertEqual(constraintTwo.constant, -10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintThree.isActive, true) XCTAssertEqual(constraintThree.firstItem as! View, viewOne) XCTAssertEqual(constraintThree.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintThree.relation, LayoutRelation.equal) XCTAssertEqual(constraintThree.secondItem as! View, viewTwo) XCTAssertEqual(constraintThree.secondAttribute, LayoutAttribute.bottomMargin) XCTAssertEqual(constraintThree.constant, -10.0) XCTAssertEqual(constraintThree.multiplier, 2.0) XCTAssertEqual(constraintThree.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testCupByTopMarginOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.cup(byTopMarginOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints[0] let constraintTwo = viewOne.constraints[1] let constraintThree = viewOne.constraints[2] XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.leadingMargin) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.topMargin) XCTAssertEqual(constraintTwo.constant, 10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintThree.isActive, true) XCTAssertEqual(constraintThree.firstItem as! View, viewOne) XCTAssertEqual(constraintThree.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintThree.relation, LayoutRelation.equal) XCTAssertEqual(constraintThree.secondItem as! View, viewTwo) XCTAssertEqual(constraintThree.secondAttribute, LayoutAttribute.trailingMargin) XCTAssertEqual(constraintThree.constant, -10.0) XCTAssertEqual(constraintThree.multiplier, 2.0) XCTAssertEqual(constraintThree.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testCupByBottomMarginOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.cup(byBottomMarginOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints[0] let constraintTwo = viewOne.constraints[1] let constraintThree = viewOne.constraints[2] XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.leadingMargin) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.bottomMargin) XCTAssertEqual(constraintTwo.constant, -10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(constraintThree.isActive, true) XCTAssertEqual(constraintThree.firstItem as! View, viewOne) XCTAssertEqual(constraintThree.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintThree.relation, LayoutRelation.equal) XCTAssertEqual(constraintThree.secondItem as! View, viewTwo) XCTAssertEqual(constraintThree.secondAttribute, LayoutAttribute.trailingMargin) XCTAssertEqual(constraintThree.constant, -10.0) XCTAssertEqual(constraintThree.multiplier, 2.0) XCTAssertEqual(constraintThree.priority, UILayoutPriority(rawValue: UILayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } } #endif
mit
32d8d5f66b97eaae6620173a695c3fe0
50.945274
148
0.751748
5.384734
false
false
false
false
adolfrank/Swift_practise
16-day/16-day/AddViewController.swift
1
1932
// // AddViewController.swift // 16-day // // Created by Adolfrank on 4/12/16. // Copyright © 2016 Frank. All rights reserved. // import UIKit protocol AddViewControllerDelegate:class { func addViewController(AddVC:AddViewController , Model: ContactModel) -> Void } class AddViewController: UIViewController { weak var delegate: AddViewControllerDelegate? @IBOutlet weak var nameField: UITextField! @IBOutlet weak var phoneNumberField: UITextField! @IBOutlet weak var addBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.textChange), name: UITextFieldTextDidChangeNotification, object: nameField) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.textChange), name: UITextFieldTextDidChangeNotification, object: phoneNumberField) } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } func textChange(){ if (nameField.text?.characters.count > 0 && phoneNumberField.text?.characters.count > 0) { addBtn.enabled = true addBtn.backgroundColor = UIColor.blueColor() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) nameField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addBtnDidTouch(sender: UIButton) { self.navigationController?.popViewControllerAnimated(true) let data = ContactModel() data.name = nameField.text! data.phoneNumber = phoneNumberField.text! delegate?.addViewController(self, Model: data) } }
mit
9131e7d213da65cd18d6f1fc469442a2
27.397059
180
0.677369
5.393855
false
false
false
false
ahoppen/swift
test/SILOptimizer/specialize_unconditional_checked_cast.swift
2
16608
// RUN: %target-swift-frontend -module-name specialize_unconditional_checked_cast -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil -o - -O %s | %FileCheck %s ////////////////// // Declarations // ////////////////// public class C {} public class D : C {} public class E {} public struct NotUInt8 { var value: UInt8 } public struct NotUInt64 { var value: UInt64 } var b = NotUInt8(value: 0) var c = C() var d = D() var e = E() var f = NotUInt64(value: 0) var o : AnyObject = c //////////////////////////// // Archetype To Archetype // //////////////////////////// @inline(never) public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 { return t as! T2 } ArchetypeToArchetype(t: b, t2: b) ArchetypeToArchetype(t: c, t2: c) ArchetypeToArchetype(t: b, t2: c) ArchetypeToArchetype(t: c, t2: b) ArchetypeToArchetype(t: c, t2: d) ArchetypeToArchetype(t: d, t2: c) ArchetypeToArchetype(t: c, t2: e) ArchetypeToArchetype(t: b, t2: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC{{.*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x is not a class but y is. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA1CCTg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast_addr // CHECK-NOT: unconditional_checked_cast_addr // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast_addr // y -> x where x is not a class but y is. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA8NotUInt8VTg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1DCTg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: [[STACK:%[0-9]+]] = alloc_stack $C // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK: unconditional_checked_cast_addr C in [[STACK]] : $*C to D in // y -> x where x is a super class of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1DC_AA1CCTg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: upcast {{%[0-9]+}} : $D to $C // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x and y are unrelated classes. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1ECTg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x and y are unrelated non classes. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA0H6UInt64VTg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype /////////////////////////// // Archetype To Concrete // /////////////////////////// @inline(never) public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> NotUInt8 { return t as! NotUInt8 } ArchetypeToConcreteConvertUInt8(t: b) ArchetypeToConcreteConvertUInt8(t: c) ArchetypeToConcreteConvertUInt8(t: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK-NEXT: debug_value %0 // CHECK-NEXT: return %0 // x -> y where y is a class but x is not. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are not classes and x is a different type from y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C) -> @owned C { // CHECK: bb0([[ARG:%.*]] : $C) // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: strong_retain [[ARG]] // CHECK-NEXT: return [[ARG]] // x -> y where x is a class but y is not. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are classes and x is a super class of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed D) -> @owned C { // CHECK: bb0([[ARG:%.*]] : $D): // CHECK: [[UPCAST:%.*]] = upcast [[ARG]] : $D to $C // CHECK: strong_retain [[ARG]] // CHECK: return [[UPCAST]] // CHECK: } // end sil function '$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5' // x -> y where x,y are classes, but x is unrelated to y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func ArchetypeToConcreteConvertC<T>(t t: T) -> C { return t as! C } ArchetypeToConcreteConvertC(t: c) ArchetypeToConcreteConvertC(t: b) ArchetypeToConcreteConvertC(t: d) ArchetypeToConcreteConvertC(t: e) @inline(never) public func ArchetypeToConcreteConvertD<T>(t t: T) -> D { return t as! D } ArchetypeToConcreteConvertD(t: c) // x -> y where x,y are classes and x is a sub class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed C) -> @owned D { // CHECK: bb0(%0 : $C): // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C // CHECK-DAG: store {{.*}} to [[STACK_C]] // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] @inline(never) public func ArchetypeToConcreteConvertE<T>(t t: T) -> E { return t as! E } ArchetypeToConcreteConvertE(t: c) // x -> y where x,y are classes, but y is unrelated to x. The idea is // to make sure that the fact that y is concrete does not affect the // result. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } /////////////////////////// // Concrete to Archetype // /////////////////////////// @inline(never) public func ConcreteToArchetypeConvertUInt8<T>(t t: NotUInt8, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertUInt8(t: b, t2: b) ConcreteToArchetypeConvertUInt8(t: b, t2: c) ConcreteToArchetypeConvertUInt8(t: b, t2: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 { // CHECK: bb0(%0 : $NotUInt8, %1 : $NotUInt8): // CHECK: debug_value %0 // CHECK: return %0 // x -> y where x is not a class but y is a class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are different non class types. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertC(t: c, t2: c) ConcreteToArchetypeConvertC(t: c, t2: b) ConcreteToArchetypeConvertC(t: c, t2: d) ConcreteToArchetypeConvertC(t: c, t2: e) // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $C, %1 : $C): // CHECK: return %0 // x -> y where x is a class but y is not. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: bb0(%0 : $C, %1 : $D): // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C // CHECK-DAG: store %0 to [[STACK_C]] // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] // x -> y where x and y are unrelated classes. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E { // CHECK: bb0(%0 : $C, %1 : $E): // CHECK: builtin "int_trap" // CHECK-NEXT: unreachable // CHECK-NEXT: } @inline(never) public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertD(t: d, t2: c) // x -> y where x is a subclass of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $D, %1 : $C): // CHECK-DAG: [[UC:%[0-9]+]] = upcast %0 // CHECK: return [[UC]] //////////////////////// // Super To Archetype // //////////////////////// @inline(never) public func SuperToArchetypeC<T>(c c : C, t : T) -> T { return c as! T } SuperToArchetypeC(c: c, t: c) SuperToArchetypeC(c: c, t: d) SuperToArchetypeC(c: c, t: b) // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $C, %1 : $C): // CHECK: return %0 // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: bb0 // CHECK: unconditional_checked_cast_addr C in // x -> y where x is a class and y is not. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func SuperToArchetypeD<T>(d d : D, t : T) -> T { return d as! T } SuperToArchetypeD(d: d, t: c) SuperToArchetypeD(d: d, t: d) // *NOTE* The frontend is smart enough to turn this into an upcast. When this // test is converted to SIL, this should be fixed appropriately. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast super_to_archetype // CHECK: upcast // CHECK-NOT: unconditional_checked_cast super_to_archetype // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed D, @guaranteed D) -> @owned D { // CHECK: bb0(%0 : $D, %1 : $D): // CHECK: return %0 ////////////////////////////// // Existential To Archetype // ////////////////////////////// @inline(never) public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T { return o as! T } // AnyObject -> Class. // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed C) -> @owned C { // CHECK: unconditional_checked_cast_addr AnyObject in {{%.*}} : $*AnyObject to C // AnyObject -> Non Class (should always fail) // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed AnyObject, NotUInt8) -> NotUInt8 { // CHECK-NOT: builtin "int_trap"() // CHECK-NOT: unreachable // CHECK: return // AnyObject -> AnyObject // CHECK-LABEL: sil shared [noinline] {{.*}}@$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}yXl{{.*}}Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> @owned AnyObject { // CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject): // CHECK: return %0 ExistentialToArchetype(o: o, t: c) ExistentialToArchetype(o: o, t: b) ExistentialToArchetype(o: o, t: o) // Ensure that a downcast from an Optional source is not promoted to a // value cast. We could do the promotion, but the optimizer would need // to insert the Optional unwrapping logic before the cast. // // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast15genericDownCastyq_x_q_mtr0_lFAA1CCSg_AA1DCTg5 : $@convention(thin) (@guaranteed Optional<C>, @thick D.Type) -> @owned D { // CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type): // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C> // CHECK-DAG: store [[ARG]] to [[STACK_C]] // CHECK-DAG: retain_value [[ARG]] // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] @inline(never) public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U { return a as! U } public func callGenericDownCast(_ c: C?) -> D { return genericDownCast(c, D.self) }
apache-2.0
3ff7423a7357e34706348a2cdf131526
42.590551
229
0.675698
3.273157
false
false
false
false
bingoogolapple/SwiftNote-PartOne
静态单元格设置程序/静态单元格设置程序/ViewController.swift
1
2365
// // ViewController.swift // 静态单元格设置程序 // // Created by bingoogol on 14/9/25. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UITableViewController { var dataList:NSArray! override func loadView() { self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame,style:UITableViewStyle.Grouped) } override func viewDidLoad() { super.viewDidLoad() var path = NSBundle.mainBundle().pathForResource("settings", ofType: "plist") self.dataList = NSArray(contentsOfFile: path!) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dataList.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var array = self.dataList[section] as NSArray return array.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell // 根据字典中是否定义了detail来决定表格样式 var dict = self.dataList[indexPath.section][indexPath.row] as NSDictionary var detail = dict["detail"] as NSString? if detail == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)! } else { cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: nil)! cell.detailTextLabel?.text = detail } cell.textLabel?.text = dict["name"] as NSString cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if 0 == indexPath.section && 0 == indexPath.row { var cell = tableView.cellForRowAtIndexPath(indexPath) cell?.tag = cell?.tag == 0 ? 1 : 0 cell?.detailTextLabel?.text = cell?.tag == 1 ? "打开" : "关闭" } var dict = self.dataList[indexPath.section][indexPath.row] as NSDictionary var id = dict["id"] as NSString println("id:\(id)") // 如果有后续的内容,可以通过获取到的id,加载对应的Plist文件即可 } }
apache-2.0
cf5cee0effb1d0487c8a9003c4bcb15b
35.290323
118
0.65896
4.867965
false
false
false
false
Xiomara7/bookiao-ios
bookiao-ios/HTTPrequests.swift
1
23621
// // HTTPrequests.swift // bookiao-ios // // Created by Xiomara on 11/5/14. // Copyright (c) 2014 UPRRP. All rights reserved. // import Foundation import UIKit import CoreData class HTTPrequests { class var sharedManager: HTTPrequests { struct Singleton { static let instance = HTTPrequests() } return Singleton.instance } let baseURL: NSString = "https://bookiao-api-staging.herokuapp.com" func initRequest(method: String!, url: NSURL!, params: NSDictionary?) -> NSMutableURLRequest { println(method) var request = NSMutableURLRequest(URL: url!) var err: NSError? request.HTTPMethod = method request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") if params != nil { request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params!, options: nil, error: &err) } if (DataManager.sharedManager.token as String! != nil) { request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") } return request } func isRequestValid(response: NSURLResponse?) -> Bool { if response != nil { let resp = response as NSHTTPURLResponse! if (resp.statusCode >= 200 && resp.statusCode < 300) {return true} } return false } func registerRequest(email: NSString, name: NSString, phone: NSString, passwd: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email":email, "name":name, "phone_number": phone,"password":passwd] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/register/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { if let block = completion {block (str: "ok", error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func authRequest(email: NSString, passwd: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email":email,"password":passwd] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/api-token-auth/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: nil) as NSDictionary DataManager.sharedManager.token = json["token"] as String! dispatch_async(dispatch_get_main_queue(), { if self.isRequestValid(response) { if let block = completion {block (str: "ok", error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) } }) task.resume() } func loginRequest(email: NSString, password: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email" : email,"password" : password] as Dictionary var request = self.initRequest("POST", url: NSURL(string: "\(baseURL)/api-token-auth/")!, params: params) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:nil) as NSDictionary if let block = completion {block (str: json["token"] as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func clientsReq(email: NSString, name: NSString, phone: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email":email, "name":name, "phone_number":phone] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/clients/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) println("token : \(DataManager.sharedManager.token)") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println("Client response: \(response)") if self.isRequestValid(response) { if let block = completion {block (str: "ok", error: nil)} } else {if let block = completion {block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} }) task.resume() } func createBusinessRequest(email: NSString, name: NSString, phone: NSString, man: NSString, loc: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email":email, "name":name, "phone_number":phone, "manager_name": man, "location":loc] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/businesses/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var strData = NSString(data: data, encoding: NSUTF8StringEncoding) println("Body: \(strData)\n\n") } }) task.resume() } func employeeReq(email: NSString, name: NSString, phone: NSString, business: Int, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email":email, "name":name, "phone_number":phone, "business": business] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/employees/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var strData = NSString(data: data, encoding: NSUTF8StringEncoding) println("Body: \(strData)\n\n") } }) task.resume() } func editProfile(userType: NSString, id: Int, nombre: NSString, email: NSString, telefono: NSString, negocio: Int){ var params = ["email":email, "name":nombre, "phone_number": telefono, "business":negocio] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/\(userType)/\(id)/")!) request.HTTPMethod = "PUT" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:nil) as NSDictionary var success = json["response"] as? String! println("Succes: \(success)") self.getClients() self.getEmployees() self.getUserInfo(email, completion: { (str, error) -> Void in println("HELO") }) } }) task.resume() } func createAppointment(services: NSArray, employee: NSString, client: NSString, date: NSString, theTime: NSString){ var params = ["day":date, "time": theTime, "services": services, "employee":employee, "client":client] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/appointments/")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var strData = NSString(data: data, encoding: NSUTF8StringEncoding) println("Body: \(strData)\n\n") } }) task.resume() } func getBusinesses() { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/businesses/")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var newdata : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary! DataManager.sharedManager.titles = newdata["results"] as NSArray! } }) task.resume() } func getClients() { println("am I doing this request?? HELLO") var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/clients/")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var newdata : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary! DataManager.sharedManager.client = newdata["results"] as NSArray! println( newdata["results"] as NSArray!) } }) task.resume() } func getEmployeeAppointments(id: Int, completion: ((str: String?, error:NSError?)-> Void)?) { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/appointments/?employee=\(id)&ordering=time")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.employeeAppointments = newData["results"] as NSArray if let block = completion {block (str: "ok" as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func getEmployeeAppointmentsPerDay(id: Int, date: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/appointments/?day=\(date)&employee=\(id)&ordering=time")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.employeeAppointmentsPerDay = newData["results"] as NSArray if let block = completion {block (str: "ok" as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func getClientAppointmentsPerDay(id: Int, date: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/appointments/?day=\(date)&client=\(id)&ordering=time")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println(response) if self.isRequestValid(response) { var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.clientAppointmentsPerDay = newData["results"] as NSArray if let block = completion {block (str: "ok" as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func getClientAppointments(id: Int, completion: ((str: String?, error:NSError?)-> Void)?) { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/appointments/?client=\(id)&ordering=time")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("JWT \(DataManager.sharedManager.token)", forHTTPHeaderField: "Authorization") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.clientAppointments = newData["results"] as NSArray if let block = completion {block (str: "ok" as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func getEmployees() { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/employees/")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var strData = NSString(data: data, encoding: NSUTF8StringEncoding)! var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.employees = newData["results"] as NSArray! println(DataManager.sharedManager.employees) } }) task.resume() } func getServices() { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/services/")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary DataManager.sharedManager.services = newData["results"] as NSArray! println(DataManager.sharedManager.services) } }) task.resume() } func getUserInfo(email: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/user-type/?email=\(email)")!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { println("UserInfo Resp: \(response)") var newData : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary! DataManager.sharedManager.userInfo = newData as NSDictionary! println("Userinfo: \(DataManager.sharedManager.userInfo)") let id = DataManager.sharedManager.userInfo["id"] as Int! let ut = DataManager.sharedManager.userInfo["userType"] as String! if ut == "client" { self.getClientAppointments(id, completion: { (str, error) -> Void in }) self.getClientAppointmentsPerDay(id, date: DataManager.sharedManager.date, completion: { (str, error) -> Void in }) } if ut == "employee" { self.getEmployeeAppointments(id, completion: { (str, error) -> Void in }) self.getEmployeeAppointmentsPerDay(id, date: DataManager.sharedManager.date, completion: { (str, error) -> Void in }) } if let block = completion {block (str: "ok" as String!, error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } func subscription(email: NSString, completion: ((str: String?, error:NSError?)-> Void)?) { var params = ["email": email] as Dictionary var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)/betaemails")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil) var session = NSURLSession.sharedSession() var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.isRequestValid(response) { println(response) if let block = completion {block (str: "ok", error: nil)} else {if let block = completion { block (str: nil, error: NSError(domain: "Error", code: 0, userInfo: nil))}} } else {if let block = completion {block (str: nil, error: nil)}} }) task.resume() } }
mit
24aa77a95e2997b3af1776c5da84df8b
52.808656
166
0.632869
4.902657
false
false
false
false
iDevelopMSD/FBMessengerShareLocation
FBMessengerShareLocation/FBMessengerShareLocation/ChooseLocationViewController.swift
1
5699
// // ChooseLocationViewController.swift // FBMessengerShareLocation // // Created by Mustafa Sait Demirci on 17/05/15. // Copyright (c) 2015 msdeveloper. All rights reserved. // //MARK: - IMPORTS - import UIKit import CoreLocation import MapKit //MARK: - Assigning Selected Delegate - protocol SelectedDelegate : class { func locationSelected(selectedLocation:CLLocation!) } //MARK: - BEGİNNİNG OF SUPERCLASS - class ChooseLocationViewController: UIViewController, MKMapViewDelegate { //MARK: - Variables,IBOutlets - @IBOutlet var mapView: MKMapView! weak var selectedLocationDelegate:SelectedDelegate? var objectAnnotation = MKPointAnnotation() var addressString : String="" var selectedLocation: CLLocation? var loadingAnimation : UIActivityIndicatorView! //MARK: - LifeCycle - override func viewDidDisappear(animated: Bool) { // There is a general bug releasing mapview cache applyMapViewMemoryHotFix() } override func viewDidLoad() { super.viewDidLoad() var center:CLLocationCoordinate2D if(self.selectedLocation != nil) { center = CLLocationCoordinate2D(latitude:self.selectedLocation!.coordinate.latitude, longitude:self.selectedLocation!.coordinate.longitude) } else { center = CLLocationCoordinate2D(latitude:37.3316309, longitude:-122.029584) self.selectedLocation=CLLocation(latitude:center.latitude, longitude:center.longitude) } // Activity Indicator initialize loadingAnimation = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) loadingAnimation.center=self.view.center loadingAnimation.hidesWhenStopped=true self.view.addSubview(loadingAnimation) addAnnotation(center) findAddress() } //MARK: - MapView Memory Releasing - func applyMapViewMemoryHotFix() { switch (self.mapView.mapType) { case MKMapType.Standard: self.mapView.mapType = MKMapType.Hybrid default: break; } self.mapView.showsUserLocation = false; self.mapView.removeAnnotations(self.mapView.annotations) self.mapView.delegate = nil; self.mapView.removeFromSuperview(); self.mapView = nil; } //MARK: - Add Annotation to Map View - func addAnnotation(center : CLLocationCoordinate2D) { loadingAnimation.startAnimating() let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.mapView.setRegion(region, animated: true) if(self.mapView.annotations.count>0) { self.mapView.removeAnnotations(self.mapView.annotations) } objectAnnotation.coordinate = center self.mapView.addAnnotation(objectAnnotation) } //MARK: - MKMapViewDelegate Methods - func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { if newState == MKAnnotationViewDragState.Ending { let ann = view.annotation println("annotation dropped at: \(ann.coordinate.latitude),\(ann.coordinate.longitude)") self.selectedLocation=CLLocation(latitude: ann.coordinate.latitude, longitude: ann.coordinate.longitude) findAddress() } } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation is MKPointAnnotation { let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") pinAnnotationView.pinColor = .Purple pinAnnotationView.draggable = true pinAnnotationView.canShowCallout = true pinAnnotationView.animatesDrop = true return pinAnnotationView } return nil } func findAddress() { CLGeocoder().reverseGeocodeLocation(self.selectedLocation, completionHandler: {(placemarks, error)->Void in if (error != nil) { println("Reverse geocoder failed with error" + error.localizedDescription) self.objectAnnotation.title="Couldn't find address info..."; return } if placemarks.count > 0 { let pm = placemarks[0] as! CLPlacemark self.addressString = self.selectedLocation!.getLocationAddress(pm) self.objectAnnotation.title=self.addressString } else { self.objectAnnotation.title="Couldn't find address info."; println("Problem with the data received from geocoder") } self.loadingAnimation.stopAnimating() }) } //MARK: - Pick and Cancel Button Actions - @IBAction func cancelButtonTouched(sender: UIButton) { self .dismissViewControllerAnimated(true, completion: nil) } @IBAction func selectLocationButtonTouched(sender: UIButton) { if self.selectedLocation != nil { selectedLocationDelegate?.locationSelected(selectedLocation) } self .dismissViewControllerAnimated(true, completion: nil) } //MARK: - END OF SUPERCLASS - }
mit
607be7c660aab25294661cad1e999135
31.930636
183
0.635773
5.384688
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_2_fixed/0019-rdar21511651.swift
1
14318
// RUN: not %target-swift-frontend %s -typecheck internal protocol _SequenceWrapper { typealias Base : Sequence typealias Iterator : IteratorProtocol = Base.Iterator var _base: Base {get} } extension Sequence where Self : _SequenceWrapper, Self.Iterator == Self.Base.Iterator { public func makeIterator() -> Base.Iterator { return self._base.makeIterator() } public func underestimatedCount() -> Int { return _base.underestimatedCount() } public func _customContainsEquatableElement( element: Base.Iterator.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>(_ preprocess: (Self) -> R) -> R? { return _base._preprocessingPass { _ in preprocess(self) } } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Base.Iterator.Element> { return _base._copyToNativeArrayBuffer() } /// Copy a Sequence into an array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) { return _base._copyContents(initializing: ptr) } } internal protocol _CollectionWrapper : _SequenceWrapper { typealias Base : Collection typealias Index : ForwardIndex = Base.Index var _base: Base {get} } extension Collection where Self : _CollectionWrapper, Self.Index == Self.Base.Index { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Base.Index { return _base.startIndex } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Base.Index { return _base.endIndex } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Base.Index) -> Base.Iterator.Element { return _base[position] } } //===--- New stuff --------------------------------------------------------===// public protocol _prext_LazySequence : Sequence { /// A Sequence that can contain the same elements as this one, /// possibly with a simpler type. /// /// This associated type is used to keep the result type of /// `lazy(x).operation` from growing a `_prext_LazySequence` layer. typealias Elements: Sequence = Self /// A sequence containing the same elements as this one, possibly with /// a simpler type. /// /// When implementing lazy operations, wrapping `elements` instead /// of `self` can prevent result types from growing a `_prext_LazySequence` /// layer. /// /// Note: this property need not be implemented by conforming types, /// it has a default implementation in a protocol extension that /// just returns `self`. var elements: Elements {get} /// An Array, created on-demand, containing the elements of this /// lazy Sequence. /// /// Note: this property need not be implemented by conforming types, it has a /// default implementation in a protocol extension. var array: [Iterator.Element] {get} } extension _prext_LazySequence { /// an Array, created on-demand, containing the elements of this /// lazy Sequence. public var array: [Iterator.Element] { return Array(self) } } extension _prext_LazySequence where Elements == Self { public var elements: Self { return self } } extension _prext_LazySequence where Self : _SequenceWrapper { public var elements: Base { return _base } } /// A sequence that forwards its implementation to an underlying /// sequence instance while exposing lazy computations as methods. public struct _prext_LazySequence<Base_ : Sequence> : _SequenceWrapper { var _base: Base_ } /// Augment `s` with lazy methods such as `map`, `filter`, etc. public func _prext_lazy<S : Sequence>(s: S) -> _prext_LazySequence<S> { return _prext_LazySequence(_base: s) } public extension Sequence where Self.Iterator == Self, Self : IteratorProtocol { public func makeIterator() -> Self { return self } } //===--- LazyCollection.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol _prext_LazyCollection : Collection, _prext_LazySequence { /// A Collection that can contain the same elements as this one, /// possibly with a simpler type. /// /// This associated type is used to keep the result type of /// `lazy(x).operation` from growing a `_prext_LazyCollection` layer. typealias Elements: Collection = Self } extension _prext_LazyCollection where Elements == Self { public var elements: Self { return self } } extension _prext_LazyCollection where Self : _CollectionWrapper { public var elements: Base { return _base } } /// A collection that forwards its implementation to an underlying /// collection instance while exposing lazy computations as methods. public struct _prext_LazyCollection<Base_ : Collection> : /*_prext_LazyCollection,*/ _CollectionWrapper { typealias Base = Base_ typealias Index = Base.Index /// Construct an instance with `base` as its underlying Collection /// instance. public init(_ base: Base_) { self._base = base } public var _base: Base_ // FIXME: Why is this needed? // public var elements: Base { return _base } } /// Augment `s` with lazy methods such as `map`, `filter`, etc. public func _prext_lazy<Base: Collection>(s: Base) -> _prext_LazyCollection<Base> { return _prext_LazyCollection(s) } //===--- New stuff --------------------------------------------------------===// /// The `IteratorProtocol` used by `_prext_MapSequence` and `_prext_MapCollection`. /// Produces each element by passing the output of the `Base` /// `IteratorProtocol` through a transform function returning `T`. public struct _prext_MapIterator< Base: IteratorProtocol, T > : IteratorProtocol, Sequence { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> T? { let x = _base.next() if x != nil { return _transform(x!) } return nil } var _base: Base var _transform: (Base.Element)->T } //===--- Sequences --------------------------------------------------------===// /// A `Sequence` whose elements consist of those in a `Base` /// `Sequence` passed through a transform function returning `T`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. public struct _prext_MapSequence<Base : Sequence, T> : _prext_LazySequence, _SequenceWrapper { typealias Elements = _prext_MapSequence public func makeIterator() -> _prext_MapIterator<Base.Iterator,T> { return _prext_MapIterator( _base: _base.makeIterator(), _transform: _transform) } var _base: Base var _transform: (Base.Iterator.Element)->T } //===--- Collections ------------------------------------------------------===// /// A `Collection` whose elements consist of those in a `Base` /// `Collection` passed through a transform function returning `T`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. public struct _prext_MapCollection<Base : Collection, T> : _prext_LazyCollection, _CollectionWrapper { public var startIndex: Base.Index { return _base.startIndex } public var endIndex: Base.Index { return _base.endIndex } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Base.Index) -> T { return _transform(_base[position]) } public func makeIterator() -> _prext_MapIterator<Base.Iterator, T> { return _prext_MapIterator(_base: _base.makeIterator(), _transform: _transform) } public func underestimatedCount() -> Int { return _base.underestimatedCount() } var _base: Base var _transform: (Base.Iterator.Element)->T } //===--- Support for lazy(s) ----------------------------------------------===// extension _prext_LazySequence { /// Return a `_prext_MapSequence` over this `Sequence`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. public func map<U>( transform: (Elements.Iterator.Element) -> U ) -> _prext_MapSequence<Self.Elements, U> { return _prext_MapSequence(_base: self.elements, _transform: transform) } } extension _prext_LazyCollection { /// Return a `_prext_MapCollection` over this `Collection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. public func map<U>( transform: (Elements.Iterator.Element) -> U ) -> _prext_MapCollection<Self.Elements, U> { return _prext_MapCollection(_base: self.elements, _transform: transform) } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End: //===--- New stuff --------------------------------------------------------===// internal protocol __prext_ReverseCollection : _prext_LazyCollection { typealias Base : Collection var _base : Base {get} } /// A wrapper for a `BidirectionalIndex` that reverses its /// direction of traversal. public struct _prext_ReverseIndex<I : BidirectionalIndex> : BidirectionalIndex { var _base: I init(_ _base: I) { self._base = _base } /// Returns the next consecutive value after `self`. /// /// - Precondition: The next value is representable. public func successor() -> _prext_ReverseIndex { return _prext_ReverseIndex(_base.predecessor()) } /// Returns the previous consecutive value before `self`. /// /// - Precondition: The previous value is representable. public func predecessor() -> _prext_ReverseIndex { return _prext_ReverseIndex(_base.successor()) } /// A type that can represent the number of steps between pairs of /// `_prext_ReverseIndex` values where one value is reachable from the other. typealias Distance = I.Distance } /// A wrapper for a `${IndexProtocol}` that reverses its /// direction of traversal. public struct _prext_ReverseRandomAccessIndex<I : RandomAccessIndex> : RandomAccessIndex { var _base: I init(_ _base: I) { self._base = _base } /// Returns the next consecutive value after `self`. /// /// - Precondition: The next value is representable. public func successor() -> _prext_ReverseRandomAccessIndex { return _prext_ReverseRandomAccessIndex(_base.predecessor()) } /// Returns the previous consecutive value before `self`. /// /// - Precondition: The previous value is representable. public func predecessor() -> _prext_ReverseRandomAccessIndex { return _prext_ReverseRandomAccessIndex(_base.successor()) } /// A type that can represent the number of steps between pairs of /// `_prext_ReverseRandomAccessIndex` values where one value is reachable from the other. typealias Distance = I.Distance /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// - Complexity: O(1). public func distance(to other: _prext_ReverseRandomAccessIndex) -> Distance { return other._base.distance(to: _base) } /// Return `self` offset by `n` steps. /// /// - Returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// - Complexity: O(1). public func advanced(by amount: Distance) -> _prext_ReverseRandomAccessIndex { return _prext_ReverseRandomAccessIndex(_base.advanced(by: -amount)) } } public func == <I> (lhs: _prext_ReverseIndex<I>, rhs: _prext_ReverseIndex<I>) -> Bool { return lhs._base == rhs._base } public func == <I> (lhs: _prext_ReverseRandomAccessIndex<I>, rhs: _prext_ReverseRandomAccessIndex<I>) -> Bool { return lhs._base == rhs._base } extension Collection where Self : __prext_ReverseCollection, Self.Base.Index : BidirectionalIndex { public var startIndex : _prext_ReverseIndex<Base.Index> { return _prext_ReverseIndex<Base.Index>(_base.endIndex) } public var endIndex : _prext_ReverseIndex<Base.Index> { return _prext_ReverseIndex<Base.Index>(_base.startIndex) } public subscript(position: _prext_ReverseIndex<Base.Index>) -> Base.Iterator.Element { return _base[position._base.predecessor()] } } extension Collection where Self : __prext_ReverseCollection, Self.Base.Index : RandomAccessIndex { public var startIndex : _prext_ReverseRandomAccessIndex<Base.Index> { return _prext_ReverseRandomAccessIndex<Base.Index>(_base.endIndex) } public var endIndex : _prext_ReverseRandomAccessIndex<Base.Index> { return _prext_ReverseRandomAccessIndex<Base.Index>(_base.startIndex) } public subscript(position: _prext_ReverseRandomAccessIndex<Base.Index>) -> Base.Iterator.Element { return _base[position._base.predecessor()] } } /// The lazy `Collection` returned by `c.reversed()` where `c` is a /// `Collection` with an `Index` conforming to `${IndexProtocol}`. public struct _prext_ReverseCollection<Base : Collection> : Collection, __prext_ReverseCollection { public init(_ _base: Base) { self._base = _base } internal var _base: Base }
apache-2.0
2d5eab9838f6cd990789b381fba1342d
32.220418
111
0.670624
4.144139
false
false
false
false
dzt/MobilePassport
ios/ios/ImageLoader/UIImageView+ImageLoader.swift
1
3284
// // UIImageView+ImageLoader.swift // ImageLoader // // Created by Hirohisa Kawasaki on 10/17/14. // Copyright © 2014 Hirohisa Kawasaki. All rights reserved. // import Foundation import UIKit private var ImageLoaderURLKey = 0 private var ImageLoaderBlockKey = 0 /** Extension using ImageLoader sends a request, receives image and displays. */ extension UIImageView { public static var imageLoader = Manager() // MARK: - properties private static let _ioQueue = dispatch_queue_create("swift.imageloader.queues.io", DISPATCH_QUEUE_CONCURRENT) private var URL: NSURL? { get { var URL: NSURL? dispatch_sync(UIImageView._ioQueue) { URL = objc_getAssociatedObject(self, &ImageLoaderURLKey) as? NSURL } return URL } set(newValue) { dispatch_barrier_async(UIImageView._ioQueue) { objc_setAssociatedObject(self, &ImageLoaderURLKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } private static let _Queue = dispatch_queue_create("swift.imageloader.queues.request", DISPATCH_QUEUE_SERIAL) // MARK: - functions public func load(URL: URLLiteralConvertible, placeholder: UIImage? = nil, completionHandler:CompletionHandler? = nil) { let block: () -> Void = { [weak self] in guard let wSelf = self else { return } wSelf.cancelLoading() } enqueue(block) image = placeholder imageLoader_load(URL.imageLoaderURL, completionHandler: completionHandler) } public func cancelLoading() { if let URL = URL { UIImageView.imageLoader.cancel(URL, identifier: hash) } } // MARK: - private private func imageLoader_load(URL: NSURL, completionHandler: CompletionHandler?) { let handler: CompletionHandler = { [weak self] URL, image, error, cacheType in if let wSelf = self, thisURL = wSelf.URL, image = image where thisURL.isEqual(URL) { wSelf.imageLoader_setImage(image) } completionHandler?(URL, image, error, cacheType) } // caching if let data = UIImageView.imageLoader.cache[URL] { self.URL = URL handler(URL, UIImage.decode(data), nil, .Cache) return } let identifier = hash let block: () -> Void = { [weak self] in guard let wSelf = self else { return } let block = Block(identifier: identifier, completionHandler: handler) UIImageView.imageLoader.load(URL).appendBlock(block) wSelf.URL = URL } enqueue(block) } private func enqueue(block: () -> Void) { dispatch_async(UIImageView._Queue, block) } private func imageLoader_setImage(image: UIImage) { dispatch_async(dispatch_get_main_queue()) { [weak self] in guard let wSelf = self else { return } if UIImageView.imageLoader.automaticallyAdjustsSize { wSelf.image = image.adjusts(wSelf.frame.size, scale: UIScreen.mainScreen().scale, contentMode: wSelf.contentMode) } else { wSelf.image = image } } } }
mit
65819b96ea9e0861f659d507cbc302a7
28.854545
129
0.608894
4.656738
false
false
false
false
Swerfvalk/SwerfvalkExtensionKit
Source/UIViewExtension.swift
1
20090
// // UIViewExtension.swift // SwerfvalkExtensionKit // // Created by 萧宇 on 14/08/2017. // Copyright © 2017 Swerfvalk. All rights reserved. // import UIKit import ObjectiveC public var kScreenWidth: CGFloat { return UIScreen.main.bounds.size.width } public var kScreenHeight: CGFloat { return UIScreen.main.bounds.size.height } public var kDefaultMargin: CGFloat { return 8.0 } public var kWiderMargin: CGFloat { return 20.0 } public var kStatusBarHeight: CGFloat { return 20.0 } public var kNavigationBarHeight: CGFloat { return 44.0 } public var kHeaderHeight: CGFloat { return kStatusBarHeight + kNavigationBarHeight } public var kTabBarHeight: CGFloat { return 49.0 } fileprivate var kLoadingActivityViewKey = "LoadingActivityView" fileprivate var kMessageTipsViewKey = "MessageTipsView" fileprivate var kMessageTipsTimerKey = "MessageTipsTimer" fileprivate var kMessageTipsCompletionKey = "MessageTipsCompletion" fileprivate var kTopTipsViewKey = "TopTipsView" fileprivate var kTopTipsTimerKey = "TopTipsTimer" fileprivate var kUserInfoKey = "UserInfo" public extension UIView { /// A shortcut of frame.origin. public var origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } /// A shortcut of frame.size. public var size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } /// A shortcut of layer.cornerRadius. public var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.masksToBounds = true self.layer.cornerRadius = newValue self.contentMode = .scaleToFill } } /// The view controller which the view belongs to. public var viewController: UIViewController? { var next: UIResponder? = self.next repeat { if let next = next as? UIViewController { return next } else { next = next?.next } } while next != nil return nil } /// A variable used to store information that can transfer data in the target-action pattern. public var userInfo: [AnyHashable : Any] { get { if objc_getAssociatedObject(self, &kUserInfoKey) == nil { let userInfo = [AnyHashable : Any]() objc_setAssociatedObject(self, &kUserInfoKey, userInfo, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return objc_getAssociatedObject(self, &kUserInfoKey) as! [AnyHashable : Any] } set { var userInfo = [AnyHashable : Any]() if let oldValue = objc_getAssociatedObject(self, &kUserInfoKey) { userInfo = newValue + (oldValue as! [AnyHashable : Any]) } else { userInfo = newValue } objc_setAssociatedObject(self, &kUserInfoKey, userInfo, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Add multiple subviews. /// /// - Parameter subviews: The subviews to add. public func addSubviews(_ subviews: Set<UIView>) { for view in subviews { self.addSubview(view) } } /// Remove multiple subviews. /// /// - Parameter subviews: The subviews to remove. public func removeSubviews(_ subviews: Set<UIView>) { for view in subviews { view.removeFromSuperview() } } /// Remove all subviews. public func removeAllSubviews() { for view in self.subviews { view.removeFromSuperview() } } } @available(iOSApplicationExtension 9.0, *) public extension UIView { // MARK: - Loading /// Showing loading indicator. public func showLoading() { guard objc_getAssociatedObject(self, &kLoadingActivityViewKey) == nil else { return } let activityView = UIView() activityView.backgroundColor = UIColor.gray.withAlphaComponent(0.8) activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.cornerRadius = kDefaultMargin let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicatorView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) activityView.addSubview(activityIndicatorView) activityIndicatorView.makeConstraints { (view) in view.centerX.equalTo(activityView.centerX) view.centerY.equalTo(activityView.centerY) } activityIndicatorView.startAnimating() objc_setAssociatedObject(self, &kLoadingActivityViewKey, activityView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(activityView) activityView.makeConstraints { (view) in view.centerX.equalTo(self.centerX) view.centerY.equalTo(self.centerY) view.width.equalToConstant(kHeaderHeight) view.height.equalToConstant(kHeaderHeight) } UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { activityView.alpha = 1.0 }, completion: nil) } /// Hide loading indicator. public func hideLoading() { if let existingActivityView = objc_getAssociatedObject(self, &kLoadingActivityViewKey) as? UIView { UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { existingActivityView.alpha = 0.0 }, completion: { (finished) in existingActivityView.removeFromSuperview() objc_setAssociatedObject(self, &kLoadingActivityViewKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } } // MARK: - Message /// Show message with string and image. /// /// - Parameters: /// - message: The string to show. /// - name: The name of image to show. `nil` by default. /// - duration: The duration of showing, 3.0 by default. /// - completion: A closure executed when the show finished. `nil` by default. public func showMessage(_ message: String?, imageNamed name: String? = nil, duration: CGFloat = 3.0, completion: (() -> Void)? = nil) { guard objc_getAssociatedObject(self, &kMessageTipsViewKey) == nil else { return } let tipsView = self.tipsView(for: message, image: UIImage(named: name ?? "")) objc_setAssociatedObject(tipsView, &kMessageTipsCompletionKey, completion, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) tipsView.center = CGPoint(x: self.size.width / 2, y: self.size.height / 2) tipsView.alpha = 0.0 objc_setAssociatedObject(self, &kMessageTipsViewKey, tipsView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(tipsView) UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { tipsView.alpha = 1.0 }) { (finished: Bool) in let timer = Timer.scheduledTimer(timeInterval: TimeInterval(duration), target: self, selector: #selector(self.tipsViewTimerDidFinish(_:)), userInfo: tipsView, repeats: false) objc_setAssociatedObject(self, &kMessageTipsTimerKey, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Creates a tips view. /// /// - Parameters: /// - message: The string to show. /// - image: The image to show. /// - Returns: Created tips view. private func tipsView(`for` message: String?, image: UIImage?) -> UIView { if message == nil && image == nil { return UIView() } let wrapperView = UIView() wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.cornerRadius = kDefaultMargin wrapperView.backgroundColor = UIColor.gray.withAlphaComponent(0.8) var imageView: UIImageView? if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFill } var messageLabel: UILabel? var expectedSize: CGSize? if let message = message { messageLabel = UILabel() messageLabel?.numberOfLines = 0 messageLabel?.font = UIFont.systemFont(ofSize: 16.0) messageLabel?.textAlignment = .center messageLabel?.lineBreakMode = .byWordWrapping messageLabel?.textColor = UIColor.white messageLabel?.backgroundColor = UIColor.clear messageLabel?.alpha = 1.0 messageLabel?.text = message let maxSizeOfMessageLabel = CGSize(width: imageView == nil ? self.bounds.size.width * 0.618 : kHeaderHeight + kWiderMargin + 2, height: self.bounds.size.height) expectedSize = self.size(for: message, font: (messageLabel?.font)!, constrainedTo: maxSizeOfMessageLabel, lineBreakMode: (messageLabel?.lineBreakMode)!) } self.addSubview(wrapperView) wrapperView.makeConstraints { (view) in view.centerX.equalTo(self.centerX) view.centerY.equalTo(self.centerY) } if let imageView = imageView, messageLabel == nil { wrapperView.addSubview(imageView) imageView.makeConstraints({ (view) in view.top.equalTo(wrapperView.top).offset(kWiderMargin) view.leading.equalTo(wrapperView.leading).offset(kWiderMargin) view.trailing.equalTo(wrapperView.trailing).offset(-kWiderMargin) view.bottom.equalTo(wrapperView.bottom).offset(-kWiderMargin) view.width.equalToConstant(kHeaderHeight) view.height.equalToConstant(kHeaderHeight) }) return wrapperView } else if let messageLabel = messageLabel, imageView == nil { wrapperView.addSubview(messageLabel) messageLabel.makeConstraints({ (view) in view.top.equalTo(wrapperView.top).offset(kDefaultMargin) view.leading.equalTo(wrapperView.leading).offset(kDefaultMargin) view.trailing.equalTo(wrapperView.trailing).offset(-kDefaultMargin) view.bottom.equalTo(wrapperView.bottom).offset(-kDefaultMargin) view.width.equalToConstant((expectedSize?.width)!) view.height.equalToConstant((expectedSize?.height)!) }) return wrapperView } else { wrapperView.addSubview(imageView!) wrapperView.addSubview(messageLabel!) imageView?.makeConstraints({ (view) in view.top.equalTo(wrapperView.top).offset(kWiderMargin) view.leading.equalTo(wrapperView.leading).offset(kWiderMargin + kDefaultMargin) view.trailing.equalTo(wrapperView.trailing).offset(-(kWiderMargin + kDefaultMargin)) view.width.equalToConstant(kHeaderHeight) view.height.equalToConstant(kHeaderHeight) }) messageLabel?.makeConstraints({ (view) in view.top.equalTo((imageView?.bottom)!).offset(kWiderMargin) view.bottom.equalTo(wrapperView.bottom).offset(-kDefaultMargin) view.centerX.equalTo(wrapperView.centerX) view.width.equalToConstant((expectedSize?.width)!) view.height.equalToConstant((expectedSize?.height)!) }) return wrapperView } } /// Calculates the size of the label. /// /// - Parameters: /// - string: The string of the label. /// - font: The string of the label. /// - constrainedSize: The constrainted size. /// - lineBreakMode: The ling break mode of the label. /// - Returns: The size of the label. private func size(`for` string: String, font: UIFont, constrainedTo constrainedSize: CGSize, lineBreakMode: NSLineBreakMode) -> CGSize { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode let attributes = [NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle] let boundingRect = string.boundingRect(with: constrainedSize, options: [.usesLineFragmentOrigin], attributes: attributes, context: nil) return CGSize(width: ceil(boundingRect.size.width), height: ceil(boundingRect.size.height)) } @objc private func tipsViewTimerDidFinish(_ timer: Timer!) { self.hideTipsView(timer.userInfo as! UIView) } private func hideTipsView(_ tipsView: UIView!) { UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseIn, .allowUserInteraction], animations: { tipsView.alpha = 0.0 }) { (finished: Bool) in tipsView.removeFromSuperview() objc_setAssociatedObject(self, &kMessageTipsViewKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let completion = objc_getAssociatedObject(tipsView, &kMessageTipsCompletionKey) as? () -> Void { completion() } } } // MARK: - TopTipMessage /// The type of the top tips view. /// /// - `default`: Default type which with a gray background color. /// - success: Success type which with a green background color. /// - info: Info type which with a blue background color. /// - warning: Warning type which with a red background color. public enum TopTipMessageType { case `default` case success case info case warning } /// Show top tips view with string and type. /// /// - Parameters: /// - message: The string to show. /// - type: The type of the top tips view. `.default` by default. public func showTopTipsMessage(_ message: String, type: TopTipMessageType = .default) { var color = UIColor() switch type { case .default: color = UIColor(r: 234.0, g: 234.0, b: 234.0, a: 0.95) case .info: color = UIColor(r: 82.0, g: 188.0, b: 255.0, a: 0.95) case .success: color = UIColor(r: 28.0, g: 255.0, b: 160.0, a: 0.95) case .warning: color = UIColor(r: 255.0, g: 84.0, b: 84.0, a: 0.95) } self.showTopTipsMessage(message, backgroundColor: color) } /// Show top tips view with string and background color. /// /// - Parameters: /// - message: The string to show. /// - color: The background color of the top tips view. public func showTopTipsMessage(_ message: String, backgroundColor color: UIColor) { guard objc_getAssociatedObject(self, &kTopTipsViewKey) == nil else { return } let topTipsView = self.topTipsView(forMessage: message, backgroundColor: color) // Can not use `self.showTopTipsView(topTipsView)` there, otherwise the string will not be display correctly under the UINavigationController. let delegate = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared.delegate)) as? UIApplicationDelegate delegate?.window??.showTopTipsView(topTipsView!) } private func topTipsView(forMessage message: String, backgroundColor color: UIColor) -> UIView? { let topTipsView = UIView() topTipsView.backgroundColor = color let messageLabel = UILabel() messageLabel.backgroundColor = UIColor.clear messageLabel.text = message messageLabel.textColor = (color.redValue < 0.8 || color.greenValue < 0.8 || color.blueValue < 0.8) ? UIColor.white : UIColor.darkGray messageLabel.numberOfLines = 0 messageLabel.lineBreakMode = .byWordWrapping messageLabel.textAlignment = .center messageLabel.tag = 10001 topTipsView.addSubview(messageLabel) return topTipsView } private func showTopTipsView(_ topTipsView: UIView) { objc_setAssociatedObject(self, &kTopTipsViewKey, topTipsView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) topTipsView.center = CGPoint(x: self.center.x, y: -kHeaderHeight / 2) self.addSubview(topTipsView) topTipsView.makeConstraints { (view) in view.top.equalTo(self.top) view.leading.equalTo(self.leading) view.trailing.equalTo(self.trailing) view.height.equalToConstant(kHeaderHeight) } let messageLabel = topTipsView.viewWithTag(10001) messageLabel?.makeConstraints { (view) in view.top.equalTo(topTipsView.top) view.leading.equalTo(topTipsView.leading) view.trailing.equalTo(topTipsView.trailing) view.bottom.equalTo(topTipsView.bottom) } UIView.animate(withDuration: 0.3, delay: 0.0, options: .transitionCurlDown, animations: { topTipsView.center = CGPoint(x: self.center.x, y: kHeaderHeight / 2) }) { (finished: Bool) in let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.topTipsViewTimerDidFinish(_:)), userInfo: topTipsView, repeats: false) objc_setAssociatedObject(topTipsView, &kTopTipsTimerKey, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc private func topTipsViewTimerDidFinish(_ timer: Timer!) { self.hideTopTipsView(timer.userInfo as! UIView) } private func hideTopTipsView(_ topTipsView: UIView!) { UIView.animate(withDuration: 0.3, delay: 0.0, options: .transitionCurlUp, animations: { topTipsView.center = CGPoint(x: self.center.x, y: -kHeaderHeight / 2) }) { (finished: Bool) in topTipsView.removeFromSuperview() objc_setAssociatedObject(self, &kTopTipsViewKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } @available(iOSApplicationExtension 9.0, *) public extension UIView { /// A shortcut of the leadingAnchor. public var leading: NSLayoutXAxisAnchor { return self.leadingAnchor } /// A shortcut of the trailingAnchor. public var trailing: NSLayoutXAxisAnchor { return self.trailingAnchor } /// A shortcut of the leftAnchor. public var left: NSLayoutXAxisAnchor { return self.leftAnchor } /// A shortcut of the rightAnchor. public var right: NSLayoutXAxisAnchor { return self.rightAnchor } /// A shortcut of the topAnchor. public var top: NSLayoutYAxisAnchor { return self.topAnchor } /// A shortcut of the bottomAnchor. public var bottom: NSLayoutYAxisAnchor { return self.bottomAnchor } /// A shortcut of the widthAnchor. public var width: NSLayoutDimension { return self.widthAnchor } /// A shortcut of the heightAnchor. public var height: NSLayoutDimension { return self.heightAnchor } /// A shortcut of the centerXAnchor. public var centerX: NSLayoutXAxisAnchor { return self.centerXAnchor } /// A shortcut of the centerYAnchor. public var centerY: NSLayoutYAxisAnchor { return self.centerYAnchor } /// A shortcut of the firstBaselintAnchor. public var firstBaseline: NSLayoutYAxisAnchor { return self.firstBaselineAnchor } /// A shortcut of the secondBaselineAnchor. public var lastBaseline: NSLayoutYAxisAnchor { return self.lastBaselineAnchor } /// Make constraints. /// /// - Parameter maker: A closure defines all constraints. public func makeConstraints(_ maker: (_ view: UIView) -> Void) { self.translatesAutoresizingMaskIntoConstraints = false maker(self) } }
mit
ff9f150609c28ba73cf4211704f4a9a0
41.463002
186
0.636445
4.808475
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
03-Single View App/Swift 3/BMI-Challenge from Section 6 Solution Swift 2/BMI/ViewController.swift
1
5171
// // ViewController.swift // BMI // // Created by Nicholas Outram on 30/12/2014. // Copyright (c) 2014 Plymouth University. All rights reserved. // // 04-11-2015 Updated for Swift 2 import UIKit class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { class func doDiv100(_ u : Int) -> Double { return Double(u) * 0.01 } class func doDiv2(_ u : Int) -> Double { return Double(u) * 0.5 } var weight : Double? var height : Double? var bmi : Double? { get { if (weight != nil) && (height != nil) { return weight! / (height! * height!) } else { return nil } } } let listOfHeightsInM = Array(140...220).map(ViewController.doDiv100) let listOfWeightsInKg = Array(80...240).map(ViewController.doDiv2) @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! @IBOutlet weak var heightPickerView: UIPickerView! @IBOutlet weak var weightPickerView: UIPickerView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() updateUI() return true } func updateUI() { if let val = self.bmi { self.bmiLabel.text = String(format: "%4.1f", val) } else { self.bmiLabel.text = "----" } } // //Called when ever the textField looses focus // func textFieldDidEndEditing(textField: UITextField) { // // //First we check if textField.text actually contains a (wrapped) String // guard let txt : String = textField.text else { // //Simply return if not // return // } // // //At this point, txt is of type String. Here is a nested function that will be used // //to parse this string, and convert it to a wrapped Double if possible. // func conv(numString : String) -> Double? { // let result : Double? = NSNumberFormatter().numberFromString(numString)?.doubleValue // return result // } // // //Which textField is being edit? // switch (textField) { // // case heightTextField: // self.height = conv(txt) // // case weightTextField: // self.weight = conv(txt) // // //default must be here to give complete coverage. A safety precaution. // default: // print("Something bad happened!") // // } //end of switch // // //Last of all, update the user interface. // updateUI() // // } // SOLUTION TO CHALLENGE func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let txt = textField.text else { return false } let conv = { NumberFormatter().number(from: $0)?.doubleValue } let newString = NSMutableString(string: txt) newString.replaceCharacters(in: range, with: string) switch (textField) { case self.weightTextField: self.weight = conv(newString as String) case self.heightTextField: self.height = conv(newString as String) default: break } //end switch updateUI() return true } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch (pickerView) { case self.heightPickerView: return listOfHeightsInM.count case self.weightPickerView: return listOfWeightsInKg.count default: return 0 } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch (pickerView) { case self.heightPickerView: return String(format: "%4.2f", listOfHeightsInM[row]) case self.weightPickerView: return String(format: "%4.1f", listOfWeightsInKg[row]) default: return "" } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch (pickerView) { case self.heightPickerView: let h : Double = self.listOfHeightsInM[row] self.height = h case self.weightPickerView: let w : Double = self.listOfWeightsInKg[row] self.weight = w default: print("Error"); } updateUI() } }
mit
3430a4a77b193d065290a2dae70514a2
26.951351
129
0.575904
4.580159
false
false
false
false
dabing1022/AlgorithmRocks
LeetCodeSwift/Playground/LeetCode.playground/Pages/070 Climbing Stairs.xcplaygroundpage/Contents.swift
1
1032
//: [Previous](@previous) /*: # [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Tags: Dynamic Programming */ class Solution { func climbStairs(n: Int) -> Int { if (n == 0) { return 0 } if (n == 1) { return 1 } var steps: [Int] = Array(count: n, repeatedValue: 0) steps[0] = 1 steps[1] = 2 for i in 2..<n { steps[i] = steps[i-1] + steps[i-2] } return steps[n-1] } } Solution().climbStairs(1) Solution().climbStairs(2) Solution().climbStairs(3) Solution().climbStairs(4) Solution().climbStairs(5) Solution().climbStairs(6) Solution().climbStairs(7) Solution().climbStairs(8) Solution().climbStairs(9) Solution().climbStairs(10) Solution().climbStairs(11) Solution().climbStairs(12) //: [Next](@next)
mit
77efc7f171caeaa85af4ee3b9f92d326
20.957447
96
0.59593
3.498305
false
false
false
false
hsienchiaolee/Anchor
Anchor/Anchor.swift
1
9861
import UIKit public extension UIView { public func anchor() -> Anchor { return Anchor(view: self) } public var top: NSLayoutAnchor<NSLayoutYAxisAnchor> { return topAnchor } public var left: NSLayoutAnchor<NSLayoutXAxisAnchor> { return leftAnchor } public var bottom: NSLayoutAnchor<NSLayoutYAxisAnchor> { return bottomAnchor } public var right: NSLayoutAnchor<NSLayoutXAxisAnchor> { return rightAnchor } public var height: NSLayoutDimension { return heightAnchor } public var width: NSLayoutDimension { return widthAnchor } public var centerX: NSLayoutXAxisAnchor { return centerXAnchor } public var centerY: NSLayoutYAxisAnchor { return centerYAnchor } } public struct Anchor { public let view: UIView public let top: NSLayoutConstraint? public let left: NSLayoutConstraint? public let bottom: NSLayoutConstraint? public let right: NSLayoutConstraint? public let height: NSLayoutConstraint? public let width: NSLayoutConstraint? public let centerX: NSLayoutConstraint? public let centerY: NSLayoutConstraint? public init(view: UIView) { self.view = view top = nil left = nil bottom = nil right = nil height = nil width = nil centerX = nil centerY = nil } private init(view: UIView, top: NSLayoutConstraint?, left: NSLayoutConstraint?, bottom: NSLayoutConstraint?, right: NSLayoutConstraint?, height: NSLayoutConstraint?, width: NSLayoutConstraint?, centerX: NSLayoutConstraint?, centerY: NSLayoutConstraint?) { self.view = view self.top = top self.left = left self.bottom = bottom self.right = right self.height = height self.width = width self.centerX = centerX self.centerY = centerY } private func update(edge: NSLayoutAttribute, constraint: NSLayoutConstraint?) -> Anchor { var top = self.top var left = self.left var bottom = self.bottom var right = self.right var height = self.height var width = self.width var centerX = self.centerX var centerY = self.centerY switch edge { case .top: top = constraint case .left: left = constraint case .bottom: bottom = constraint case .right: right = constraint case .height: height = constraint case .width: width = constraint case .centerX: centerX = constraint case .centerY: centerY = constraint default: return self } return Anchor( view: self.view, top: top, left: left, bottom: bottom, right: right, height: height, width: width, centerX: centerX, centerY: centerY) } private func insert(anchor: Anchor) -> Anchor { return Anchor( view: self.view, top: anchor.top ?? top, left: anchor.left ?? left, bottom: anchor.bottom ?? bottom, right: anchor.right ?? right, height: anchor.height ?? height, width: anchor.width ?? width, centerX: anchor.centerX ?? centerX, centerY: anchor.centerY ?? centerY) } // MARK: Anchor to superview edges public func topToSuperview(constant c: CGFloat = 0) -> Anchor { guard let superview = view.superview else { return self } return top(to: superview.top, constant: c) } public func leftToSuperview(constant c: CGFloat = 0) -> Anchor { guard let superview = view.superview else { return self } return left(to: superview.left, constant: c) } public func bottomToSuperview(constant c: CGFloat = 0) -> Anchor { guard let superview = view.superview else { return self } return bottom(to: superview.bottom, constant: c) } public func rightToSuperview(constant c: CGFloat = 0) -> Anchor { guard let superview = view.superview else { return self } return right(to: superview.right, constant: c) } public func edgesToSuperview(omitEdge e: NSLayoutAttribute = .notAnAttribute, insets: UIEdgeInsets = UIEdgeInsets.zero) -> Anchor { let superviewAnchors = topToSuperview(constant: insets.top) .leftToSuperview(constant: insets.left) .bottomToSuperview(constant: insets.bottom) .rightToSuperview(constant: insets.right) .update(edge: e, constraint: nil) return self.insert(anchor: superviewAnchors) } // MARK: Anchor to superview axises public func centerXToSuperview() -> Anchor { guard let superview = view.superview else { return self } return centerX(to: superview.centerX) } public func centerYToSuperview() -> Anchor { guard let superview = view.superview else { return self } return centerY(to: superview.centerY) } public func centerToSuperview() -> Anchor { guard let superview = view.superview else { return self } return centerX(to: superview.centerX) .centerY(to: superview.centerY) } // MARK: Anchor to public func top(to anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .top, constraint: view.top.constraint(equalTo: anchor, constant: c)) } public func left(to anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .left, constraint: view.left.constraint(equalTo: anchor, constant: c)) } public func bottom(to anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .bottom, constraint: view.bottom.constraint(equalTo: anchor, constant: c)) } public func right(to anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .right, constraint: view.right.constraint(equalTo: anchor, constant: c)) } // MARK: Anchor greaterOrEqual public func top(greaterOrEqual anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .top, constraint: view.top.constraint(greaterThanOrEqualTo: anchor, constant: c)) } public func left(greaterOrEqual anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .left, constraint: view.left.constraint(greaterThanOrEqualTo: anchor, constant: c)) } public func bottom(greaterOrEqual anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .bottom, constraint: view.bottom.constraint(greaterThanOrEqualTo: anchor, constant: c)) } public func right(greaterOrEqual anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .right, constraint: view.right.constraint(greaterThanOrEqualTo: anchor, constant: c)) } // MARK: Anchor lessOrEqual public func top(lesserOrEqual anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .top, constraint: view.top.constraint(lessThanOrEqualTo: anchor, constant: c)) } public func left(lesserOrEqual anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .left, constraint: view.left.constraint(lessThanOrEqualTo: anchor, constant: c)) } public func bottom(lesserOrEqual anchor: NSLayoutAnchor<NSLayoutYAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .bottom, constraint: view.bottom.constraint(lessThanOrEqualTo: anchor, constant: c)) } public func right(lesserOrEqual anchor: NSLayoutAnchor<NSLayoutXAxisAnchor>, constant c: CGFloat = 0) -> Anchor { return update(edge: .right, constraint: view.right.constraint(lessThanOrEqualTo: anchor, constant: c)) } // MARK: Dimension anchors public func height(constant c: CGFloat) -> Anchor { return update(edge: .height, constraint: view.height.constraint(equalToConstant: c)) } public func height(to dimension: NSLayoutDimension, multiplier m: CGFloat = 1) -> Anchor { return update(edge: .height, constraint: view.height.constraint(equalTo: dimension, multiplier: m)) } public func width(constant c: CGFloat) -> Anchor { return update(edge: .width, constraint: view.width.constraint(equalToConstant: c)) } public func width(to dimension: NSLayoutDimension, multiplier m: CGFloat = 1) -> Anchor { return update(edge: .width, constraint: view.width.constraint(equalTo: dimension, multiplier: m)) } // MARK: Axis anchors public func centerX(to axis: NSLayoutXAxisAnchor, constant c: CGFloat = 0) -> Anchor { return update(edge: .centerX, constraint: view.centerX.constraint(equalTo: axis, constant: c)) } public func centerY(to axis: NSLayoutYAxisAnchor, constant c: CGFloat = 0) -> Anchor { return update(edge: .centerY, constraint: view.centerY.constraint(equalTo: axis, constant: c)) } // MARK: Activation public func activate() -> Anchor { view.translatesAutoresizingMaskIntoConstraints = false let constraints = [top, left, bottom, right, height, width, centerX, centerY].flatMap({ $0 }) NSLayoutConstraint.activate(constraints) return self } }
mit
7e43cf2e6b7df25b175e6210aaddefa0
38.130952
135
0.642633
4.874444
false
false
false
false
cuappdev/podcast-ios
old/Podcast/EmptyStateView.swift
1
8195
// // EmptyStateView.swift // Podcast // // Created by Natasha Armbrust on 10/22/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit import SnapKit enum EmptyStateType { case pastSearch case bookmarks case search case searchItunes case feed case listeningHistory case following case followers case subscription case sharedContent // for the view controller for episodes shared with you case unimplemented case downloads var title: String { switch self { case .pastSearch: return "Search Podcasts" case .bookmarks: return "Nothing Saved for Later" case .search, .searchItunes: return "Sorry! No results found." case .feed: return "Empty Feed" case .listeningHistory: return "No Listening History" case .followers: return "No Followers" case .following: return "No Followings" case .subscription: return "No Subscriptions" case .downloads: return "No Downloads" case .sharedContent: return "No Shared Content" case .unimplemented: return "Coming Soon!" } } var explanation: String { switch self { case .pastSearch: return "Find your favorite podcast episodes, series, & friends." case .bookmarks: return "You can save podcast episodes for later here. Start looking now!" case .feed: return "Oh no! Your feed is empty. Find series and friends to get live updates!" case .listeningHistory: return "You haven’t listened to anything yet. Start listening to some now." case .subscription: return "You haven’t subscribed to any series yet. Search for some now." case .followers: return "No followers yet." case .following: return "No one followed yet." case .downloads: return "You can view your locally downloaded podcast episodes here." case .sharedContent: return "This is where you can find podcast episodes shared with you by your friends." case .unimplemented: return "We are hard at work getting this feature to you!" default: return "" } } var image: UIImage? { switch self { case .search, .searchItunes: return #imageLiteral(resourceName: "no_search_results_icon") case .pastSearch: return #imageLiteral(resourceName: "searchIcon") // case .bookmarks: // return #imageLiteral(resourceName: "bookmark_empty_state") case .listeningHistory: return #imageLiteral(resourceName: "iPodcast") case .followers, .following: return #imageLiteral(resourceName: "profile_empty_state") case .downloads: return #imageLiteral(resourceName: "download_null") case .sharedContent: return #imageLiteral(resourceName: "shared_null_state") default: return nil } } var actionItemButtonTitle: String? { switch self { case .listeningHistory, .downloads, .bookmarks: return "Discover Episodes" case .feed: return "Find Friends & Series to Follow" case .subscription: return "Search Series" case .sharedContent: return "Find Friends to Follow" case .search: return "Search the web to add more series to our collection." default: return nil } } var backgroundColor: UIColor { switch self { case .pastSearch: return .offWhite default: return .paleGrey } } } protocol EmptyStateViewDelegate: class { func didPressActionItemButton() } class EmptyStateView: UIView { let iconImageViewWidth: CGFloat = 50 let iconImageViewHeight: CGFloat = 48 let explanationLabelWidth: CGFloat = 0.7 let padding: CGFloat = 18 var iconImageView: UIImageView? var titleLabel: UILabel! var explanationLabel: UILabel! var actionItemButton: UIButton! var mainView: UIView! weak var delegate: EmptyStateViewDelegate? init(type: EmptyStateType, iconImageViewY: CGFloat = 175) { super.init(frame: .zero) backgroundColor = type.backgroundColor mainView = UIView() addSubview(mainView) if let image = type.image { iconImageView = UIImageView(image: image) mainView.addSubview(iconImageView!) iconImageView!.snp.makeConstraints { make in make.top.equalToSuperview().inset(iconImageViewY) make.centerX.equalToSuperview() make.width.lessThanOrEqualTo(iconImageViewWidth) make.height.lessThanOrEqualTo(iconImageViewHeight) } } titleLabel = UILabel() titleLabel.numberOfLines = 2 titleLabel.text = type.title titleLabel.textAlignment = .center titleLabel.textColor = .slateGrey titleLabel.font = ._16SemiboldFont() mainView.addSubview(titleLabel) explanationLabel = UILabel() explanationLabel.numberOfLines = 3 explanationLabel.textAlignment = .center explanationLabel.text = type.explanation explanationLabel.textColor = .slateGrey explanationLabel.font = ._14RegularFont() mainView.addSubview(explanationLabel) actionItemButton = UIButton() actionItemButton.setTitleColor(.sea, for: .normal) actionItemButton.backgroundColor = .clear actionItemButton.addTarget(self, action: #selector(didPressActionItemButton), for: .touchUpInside) actionItemButton.isHidden = true if let actionItemButtonTitle = type.actionItemButtonTitle { let attributedString = NSMutableAttributedString(string: actionItemButtonTitle) attributedString.addAttribute(.foregroundColor, value: UIColor.sea, range: NSRange(location: 0, length: actionItemButtonTitle.count)) if type == .search { attributedString.addAttribute(.foregroundColor, value: UIColor.slateGrey, range: NSRange(location: 15, length: 37)) } actionItemButton.setAttributedTitle(attributedString, for: .normal) actionItemButton.titleLabel?.font = ._14RegularFont() actionItemButton.titleLabel?.numberOfLines = 2 actionItemButton.titleLabel?.textAlignment = .center actionItemButton.isHidden = false } mainView.addSubview(actionItemButton) mainView.snp.makeConstraints { make in make.edges.equalToSuperview() } titleLabel.snp.makeConstraints { make in if let imageView = iconImageView { make.top.equalTo(imageView.snp.bottom).offset(padding) } else { make.top.equalToSuperview().inset(iconImageViewY) } make.leading.trailing.equalToSuperview().inset(padding).priority(999) make.centerX.equalToSuperview().priority(999) } explanationLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalTo(titleLabel.snp.bottom).offset(padding) make.width.equalTo(snp.width).multipliedBy(explanationLabelWidth) } actionItemButton.snp.makeConstraints { make in make.top.equalTo(explanationLabel.snp.bottom).offset(padding) make.width.equalTo(snp.width).multipliedBy(explanationLabelWidth) make.centerX.equalToSuperview() } } @objc func didPressActionItemButton() { delegate?.didPressActionItemButton() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
d94b919a725a575ed04ac768479539ae
34
145
0.616972
5.287282
false
false
false
false
QuanXu/SwiftSimpleFramwork
SwiftDemo/Base/BaseViewController.swift
3
4095
// // BaseViewController.swift // SwiftDemo // // Created by zhoutong on 16/11/11. // Copyright © 2016年 zhoutong. All rights reserved. // import UIKit open class BaseViewController: UIViewController { override open func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.edgesForExtendedLayout = .init(rawValue: 0) self.view.addSubview(HUDView) setLeftButton() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) layoutPageSubViews() } //MARK:-----属性----- lazy var HUDView: UIActivityIndicatorView = { let HUDView = UIActivityIndicatorView(activityIndicatorStyle: .gray) let centerOffset = CGPoint(x: self.view.center.x, y: self.view.center.y-50) HUDView.center = centerOffset return HUDView }() } //布局 extension BaseViewController{ func layoutPageSubViews(){ } } //nav bar 按钮 extension BaseViewController{ //右边按钮 纯文字 func setRightButton(title:String){ let btn=UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 30)) btn.setTitle(title, for: UIControlState.normal) btn.setTitleColor(UIColor.black, for: UIControlState.normal) btn.setTitleColor(UIColor.lightGray, for: UIControlState.highlighted) btn.addTarget(self, action: #selector(rightButtonAction), for: UIControlEvents.touchUpInside) let item=UIBarButtonItem(customView: btn) self.navigationItem.rightBarButtonItem=item } //右边按钮 图片 func setRightButton(imgName:String){ let img=UIImage(named: imgName) let item=UIBarButtonItem(image: img, style: UIBarButtonItemStyle.plain, target: self, action: #selector(rightButtonAction)) item.tintColor = UIColor.white self.navigationItem.rightBarButtonItem=item } func rightButtonAction() { DLog(message: "right button") } //设置返回按钮 func setLeftButton(){ //判断如果不是根视图 if((self.navigationController?.childViewControllers.count)! > 1){ let leftBarBtn = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(leftButtonAction)) leftBarBtn.image = UIImage(named: "button_back") leftBarBtn.tintColor = UIColor.white //用于消除左边空隙,要不然按钮顶不到最前面 let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) spacer.width = -5; self.navigationItem.leftBarButtonItems = [spacer, leftBarBtn] } } func leftButtonAction(){ _ = self.navigationController?.popViewController(animated: true) } } //简单的alert extension BaseViewController{ func alert(title:String,msg:String){ let alertVC = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert) // alertVC.addTextField { (tField:UITextField!) -> Void in // tField.placeholder = "Account" // } // let acOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (alertAction:UIAlertAction!) -> Void in // } let acCancel = UIAlertAction(title: "确定", style: UIAlertActionStyle.cancel) { (alertAction:UIAlertAction!) -> Void in } // acOK.isEnabled = false // alertVC.addAction(acOK) alertVC.addAction(acCancel) //因为UIAlertController是控制器,所以我们现在得改用控制器弹出 self.present(alertVC, animated: true, completion: nil) } } //网络加载 菊花 extension BaseViewController{ func initLoadingView() { HUDView.startAnimating() } func removeLoadingView() { HUDView.stopAnimating() } }
mit
2c05bc256ad2e6099197ebdb813cc498
32.504274
132
0.640561
4.622642
false
false
false
false
TalkingBibles/Talking-Bible-iOS
TalkingBibleTests/TalkingBibleTests.swift
1
3044
// // TalkingBibleTests.swift // TalkingBibleTests // // Created by Clay Smith on 10/30/14. // Copyright (c) 2014 Talking Bibles International. All rights reserved. // import UIKit import XCTest import Foundation class TalkingBibleTests: XCTestCase { var app: UIApplication! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. app = UIApplication.sharedApplication() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // func testCanOpenURL() { // XCTAssert(app.canOpenURL(NSURL(string: "talkingbible://eng/01_matthew/1")!), "Can open talkingbible:// url scheme") // } // func testBookmarkLanguage() { // let bookmark = Bookmark(languageId: "eng", bookId: nil, chapterId: nil) // XCTAssertNotNil(bookmark.languageId, "Language was bookmarked") // } // // func testBookmarkInvalidLanguage() { // let bookmark = Bookmark(languageId: "xxx", bookId: nil, chapterId: nil) // XCTAssertNil(bookmark.languageId, "Invalid language was not bookmarked") // } // // func testBookmarkBook() { // let bookmark = Bookmark(languageId: "eng", bookId: "01_matthew", chapterId: nil) // XCTAssertNotNil(bookmark.bookId, "Book was bookmarked") // } // // func testBookmarkInvalidBook() { // let bookmark = Bookmark(languageId: "eng", bookId: "xxx", chapterId: nil) // XCTAssertNotNil(bookmark.languageId, "Language was bookmarked") // XCTAssertNil(bookmark.bookId, "Invalid book was not bookmarked") // } // // func testBookmarkChapter() { // let bookmark = Bookmark(languageId: "eng", bookId: "01_matthew", chapterId: 1) // XCTAssertNotNil(bookmark.chapterId, "Chapter was bookmarked") // } // // func testBookmarkInvalidChapter() { // let bookmark = Bookmark(languageId: "eng", bookId: "01_matthew", chapterId: 999) // XCTAssertNotNil(bookmark.languageId, "Language was bookmarked") // XCTAssertNotNil(bookmark.bookId, "Book was bookmarked") // XCTAssertNil(bookmark.chapterId, "Invalid chapter was not bookmarked") // } // // func testBookmarkFromPath() { // let bookmark = Bookmark(path: "eng/01_matthew/1") // XCTAssertNotNil(bookmark.languageId, "Language was bookmarked") // XCTAssertNotNil(bookmark.bookId, "Book was bookmarked") // XCTAssertNotNil(bookmark.chapterId, "Chapter was bookmarked") // } // func testExample() { // // This is an example of a functional test case. // XCTAssert(true, "Pass") // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock() { // // Put the code you want to measure the time of here. // } // } }
apache-2.0
b96bd9b5e2a258e438b23324a31c3b62
35.238095
125
0.635677
4.026455
false
true
false
false
qualaroo/QualarooSDKiOS
QualarooTests/Network/SimpleRequestSchedulerSpec.swift
1
1446
// // SimpleRequestSchedulerSpec.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class SimpleRequestSchedulerSpec: QuickSpec { override func spec() { super.spec() describe("SimpleRequestScheduler") { var scheduler: SimpleRequestScheduler! beforeEach { scheduler = SimpleRequestScheduler(reachability: nil, storage: PersistentMemory()) scheduler.removeObservers() } context("SimpleRequestProtocol") { it("schedule request when asked") { scheduler.privateQueue.isSuspended = true scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false } expect(operations).to(haveCount(1)) } it("schedule two request when asked") { scheduler.privateQueue.isSuspended = true scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false } expect(operations).to(haveCount(2)) } } } } }
mit
1bc5a634099d6ffc6bf443e3dd867518
32.627907
95
0.670816
4.532915
false
false
false
false
cailingyun2010/swift-weibo
微博-S/Classes/Main/MainViewController.swift
1
6280
// // MainViewController.swift // DSWeibo // // Created by xiaomage on 15/9/7. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit /* command + j -> 定位到目录结构 ⬆️⬇️键选择文件夹 按回车 -> command + c 拷贝文件名称 command + n 创建文件 */ class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // 设置当前控制器对应tabBar的颜色 // 注意: 在iOS7以前如果设置了tintColor只有文字会变, 而图片不会变 tabBar.tintColor = UIColor.orangeColor() // 添加子控制器 addChildViewControllers() // 从iOS7开始就不推荐大家在viewDidLoad中设置frame // print(tabBar.subviews) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // print("-----------") // print(tabBar.subviews) // 添加加号按钮 setupComposeBtn() } /** 监听加号按钮点击 注意: 监听按钮点击的方法不能是私有方法 按钮点击事件的调用是由 运行循环 监听并且以消息机制传递的,因此,按钮监听函数不能设置为 private */ func composeBtnClick(){ print(__FUNCTION__) } // MARK: - 内部控制方法 private func setupComposeBtn() { // 1.添加加号按钮 tabBar.addSubview(composeBtn) // 2.调整加号按钮的位置 let width = UIScreen.mainScreen().bounds.size.width / CGFloat(viewControllers!.count) let rect = CGRect(x: 0, y: 0, width: width, height: 49) // composeBtn.frame = rect // 第一个参数:是frame的大小 // 第二个参数:是x方向偏移的大小 // 第三个参数: 是y方向偏移的大小 composeBtn.frame = CGRectOffset(rect, 2 * width, 0) } /** 添加所有子控制器 */ private func addChildViewControllers() { // 1.获取json文件的路径 let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) // 2.通过文件路径创建NSData if let jsonPath = path{ let jsonData = NSData(contentsOfFile: jsonPath) do{ // 有可能发生异常的代码放到这里 // 3.序列化json数据 --> Array // try : 发生异常会跳到catch中继续执行 // try! : 发生异常程序直接崩溃 let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) // 4.遍历数组, 动态创建控制器和设置数据 // 在Swift中, 如果需要遍历一个数组, 必须明确数据的类型 for dict in dictArr as! [[String: String]] { // 报错的原因是因为addChildViewController参数必须有值, 但是字典的返回值是可选类型 addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } }catch { // 发生异常之后会执行的代码 print(error) // 从本地创建控制器 addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") // 再添加一个占位控制器 addChildViewController("NullViewController", title: "", imageName: "") addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover") addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile") } } } /** 初始化子控制器 :param: childController 需要初始化的子控制器 :param: title 子控制器的标题 :param: imageName 子控制器的图片 */ private func addChildViewController(childControllerName: String, title:String, imageName:String) { // -1.动态获取命名空间 let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String // 0 .将字符串转换为类 // 0.1默认情况下命名空间就是项目的名称, 但是命名空间名称是可以修改的 let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName) // 0.2通过类创建对象 // 0.2.1将AnyClass转换为指定的类型 let vcCls = cls as! UIViewController.Type // 0.2.2通过class创建对象 let vc = vcCls.init() // 1设置首页对应的数据 vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") vc.title = title // 2.给首页包装一个导航控制器 let nav = UINavigationController() nav.addChildViewController(vc) // 3.将导航控制器添加到当前控制器上 addChildViewController(nav) } // MARK: - 懒加载 private lazy var composeBtn:UIButton = { let btn = UIButton() // 2.设置前景图片 btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) // 3.设置背景图片 btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) // 4.添加监听 btn.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return btn }() }
apache-2.0
2ea4a07c9eea4b01e638f1cbc37bc3b1
31.54375
132
0.572883
4.531767
false
false
false
false
NJUiosproject/AnyWay
AnyWay/AnyWay/ViewController.swift
1
3776
// // ViewController.swift // AnyWay // // Created by XiaoPeng on 16/4/12. // Copyright © 2016年 XiaoPeng. All rights reserved. // import UIKit class ViewController: UIViewController,UISearchBarDelegate { @IBOutlet weak var initdeskimage: UIImageView! override func viewDidLoad() { super.viewDidLoad() addimage() /*let bundle = NSBundle.mainBundle() let imageTrashFullPath = bundle.pathForResource("con", ofType: "jpg") self.imageTrashFull = UIImage(contentsOfFile: imageTrashFullPath!) initdeskimage.userInteractionEnabled = true initdeskimage.center = self.initdeskimage.image = self.imageTrashFull */ // Do any additional setup after loading the view, typically from a nib. } @IBOutlet var mypinch: UIPinchGestureRecognizer! var imageTrashFull : UIImage! var currentScale : CGFloat = 1.0 func addimage() { // 初始化uiimageview and uiimage //设置加载一张本地图片 //把加载好的图片丢给imageview中的image显示 let image = UIImage(named:"1.jpg") initdeskimage.userInteractionEnabled = true initdeskimage.image = image //let bundle = NSBundle.mainBundle() //let imageTrashFullPath = bundle.pathForResource("con", ofType: "jpg") //self.imageTrashFull = UIImage(contentsOfFile: imageTrashFullPath!) //self.initdeskimage.image = self.imageTrashFull //let recongnizer = UITapGestureRecognizer(target: self, action: Selector("foundtap")) // tapGestureRecognizer.numberOfTapsRequired = 2 //initdeskimage.userInteractionEnabled = true //self.initdeskimage.addGestureRecognizer(recongnizer) //把uiimageview加载到父控件上,也就是self.view //self.view.addSubview(uimageview) } @IBAction func foundpinch(sender: AnyObject) { let paramSender = sender as! UIPinchGestureRecognizer if paramSender.state == .Ended { currentScale = paramSender.scale }else if paramSender.state == .Began && currentScale != 0.0 { paramSender.scale = currentScale } self.initdeskimage.transform = CGAffineTransformMakeScale(paramSender.scale, paramSender.scale) } /* func pinch(gestureRecognizer: UIPinchGestureRecognizer) { if gestureRecognizer.state == UIGestureRecognizerState.Began || gestureRecognizer.state == UIGestureRecognizerState.Changed { initdeskimage.transform = CGAffineTransformScale(initdeskimage.transform, gestureRecognizer.scale, gestureRecognizer.scale) gestureRecognizer.scale = 1 } } func rotate(gestureRecognizer: UIRotationGestureRecognizer) { if gestureRecognizer.state == UIGestureRecognizerState.Began || gestureRecognizer.state == UIGestureRecognizerState.Changed { initdeskimage.transform = CGAffineTransformRotate(initdeskimage.transform, gestureRecognizer.rotation) gestureRecognizer.rotation = 0 } }*/ func foundtap(paramSender: UIPinchGestureRecognizer) { if paramSender.state == .Ended { currentScale = paramSender.scale }else if paramSender.state == .Began && currentScale != 0.0 { paramSender.scale = currentScale } self.initdeskimage.transform = CGAffineTransformMakeScale(paramSender.scale, paramSender.scale) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5f3c9bbcb272cb2ed521c32891b803d9
35.97
135
0.654314
5.170629
false
false
false
false
mwolicki/swift-game
Space Battle/DrawGame.swift
1
8026
// // GamieLogic.swift // Space Battle // // Created by Marcin Wolicki on 18/03/2016. // Copyright © 2016 Marcin Wolicki. All rights reserved. // import UIKit import SpriteKit enum Asteroid : String{ case A = "asteroid0" case B = "asteroid1" case C = "asteroid2" case D = "asteroid3" } enum GameObject : UInt32{ case Laser = 0x01 case Asteroid = 0x02 case Spaceship = 0x4 } func startGame(scene:SKScene){ drawGameOnStart(scene) Signal.frame(5).subscribe(newAsteroid) |> ignore Signal.didBeginContact.subscribe(onContact) |> ignore GameLogic.onPointsUpdated.subscribe({ points in drawPoints(points, scene: scene) }) |> ignore GameLogic.onFire.subscribe { onFire(scene) } |> ignore GameLogic.onRestartGame.subscribe { onRestart(scene) } |> ignore GameLogic.onDirectionChanged.subscribe { onDirectionChanged($0, scene: scene) } |> ignore } func drawGameOnStart(scene:SKScene){ drawBackground(scene) drawSpaceship(scene) drawPoints(0, scene: scene) } func newAsteroid(scene:SKScene){ let setAsteroid = { x, type, scale in drawAsteroid(scene, position: CGPointMake(x, scene.size.height), type: type, scale: scale) } if arc4random_uniform(50) > 48{ let pos = CGFloat(arc4random_uniform(UInt32(scene.size.width))) let objPos = Int32(arc4random_uniform(4)) if let obj = Asteroid(rawValue: "asteroid\(objPos)"){ let scale = (Double(arc4random_uniform(95))+5.0)/100.0 setAsteroid(pos, obj, CGFloat(scale)) } } } func onContact (scene:SKScene, contact:SKPhysicsContact){ if(contact.bodyA.categoryBitMask != contact.bodyB.categoryBitMask){ if let bodyA = GameObject(rawValue: contact.bodyA.categoryBitMask) { if bodyA == .Spaceship { gameOver(scene) } } if let node = contact.bodyA.node{ node.removeFromParent() GameEvent.onHitAsteroid.set(10) } if let node = contact.bodyB.node{ node.removeFromParent() GameEvent.onHitAsteroid.set(10) } } } func gameOver(scene:SKScene){ let gameover = SKLabelNode(fontNamed: "Chalkduster") gameover.text = "Game Over" gameover.fontSize = 50 gameover.fontColor = SKColor.blueColor() gameover.position = CGPointMake(scene.size.width/2, scene.size.height/2) gameover.zPosition = 1 scene.addChild(gameover) GameEvent.onGameOver.set(()) } func drawBackground(scene:SKScene){ let background = SKSpriteNode(imageNamed: "background") background.size = scene.size background.position = CGPointMake(scene.size.width/2, scene.size.height/2) background.zPosition = -1 scene.addChild(background) } func drawPoints(currentPoints: Int, scene:SKScene){ if let points : SKLabelNode = scene.childNodeWithName("points") as! SKLabelNode?{ points.removeFromParent() } let points = SKLabelNode(fontNamed: "Chalkduster") points.name = "points" points.text = "score: \(currentPoints)" points.fontSize = 25 points.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right points.fontColor = SKColor.yellowColor() points.position = CGPointMake(scene.size.width-10, scene.size.height-20) points.zPosition = 1 scene.addChild(points) } func drawAsteroid(scene:SKScene, position:CGPoint, type:Asteroid, scale:CGFloat){ let asteroid = SKSpriteNode(imageNamed: type.rawValue) asteroid.position = position asteroid.xScale = scale asteroid.yScale = scale let physicsBody = PhysicsBody.basedOnTexture(asteroid.texture!, size: asteroid.size) |> PhysicsBody.setCategoryBitMask (GameObject.Asteroid.rawValue | GameObject.Spaceship.rawValue) |> PhysicsBody.setContactTestBitMask (GameObject.Laser.rawValue) asteroid.physicsBody = physicsBody let angel = CGFloat(arc4random_uniform(12) + 1) - 6 let duration = Double(arc4random_uniform(20) + 1) let speed = Double(arc4random_uniform(25) + 5) asteroid.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(angel, duration:duration))) let moveAction = SKAction.moveToY (-asteroid.size.height*4, duration: speed) asteroid.runAction(moveAction, completion: { asteroid.removeFromParent() }) scene.addChild(asteroid) } class PhysicsBody { static func basedOnTexture (texture:SKTexture, size:CGSize) -> SKPhysicsBody{ return SKPhysicsBody(texture: texture, size: size) |> setupDefaults } private static func setCategoryBitMask (categoryBitMask : UInt32) (pb:SKPhysicsBody) -> SKPhysicsBody{ pb.categoryBitMask = categoryBitMask return pb } private static func setContactTestBitMask (contactTestBitMask : UInt32) (pb:SKPhysicsBody) -> SKPhysicsBody{ pb.contactTestBitMask = contactTestBitMask return pb } private static func setupDefaults (pb:SKPhysicsBody) -> SKPhysicsBody{ pb.dynamic = true pb.affectedByGravity = false pb.collisionBitMask = 0 return pb } } func drawSpaceship(scene:SKScene){ let spaceship = SKSpriteNode(imageNamed:"Spaceship") spaceship.name = "spaceship" spaceship.xScale = 0.25 spaceship.yScale = 0.25 spaceship.position = CGPointMake(scene.size.width/2, spaceship.size.height) spaceship.zPosition = 1 let physicsBody = SKPhysicsBody(texture: spaceship.texture!, size: spaceship.size) physicsBody.dynamic = true physicsBody.affectedByGravity = false physicsBody.collisionBitMask = 0 physicsBody.categoryBitMask = GameObject.Spaceship.rawValue physicsBody.contactTestBitMask = GameObject.Asteroid.rawValue spaceship.physicsBody = physicsBody scene.addChild(spaceship) } func getSpaceshipSpeed(direction : Direction, scene:SKScene, spaceship: SKSpriteNode) -> (CGFloat, Double){ switch direction{ case .Left (let speed): return (spaceship.size.width/2, speed) case .Right (let speed): return (scene.size.width - spaceship.size.width/2, speed) default: return (0,0) } } func moveSpaceship (direction : Direction, scene:SKScene, spaceship: SKSpriteNode){ spaceship.removeActionForKey("moveSpaceship") if direction != .None { let (pos, speedFactor) = getSpaceshipSpeed(direction, scene:scene, spaceship: spaceship) let speed = Double(10 * abs(pos - spaceship.position.x)/scene.size.width) let action = SKAction.moveToX (pos, duration: speed*min(0.2, speedFactor / 1.5)) spaceship.runAction (action, withKey: "moveSpaceship") } } func fire(scene:SKScene, position:CGPoint){ let laser = SKShapeNode(rectOfSize: CGSize(width: 3, height: 15)) laser.fillColor = SKColor.yellowColor() laser.position = position let moveAction = SKAction.moveToY (scene.size.height + 15, duration: 1.5) laser.runAction(moveAction, completion: { laser.removeFromParent() }) let physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 3, height: 15)) physicsBody.dynamic = true physicsBody.affectedByGravity = false physicsBody.collisionBitMask = 0 physicsBody.categoryBitMask = GameObject.Laser.rawValue physicsBody.contactTestBitMask = GameObject.Asteroid.rawValue laser.physicsBody = physicsBody scene.addChild(laser) } func onFire(scene:SKScene){ if let spaceship : SKSpriteNode = scene.childNodeWithName("spaceship") as! SKSpriteNode?{ fire(scene, position: spaceship.position) } } func onDirectionChanged(direction:Direction, scene:SKScene){ if let spaceship : SKSpriteNode = scene.childNodeWithName("spaceship") as! SKSpriteNode?{ moveSpaceship(direction, scene: scene, spaceship: spaceship) } } func onRestart(scene:SKScene){ scene.removeAllChildren() drawGameOnStart(scene) }
mit
a6fdd96a6e2761790a7988b354ad7d8d
31.358871
112
0.6881
4.115385
false
false
false
false
fredyshox/SlidingSideView
SlidingSideViewDemo/AnchorTableViewController.swift
1
1641
// // AnchorTableViewController.swift // SlidingSideView // // Created by Kacper Raczy on 26.07.2017. // Copyright © 2017 Kacper Raczy. All rights reserved. // import UIKit class AnchorTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "Choose side" } var anchorDict: [String: SlidingSideViewAnchor] = [ "Bottom": .bottom, "Top": .top, "Left": .left, "Right":.right ] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return anchorDict.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = Array(anchorDict.keys)[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showDemo", sender: indexPath.row) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case "showDemo": if let vc = segue.destination as? DemoViewController { if let index = sender as? Int { vc.slidingDetailAnchor = Array(anchorDict.values)[index] vc.title = Array(anchorDict.keys)[index] } } default: break } } } }
mit
ff036025332c2e4d227ae3931be4aa4a
26.79661
109
0.587805
4.880952
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
2
20361
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. /// You can use the enum of option item with value to control some behaviors of Kingfisher. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] extension Array where Element == KingfisherOptionsInfoItem { static let empty: KingfisherOptionsInfo = [] } /// Represents the available option items could be used in `KingfisherOptionsInfo`. public enum KingfisherOptionsInfoItem { /// Kingfisher will use the associated `ImageCache` object when handling related operations, /// including trying to retrieve the cached images and store the downloaded image to it. case targetCache(ImageCache) /// The `ImageCache` for storing and retrieving original images. If `originalCache` is /// contained in the options, it will be preferred for storing and retrieving original images. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. /// /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is /// applied in the option, the original image will be stored to this `originalCache`. At the /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, /// Kingfisher will try to search the original image to check whether it is already there. If found, /// it will be used and applied with the given processor. It is an optimization for not downloading /// the same image for multiple times. case originalCache(ImageCache) /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. case downloader(ImageDownloader) /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `.forceRefresh` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. case downloadPriority(Float) /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory /// cache, then it will ignore the disk cache but download the image again from network. This is useful when /// you want to display a changeable image behind the same url at the same app session, while avoiding download /// it for multiple times. case fromMemoryCacheOrRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `.transition` option for more. case forceTransition /// If set, Kingfisher will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. case waitForCache /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is /// not in cache, the image retrieving will fail with an error. case onlyFromCache /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen /// rendering to extract pixel information in background. This can speed up display, but will cost more time to /// prepare the image for using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks. @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") case callbackDispatchQueue(DispatchQueue?) /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. /// /// - Note: /// This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue. case callbackQueue(CallbackQueue) /// The associated value will be used as the scale factor when converting retrieved data to an image. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. /// /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, /// which uses more memory but only decode image frames once. case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the image download request. You can modify the request for some /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. /// The original request will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirect. You can modify the request for /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url /// mapping. /// The original redirection request will be sent without any modification by default. case redirectHandler(ImageDownloadRedirectHandler) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. /// If not set, the `DefaultImageProcessor.default` will be used. case processor(ImageProcessor) /// Supplies a `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// If not set, the `DefaultCacheSerializer.default` will be used. case cacheSerializer(CacheSerializer) /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being /// fetched from a cache, the modifier will run after the `CacheSerializer`. /// /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from an animated image file as a single image. /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. /// /// This option will be ignored if the target image is not animated image data. case onlyLoadFirstFrame /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original /// images if necessary. /// /// The original image will be only cached to disk storage. case cacheOriginalImage /// If set and a downloading error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. case onFailureImage(KFCrossPlatformImage?) /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage /// aggressively. By default this is not contained in the options, that means if the requested image is already /// in disk cache, Kingfisher will not try to load it to memory. case alsoPrefetchToMemory /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already /// has an image set. /// /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. case loadDiskFileSynchronously /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case memoryCacheExpiration(StorageExpiration) /// The expiration extending setting for memory cache. The item expiration time will be incremented by this /// value after access. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending /// value: .cacheTime. /// /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. case memoryCacheAccessExtendingExpiration(ExpirationExtending) /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case diskCacheExpiration(StorageExpiration) /// The expiration extending setting for disk cache. The item expiration time will be incremented by this value after access. /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. /// To disable extending option at all add diskCacheAccessExtendingExpiration(.none) to options. case diskCacheAccessExtendingExpiration(ExpirationExtending) /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of /// blocking the UI, especially if the processor needs a lot of time to run). case processingQueue(CallbackQueue) /// Enable progressive image loading, Kingfisher will use the `ImageProgressive` of case progressiveJPEG(ImageProgressive) } // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. // So we can prevent the iterating over the options array again and again. /// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member /// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be /// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. public struct KingfisherParsedOptionsInfo { public var targetCache: ImageCache? = nil public var originalCache: ImageCache? = nil public var downloader: ImageDownloader? = nil public var transition: ImageTransition = .none public var downloadPriority: Float = URLSessionTask.defaultPriority public var forceRefresh = false public var fromMemoryCacheOrRefresh = false public var forceTransition = false public var cacheMemoryOnly = false public var waitForCache = false public var onlyFromCache = false public var backgroundDecode = false public var preloadAllAnimationData = false public var callbackQueue: CallbackQueue = .mainCurrentOrAsync public var scaleFactor: CGFloat = 1.0 public var requestModifier: ImageDownloadRequestModifier? = nil public var redirectHandler: ImageDownloadRedirectHandler? = nil public var processor: ImageProcessor = DefaultImageProcessor.default public var imageModifier: ImageModifier? = nil public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default public var keepCurrentImageWhileLoading = false public var onlyLoadFirstFrame = false public var cacheOriginalImage = false public var onFailureImage: Optional<KFCrossPlatformImage?> = .none public var alsoPrefetchToMemory = false public var loadDiskFileSynchronously = false public var memoryCacheExpiration: StorageExpiration? = nil public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime public var diskCacheExpiration: StorageExpiration? = nil public var diskCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime public var processingQueue: CallbackQueue? = nil public var progressiveJPEG: ImageProgressive? = nil var onDataReceived: [DataReceivingSideEffect]? = nil public init(_ info: KingfisherOptionsInfo?) { guard let info = info else { return } for option in info { switch option { case .targetCache(let value): targetCache = value case .originalCache(let value): originalCache = value case .downloader(let value): downloader = value case .transition(let value): transition = value case .downloadPriority(let value): downloadPriority = value case .forceRefresh: forceRefresh = true case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true case .forceTransition: forceTransition = true case .cacheMemoryOnly: cacheMemoryOnly = true case .waitForCache: waitForCache = true case .onlyFromCache: onlyFromCache = true case .backgroundDecode: backgroundDecode = true case .preloadAllAnimationData: preloadAllAnimationData = true case .callbackQueue(let value): callbackQueue = value case .scaleFactor(let value): scaleFactor = value case .requestModifier(let value): requestModifier = value case .redirectHandler(let value): redirectHandler = value case .processor(let value): processor = value case .imageModifier(let value): imageModifier = value case .cacheSerializer(let value): cacheSerializer = value case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true case .onlyLoadFirstFrame: onlyLoadFirstFrame = true case .cacheOriginalImage: cacheOriginalImage = true case .onFailureImage(let value): onFailureImage = .some(value) case .alsoPrefetchToMemory: alsoPrefetchToMemory = true case .loadDiskFileSynchronously: loadDiskFileSynchronously = true case .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration case .diskCacheAccessExtendingExpiration(let expirationExtending): diskCacheAccessExtendingExpiration = expirationExtending case .processingQueue(let queue): processingQueue = queue case .progressiveJPEG(let value): progressiveJPEG = value } } if originalCache == nil { originalCache = targetCache } } } extension KingfisherParsedOptionsInfo { var imageCreatingOptions: ImageCreatingOptions { return ImageCreatingOptions( scale: scaleFactor, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyLoadFirstFrame) } } protocol DataReceivingSideEffect: AnyObject { var onShouldApply: () -> Bool { get set } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) } class ImageLoadingProgressSideEffect: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } let block: DownloadProgressBlock init(_ block: @escaping DownloadProgressBlock) { self.block = block } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { guard onShouldApply() else { return } guard let expectedContentLength = task.task.response?.expectedContentLength, expectedContentLength != -1 else { return } let dataLength = Int64(task.mutableData.count) DispatchQueue.main.async { self.block(dataLength, expectedContentLength) } } }
mit
900ab554d1ac3068064ebd9bfd213f66
55.558333
139
0.729237
5.410842
false
false
false
false
imod/MyAwesomeChecklist
MyAwesomeChecklist/MyViewController.swift
1
2339
// // MyViewController.swift // MyAwesomeChecklist // // Created by Dominik on 08/06/14. // Copyright (c) 2014 Dominik. All rights reserved. // import UIKit class MyViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView! var textField: UITextField! var tableViewData = ["My Text 1","MyText 2"] init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() // Set up table view self.tableView = UITableView(frame: CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height-100), style: UITableViewStyle.Plain) //self.tableView.registerClass(UITableViewCell.self, forHeaderFooterViewReuseIdentifier: "myCell") self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell") self.tableView.delegate = self self.tableView.dataSource = self self.view.addSubview(self.tableView) // Set up text field self.textField = UITextField(frame: CGRectMake(0, 0, self.view.bounds.size.width, 100)) self.textField.backgroundColor = UIColor.redColor() self.textField.delegate = self self.view.addSubview(self.textField) } // TableViewDatasoruce func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ return tableViewData.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ let myNewCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell myNewCell.text = self.tableViewData[indexPath.row] return myNewCell } // TextFieldDelegate func textFieldShouldReturn(textField: UITextField!) -> Bool { tableViewData.append(textField.text) textField.text = "" self.tableView.reloadData() textField.resignFirstResponder() return true } }
mit
6a44420f0af07ee72d491219b112658c
30.608108
157
0.660111
5.315909
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
Liferay-Screens/Source/DDL/Model/DDLFieldStringWithOptions.swift
1
4438
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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. */ import Foundation public class DDLFieldStringWithOptions : DDLField { public class Option { public var label:String public var name:String public var value:String public init(label:String, name:String, value:String) { self.label = label self.name = name self.value = value } } //FIXME: Multiple selection not supported yet private(set) var multiple:Bool private(set) var options:[Option] = [] override public init(attributes: [String:AnyObject], locale: NSLocale) { multiple = Bool.from(any: attributes["multiple"] ?? "false") if let optionsArray = (attributes["options"] ?? nil) as? [[String:AnyObject]] { for optionDict in optionsArray { let label = (optionDict["label"] ?? "") as! String let name = (optionDict["name"] ?? "") as! String let value = (optionDict["value"] ?? "") as! String let option = Option(label:label, name:name, value:value) self.options.append(option) } } super.init(attributes: attributes, locale: locale) } //MARK: DDLField override internal func convert(fromCurrentValue value: AnyObject?) -> String? { var result:String = "[" if let currentOptions = value as? [Option] { var first = true for option in currentOptions { if first { first = false } else { result += ", " } result += "\"\(option.value)\"" } } return result + "]" } override internal func convert(fromString value:String?) -> AnyObject? { var result:[Option] = [] func findOptionByValue(value:String) -> Option? { return options.filter { $0.value == value }.first } func findOptionByLabel(label:String) -> Option? { return options.filter { $0.label == label }.first } func extractFirstOption(options:String) -> String? { func removeFirstAndLastChars(value:String) -> String { var result: String = value if count(value) >= 2 { let range = Range<String.Index>( start: value.startIndex.successor(), end: value.endIndex.predecessor()) result = value.substringWithRange(range) } return result } let optionsArray = removeFirstAndLastChars(options).componentsSeparatedByString(",") var result:String? if let firstOptionValue = optionsArray.first { result = firstOptionValue.hasPrefix("\"") ? removeFirstAndLastChars(firstOptionValue) : firstOptionValue } return result } var firstOption:String? if let valueString = value { if valueString.hasPrefix("[") { firstOption = extractFirstOption(valueString) } else { firstOption = valueString } } if let firstOptionValue = firstOption { if let foundOption = findOptionByLabel(firstOptionValue) { result = [foundOption] } else if let foundOption = findOptionByValue(firstOptionValue) { result = [foundOption] } } return result } override func convert(fromLabel label: String?) -> AnyObject? { func findOptionByLabel(label:String) -> Option? { return options.filter { $0.label == label }.first } var result: [Option] = [] if label != nil { let foundOption = findOptionByLabel(label!) if let foundOptionValue = foundOption { result.append(foundOptionValue) } } return result } override func convertToLabel(fromCurrentValue value: AnyObject?) -> String? { var result = "" if let currentOptions = currentValue as? [Option] { if let firstOption = currentOptions.first { result = firstOption.label } } return result } override internal func doValidate() -> Bool { let current = (currentValue as! [Option]?) ?? [] return !(required && current.count == 0) } override internal func onChangedCurrentValue() { if !(currentValue is [Option]) { if let currentValueAsString = currentValue as? String { currentValue = convert(fromString: currentValueAsString) } } } }
gpl-3.0
a18fbaf86c128dcf130ef53345a73150
22.860215
87
0.680036
3.701418
false
false
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Settings/AASettingsPrivacyViewController.swift
1
1271
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit open class AASettingsPrivacyViewController: AAContentTableController { fileprivate var sessionsCell: AAManagedArrayRows<ARApiAuthSession, AACommonCell>? public init() { super.init(style: AAContentTableStyle.settingsGrouped) navigationItem.title = AALocalized("PrivacyTitle") content = ACAllEvents_Settings.privacy() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func tableDidLoad() { _ = section { (s) -> () in s.headerText = AALocalized("PrivacyHeader") // Settings: Last seen _ = s.navigate(AALocalized("PrivacyLastSeen"), controller: AASettingsLastSeenController.self) s.footerText = AALocalized("PrivacyLastSeenHint") } _ = section { (s) -> () in s.headerText = AALocalized("PrivacySecurityHeader") // Settings: All sessions _ = s.navigate("PrivacyAllSessions", controller: AASettingsSessionsController.self) } } }
agpl-3.0
c262113e0a22f5e87d111b0857a179c1
27.886364
104
0.585366
5.063745
false
false
false
false
CodeReaper/Waffle
Waffle/Classes/Waffle.swift
1
1344
import Foundation enum WaffleError: Error { case notFound, multipleFound } open class Waffle { open class Builder { private var items:[Any] public init(items:[Any] = []) { self.items = items } @discardableResult public func add(_ item:Any) -> Builder { items.append(item) return self } @discardableResult public func replace(_ item:Any) -> Builder { let type = type(of: item) let index = items.index(where: { type(of: $0) == type }) if let index = index { items.remove(at: index) } items.append(item) return self } public func build() -> Waffle { return Waffle(items: items) } } private let items:[Any] private init(items:[Any]) { self.items = items } public func get<T>(_ type: T.Type) throws -> T { let resolved = items.filter { $0 is T } guard resolved.count > 0 else { throw WaffleError.notFound } guard resolved.count == 1 else { throw WaffleError.multipleFound } return resolved.first! as! T } public func rebuild() -> Waffle.Builder { return Waffle.Builder(items: items) } }
mit
4a66b1f22f94f7afadb7add2fcf52c41
22.578947
68
0.519345
4.2
false
false
false
false
Buratti/VaporPayPal
Sources/VaporPayPalPayment.swift
1
2699
// // VaporPayPalPayment.swift // VaporAuthTemplate // // Created by Alessio Buratti on 04/03/2017. // // import Foundation import JSON /// Describe a Payment public final class VaporPayPalPayment { /// The possible intent public enum Intent: String { case sale case authorize case order } /// public enum State: String { case unexisting case created case approved case failed } /// public var id: String { return _id ?? "" } /// internal var _id: String? /// The selected intent public var intent = Intent.sale /// public var state: State { return _state } /// internal var _state = State.unexisting /// The PayPal Payer object public var payer = VaporPayPalPayer() /// The PayPal Redirect URLs public var redirectUrls = VaporPayPalRedirectUrls() /// The transaction array public var transactions: [VaporPayPalTransaction] = [] /// The link generated by the PayPal REST API. Empty until the Payment object is executed from a PayPal object. internal var _links: [VaporPayPalLink] = [] /// The link generated by the PayPal REST API. Empty until the Payment object is executed from a PayPal object. public var links: [VaporPayPalLink] { return _links } /// The approval url generated by the PayPal REST API public var approvalUrl: String? { for link in _links { if link.rel.equals(caseInsensitive: "approval_url") { return link.href } } return nil } /// Creates a default Payment object public init() { } /// public init(id: String) { _state = .created self._id = id } /// Create a Payment object with the requested properties public init(payer: VaporPayPalPayer, redirectUrls: VaporPayPalRedirectUrls, transactions: [VaporPayPalTransaction], intent: Intent = .sale) { self.payer = payer self.redirectUrls = redirectUrls self.transactions = transactions self.intent = intent } } extension VaporPayPalPayment: JSONRepresentable { public func makeJSON() throws -> JSON { guard transactions.count > 0 else { throw VaporPayPalError.transactionsMissing } return try JSON([ "intent": intent.rawValue.makeNode(), "redirect_urls": redirectUrls.makeJSON().makeNode(), "payer": payer.makeJSON().makeNode(), "transactions": transactions.makeJSON().makeNode() ]) } }
mit
7083e9bbd82f3c094d9791eb8e3e15ff
23.761468
145
0.596517
4.836918
false
false
false
false
steve228uk/Torrents
Torrents/ViewController.swift
1
1960
// // ViewController.swift // Torrents // // Created by Stephen Radford on 01/03/2016. // Copyright © 2016 Cocoon Development Ltd. All rights reserved. // import UIKit import RxSwift import RxCocoa import JLToast class ViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var objects = Variable([[String:String]]()) override func viewDidLoad() { super.viewDidLoad() addObserverToSelectedRow() addObserverToSearchBar() addObserverToTable() } func addObserverToSelectedRow() { tableView.rx_itemSelected.subscribeNext { indexPath in UIPasteboard.generalPasteboard().string = self.objects.value[indexPath.row]["link"] JLToast.makeText("Link Copied!").show() self.tableView.deselectRowAtIndexPath(indexPath, animated: true) }.addDisposableTo(disposeBag) } func addObserverToTable() { objects.asObservable() .map { $0.map { $0["title"]! } } .bindTo(self.tableView.rx_itemsWithCellIdentifier("Cell")) { row, element, cell in cell.textLabel?.text = element }.addDisposableTo(disposeBag) } func addObserverToSearchBar() { searchBar.rx_text .throttle(0.3, scheduler: MainScheduler.instance) .subscribeNext { text in UIApplication.sharedApplication().networkActivityIndicatorVisible = true YIFY.search(text) .subscribe(onNext: { self.objects.value = $0 }, onError: { _ in JLToast.makeText("Could not connect to YIFY!").show() }, onCompleted: { UIApplication.sharedApplication().networkActivityIndicatorVisible = false }, onDisposed: nil) .addDisposableTo(disposeBag) }.addDisposableTo(disposeBag) } }
mit
827e72bd25d7936722d634154f614c8d
30.596774
95
0.630934
5.128272
false
false
false
false
SteveBarnegren/SBSwiftUtils
Tests/Extensions/Array/Array+InsertionTests.swift
1
2158
// // Array+InsertionTests.swift // SBSwiftUtilsTests // // Created by Steve Barnegren on 11/02/2018. // Copyright © 2018 SteveBarnegren. All rights reserved. // import XCTest import SBSwiftUtils class Array_InsertionTests: XCTestCase { // MARK: - Prepend func testPrepend() { var array = ["e", "l", "l", "o"] array.prepend("h") XCTAssertEqual(array, ["h", "e", "l", "l", "o"]) var emptyArray = [String]() emptyArray.prepend("a") XCTAssertEqual(emptyArray, ["a"]) } func testPrependContentsOf() { var array = ["l", "l", "o"] array.prepend(contentsOf: ["h", "e"]) XCTAssertEqual(array, ["h", "e", "l", "l", "o"]) var emptyArray = [String]() emptyArray.prepend(contentsOf: ["h", "e", "l", "l", "o"]) XCTAssertEqual(emptyArray, ["h", "e", "l", "l", "o"]) } // MARK: - Prepending func testPrepending() { let array = ["e", "l", "l", "o"] XCTAssertEqual(array.prepending("h"), ["h", "e", "l", "l", "o"]) let emptyArray = [String]() XCTAssertEqual(emptyArray.prepending("a"), ["a"]) } func testPrependingContentsOf() { let array = ["l", "l", "o"] XCTAssertEqual(array.prepending(contentsOf: ["h", "e"]), ["h", "e", "l", "l", "o"]) let emptyArray = [String]() XCTAssertEqual(emptyArray.prepending(contentsOf: ["h", "e", "l", "l", "o"]), ["h", "e", "l", "l", "o"]) } // MARK: - Appending func testAppending() { let array = ["d", "o"] XCTAssertEqual(array.appending("g"), ["d", "o", "g"]) let emptyArray = [String]() XCTAssertEqual(emptyArray.appending("a"), ["a"]) } func testAppendingContentsOf() { let array = ["h", "e"] XCTAssertEqual(array.appending(contentsOf: ["l", "l", "o"]), ["h", "e", "l", "l", "o"]) let emptyArray = [String]() XCTAssertEqual(emptyArray.appending(contentsOf: ["d", "o", "g"]), ["d", "o", "g"]) } }
mit
2444baafa48c8d88362a54c0ab43c8ff
26.653846
111
0.487714
3.777583
false
true
false
false
vapor-community/stripe
Sources/Stripe/Stripe+Extensions.swift
1
2714
// // Stripe+Extensions.swift // // // Created by Andrew Edwards on 6/14/19. // import Vapor @_exported import StripeKit extension Application { public var stripe: StripeClient { guard let stripeKey = Environment.get("STRIPE_API_KEY") else { fatalError("STRIPE_API_KEY env var required") } return .init(httpClient: self.http.client.shared, eventLoop: self.eventLoopGroup.next(), apiKey: stripeKey) } } extension Request { private struct StripeKey: StorageKey { typealias Value = StripeClient } public var stripe: StripeClient { if let existing = application.storage[StripeKey.self] { return existing.hopped(to: self.eventLoop) } else { guard let stripeKey = Environment.get("STRIPE_API_KEY") else { fatalError("STRIPE_API_KEY env var required") } let new = StripeClient(httpClient: self.application.http.client.shared, eventLoop: self.eventLoop, apiKey: stripeKey) self.application.storage[StripeKey.self] = new return new } } } extension StripeClient { /// Verifies a Stripe signature for a given `Request`. This automatically looks for the header in the headers of the request and the body. /// - Parameters: /// - req: The `Request` object to check header and body for /// - secret: The webhook secret used to verify the signature /// - tolerance: In seconds the time difference tolerance to prevent replay attacks: Default 300 seconds /// - Throws: `StripeSignatureError` public static func verifySignature(for req: Request, secret: String, tolerance: Double = 300) throws { guard let header = req.headers.first(name: "Stripe-Signature") else { throw StripeSignatureError.unableToParseHeader } guard let data = req.body.data else { throw StripeSignatureError.noMatchingSignatureFound } try StripeClient.verifySignature(payload: Data(data.readableBytesView), header: header, secret: secret, tolerance: tolerance) } } extension StripeSignatureError: AbortError { public var reason: String { switch self { case .noMatchingSignatureFound: return "No matching signature was found" case .timestampNotTolerated: return "Timestamp was not tolerated" case .unableToParseHeader: return "Unable to parse Stripe-Signature header" } } public var status: HTTPResponseStatus { .badRequest } }
mit
325162d0bc491b7db86982ed495abb68
34.246753
142
0.624171
4.695502
false
false
false
false
phausler/Auspicion
Auspicion/SourceRange.swift
1
1076
// // SourceRange.swift // Auspicion // // Created by Philippe Hausler on 10/6/14. // Copyright (c) 2014 Philippe Hausler. All rights reserved. // import clang public final class SourceRange { init(_ context: CXSourceRange) { self.context = context } public convenience init(begin: SourceLocation, end: SourceLocation) { self.init(clang_getRange(begin.context, end.context)) } private var _start: SourceLocation? = nil public var start: SourceLocation { if _start == nil { _start = SourceLocation(clang_getRangeStart(self.context)) } return _start! } private var _end: SourceLocation? = nil public var end: SourceLocation { if _end == nil { _end = SourceLocation(clang_getRangeEnd(self.context)) } return _end! } internal let context: CXSourceRange } public func ==(lhs: SourceRange, rhs: SourceRange) -> Bool { return clang_equalRanges(lhs.context, rhs.context) != 0 } extension SourceRange : Equatable { }
mit
df555643d4a88c01d2683b45ffa57c6e
22.933333
73
0.625465
4.029963
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/ScrollSelectionTableViewCell.swift
3
1409
// // ScrollSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/25/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class ScrollSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Scroll Behavior" descriptionValue = "Describes whether the entry is vertically scrollable" insertSegments(by: ["Loosed", "Disabled", "One Side"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.scroll { case .enabled: segmentedControl.selectedSegmentIndex = 0 case .disabled: segmentedControl.selectedSegmentIndex = 1 case .edgeCrossingDisabled: segmentedControl.selectedSegmentIndex = 2 } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt) case 1: attributesWrapper.attributes.scroll = .disabled case 2: attributesWrapper.attributes.scroll = .edgeCrossingDisabled(swipeable: true) default: break } } }
apache-2.0
dc1f1d0d81367dc9752ae3d9932d3182
31.767442
101
0.663591
5.105072
false
false
false
false
DarrenKong/firefox-ios
Sync/BookmarkPayload.swift
5
16682
/* 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 Shared import Storage import XCGLogger import SwiftyJSON private let log = Logger.syncLogger public protocol MirrorItemable { func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem } extension BookmarkMirrorItem { func asPayload() -> BookmarkBasePayload { return BookmarkType.somePayloadFromJSON(self.asJSON()) } func asPayloadWithChildren(_ children: [GUID]?) -> BookmarkBasePayload { let remappedChildren: [GUID]? if let children = children { if BookmarkRoots.RootGUID == self.guid { // Only the root contains roots, and so only its children // need to be translated. remappedChildren = children.map(BookmarkRoots.translateOutgoingRootGUID) } else { remappedChildren = children } } else { remappedChildren = nil } let json = self.asJSONWithChildren(remappedChildren) return BookmarkType.somePayloadFromJSON(json) } } /** * Hierarchy: * - BookmarkBasePayload * \_ FolderPayload * \_ LivemarkPayload * \_ SeparatorPayload * \_ BookmarkPayload * \_ BookmarkQueryPayload */ public enum BookmarkType: String { case livemark case separator case folder case bookmark case query case microsummary // Dead: now a bookmark. // The result might be invalid, but it won't be nil. public static func somePayloadFromJSON(_ json: JSON) -> BookmarkBasePayload { return payloadFromJSON(json) ?? BookmarkBasePayload(json) } public static func payloadFromJSON(_ json: JSON) -> BookmarkBasePayload? { if json["deleted"].bool ?? false { // Deleted records won't have a type. return BookmarkBasePayload(json) } guard let typeString = json["type"].string else { return nil } guard let type = BookmarkType(rawValue: typeString) else { return nil } switch type { case microsummary: fallthrough case bookmark: return BookmarkPayload(json) case folder: return FolderPayload(json) case livemark: return LivemarkPayload(json) case separator: return SeparatorPayload(json) case query: return BookmarkQueryPayload(json) } } public static func isValid(_ type: String?) -> Bool { guard let type = type else { return false } return BookmarkType(rawValue: type) != nil } } open class LivemarkPayload: BookmarkBasePayload { open var feedURI: String? { return self["feedUri"].string } open var siteURI: String? { return self["siteUri"].string } override open func isValid() -> Bool { if !super.isValid() { return false } return self.hasRequiredStringFields(["feedUri", "siteUri"]) } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? LivemarkPayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if self.feedURI != p.feedURI { return false } if self.siteURI != p.siteURI { return false } return true } override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { if self.deleted { return BookmarkMirrorItem.deleted(.livemark, guid: self.id, modified: modified) } return BookmarkMirrorItem.livemark( self.id, dateAdded: self["dateAdded"].uInt64, modified: modified, hasDupe: self.hasDupe, // TODO: these might need to be weakened if real-world data is dirty. parentID: self["parentid"].stringValue, parentName: self["parentName"].string, title: self["title"].string, description: self["description"].string, feedURI: self.feedURI!, siteURI: self.siteURI! ) } } open class SeparatorPayload: BookmarkBasePayload { override open func isValid() -> Bool { if !super.isValid() { return false } if !self["pos"].isInt() { log.warning("Separator \(self.id) missing pos.") return false } return true } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? SeparatorPayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if self["pos"].int != p["pos"].int { return false } return true } override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { if self.deleted { return BookmarkMirrorItem.deleted(.separator, guid: self.id, modified: modified) } return BookmarkMirrorItem.separator( self.id, dateAdded: self["dateAdded"].uInt64, modified: modified, hasDupe: self.hasDupe, // TODO: these might need to be weakened if real-world data is dirty. parentID: self["parentid"].string!, parentName: self["parentName"].string, pos: self["pos"].int! ) } } open class FolderPayload: BookmarkBasePayload { fileprivate var childrenAreValid: Bool { return self.hasStringArrayField("children") } override open func isValid() -> Bool { if !super.isValid() { return false } if !self.hasRequiredStringFields(["title"]) { log.warning("Folder \(self.id) missing title.") return false } if !self.hasOptionalStringFields(["description"]) { log.warning("Folder \(self.id) missing string description.") return false } if !self.childrenAreValid { log.warning("Folder \(self.id) has invalid children.") return false } return true } open var children: [String] { return self["children"].arrayValue.map { $0.string! } } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? FolderPayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if self["title"].string != p["title"].string { return false } if self["description"].string != p["description"].string { return false } if self.children != p.children { return false } return true } override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { if self.deleted { return BookmarkMirrorItem.deleted(.folder, guid: self.id, modified: modified) } return BookmarkMirrorItem.folder( self.id, dateAdded: self["dateAdded"].uInt64, modified: modified, hasDupe: self.hasDupe, // TODO: these might need to be weakened if real-world data is dirty. parentID: self["parentid"].string!, parentName: self["parentName"].string, title: self["title"].string!, description: self["description"].string, children: self.children ) } } open class BookmarkPayload: BookmarkBasePayload { fileprivate static let requiredBookmarkStringFields = ["bmkUri"] // Title *should* be required, but can be missing for queries. Great. fileprivate static let optionalBookmarkStringFields = ["title", "keyword", "description"] fileprivate static let optionalBookmarkBooleanFields = ["loadInSidebar"] override open func isValid() -> Bool { if !super.isValid() { return false } if !self.hasRequiredStringFields(BookmarkPayload.requiredBookmarkStringFields) { log.warning("Bookmark \(self.id) missing required string field.") return false } if !self.hasStringArrayField("tags") { log.warning("Bookmark \(self.id) missing tags array. We'll replace with an empty array.") // Ignore. } if !self.hasOptionalStringFields(BookmarkPayload.optionalBookmarkStringFields) { return false } return self.hasOptionalBooleanFields(BookmarkPayload.optionalBookmarkBooleanFields) } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? BookmarkPayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if !BookmarkPayload.requiredBookmarkStringFields.every({ p[$0].string! == self[$0].string! }) { return false } // TODO: compare optional fields. if Set(self.tags) != Set(p.tags) { return false } if self["loadInSidebar"].bool != p["loadInSidebar"].bool { return false } return true } lazy var tags: [String] = { return self["tags"].arrayValue.flatMap { $0.string } }() lazy var tagsString: String = { if self["tags"].isArray() { return self["tags"].stringValue() ?? "[]" } return "[]" }() override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { if self.deleted { return BookmarkMirrorItem.deleted(.bookmark, guid: self.id, modified: modified) } return BookmarkMirrorItem.bookmark( self.id, dateAdded: self["dateAdded"].uInt64, modified: modified, hasDupe: self.hasDupe, // TODO: these might need to be weakened if real-world data is dirty. parentID: self["parentid"].string!, parentName: self["parentName"].string, title: self["title"].string ?? "", description: self["description"].string, URI: self["bmkUri"].string!, tags: self.tagsString, // Stringify it so we can put the array in the DB. keyword: self["keyword"].string ) } } open class BookmarkQueryPayload: BookmarkPayload { override open func isValid() -> Bool { if !super.isValid() { return false } if !self.hasOptionalStringFields(["queryId", "folderName"]) { log.warning("Query \(self.id) missing queryId or folderName.") return false } return true } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? BookmarkQueryPayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if self["folderName"].string != p["folderName"].string { return false } if self["queryId"].string != p["queryId"].string { return false } return true } override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { if self.deleted { return BookmarkMirrorItem.deleted(.query, guid: self.id, modified: modified) } return BookmarkMirrorItem.query( self.id, dateAdded: self["dateAdded"].uInt64, modified: modified, hasDupe: self.hasDupe, parentID: self["parentid"].string!, parentName: self["parentName"].string, title: self["title"].string ?? "", description: self["description"].string, URI: self["bmkUri"].string!, tags: self.tagsString, // Stringify it so we can put the array in the DB. keyword: self["keyword"].string, folderName: self["folderName"].string, queryID: self["queryID"].string ) } } open class BookmarkBasePayload: CleartextPayloadJSON, MirrorItemable { fileprivate static let requiredStringFields: [String] = ["parentid", "type"] fileprivate static let optionalBooleanFields: [String] = ["hasDupe"] static func deletedPayload(_ guid: GUID) -> BookmarkBasePayload { let remappedGUID = BookmarkRoots.translateOutgoingRootGUID(guid) return BookmarkBasePayload(JSON(["id": remappedGUID, "deleted": true])) } func hasStringArrayField(_ name: String) -> Bool { guard let arr = self[name].array else { return false } return arr.every { $0.isString() } } func hasRequiredStringFields(_ fields: [String]) -> Bool { return fields.every { self[$0].isString() } } func hasOptionalStringFields(_ fields: [String]) -> Bool { return fields.every { field in let val = self[field] // Yup, 404 is not found, so this means "string or nothing". let valid = val.isString() || val.isNull() || val.isError() if !valid { log.debug("Field \(field) is invalid: \(val).") } return valid } } func hasOptionalBooleanFields(_ fields: [String]) -> Bool { return fields.every { field in let val = self[field] // Yup, 404 is not found, so this means "boolean or nothing". let valid = val.isBool() || val.isNull() || val.error?.code == 404 if !valid { log.debug("Field \(field) is invalid: \(val).") } return valid } } override open func isValid() -> Bool { if !super.isValid() { return false } if self["deleted"].bool ?? false { return true } // If not deleted, we must be a specific, known, type! if !BookmarkType.isValid(self["type"].string) { return false } if !(self["parentName"].isString() || self.id == "places") { if self["parentid"].string! == "places" { log.debug("Accepting root with missing parent name.") } else { // Bug 1318414. log.warning("Accepting bookmark with missing parent name.") } } if !self.hasRequiredStringFields(BookmarkBasePayload.requiredStringFields) { log.warning("Item missing required string field.") return false } return self.hasOptionalBooleanFields(BookmarkBasePayload.optionalBooleanFields) } open var hasDupe: Bool { return self["hasDupe"].bool ?? false } /** * This only makes sense for valid payloads. */ override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { guard let p = obj as? BookmarkBasePayload else { return false } if !super.equalPayloads(p) { return false } if self.deleted { return true } if p.deleted { return self.deleted == p.deleted } // If either record is deleted, these other fields might be missing. // But we just checked, so we're good to roll on. let same: (String) -> Bool = { field in let left = self[field].string let right = p[field].string return left == right } if !BookmarkBasePayload.requiredStringFields.every(same) { return false } if p["parentName"].string != self["parentName"].string { return false } return self.hasDupe == p.hasDupe } // This goes here because extensions cannot override methods yet. open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem { precondition(self.deleted, "Non-deleted items should have a specific type.") return BookmarkMirrorItem.deleted(.bookmark, guid: self.id, modified: modified) } }
mpl-2.0
586e6d757b729c9b473953f40144babf
28.215412
103
0.570255
5.027728
false
false
false
false
FabrizioBrancati/SwiftyBot
Sources/Assistant/Response/GooglePayload.swift
1
2003
// // GooglePayload.swift // SwiftyBot // // The MIT License (MIT) // // Copyright (c) 2016 - 2019 Fabrizio Brancati. // // 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 /// Message Google Payload. public struct GooglePayload: Codable { /// Expect User Response. public private(set) var expectUserResponse: Bool /// Rich Response. public internal(set) var richResponse: RichResponse /// System Intent. public internal(set) var systemIntent: SystemIntent? /// Creates a Google payload. /// /// - Parameters: /// - expectUserResponse: Expect user response. /// - richResponse: Rich response. /// - systemIntent: System intent. public init(expectUserResponse: Bool = true, richResponse: RichResponse, systemIntent: SystemIntent? = nil) { self.expectUserResponse = expectUserResponse self.richResponse = richResponse self.systemIntent = systemIntent } }
mit
6fcac66528415ab6cf3bd0b934f5ccea
39.877551
113
0.718922
4.411894
false
false
false
false
senfi/KSTokenView
Examples/ProgrammaticallyExample/ProgrammaticallyExample/ViewController.swift
1
4011
// // ViewController.swift // ProgrammaticallyExample // // Created by Khawar Shahzad on 01/01/2015. // Copyright (c) 2015 Khawar Shahzad. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit class ViewController: UIViewController { let names = List.names() var tokenView: KSTokenView = KSTokenView(frame: .zeroRect) @IBOutlet weak var shouldChangeSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() tokenView = KSTokenView(frame: CGRect(x: 10, y: 160, width: 300, height: 30)) tokenView.delegate = self tokenView.promptText = "Favorites: " tokenView.placeholder = "Type to search" tokenView.descriptionText = "Languages" tokenView.style = .Rounded view.addSubview(tokenView) for i in 0...20 { let token: KSToken = KSToken(title: names[i]) tokenView.addToken(token) } } @IBAction func addToken(sender: AnyObject) { let title = names[Int(arc4random_uniform(UInt32(names.count)))] as String let token = KSToken(title: title, object: title) // Token background color var red = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) var green = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) var blue = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) token.tokenBackgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0) // Token text color red = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) green = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) blue = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) token.tokenTextColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0) tokenView.addToken(token) } @IBAction func deleteLastToken(sender: AnyObject) { tokenView.deleteLastToken() } @IBAction func deleteAllTokens(sender: AnyObject) { tokenView.deleteAllTokens() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: KSTokenViewDelegate { func tokenView(token: KSTokenView, performSearchWithString string: String, completion: ((results: Array<AnyObject>) -> Void)?) { var data: Array<String> = [] for value: String in names { if value.lowercaseString.rangeOfString(string.lowercaseString) != nil { data.append(value) } } completion!(results: data) } func tokenView(token: KSTokenView, displayTitleForObject object: AnyObject) -> String { return object as! String } func tokenView(tokenView: KSTokenView, shouldChangeAppearanceForToken token: KSToken) -> KSToken? { if shouldChangeSwitch.on { token.tokenBackgroundColor = UIColor.redColor() token.tokenTextColor = UIColor.blackColor() } return token } }
mit
1c659892f19c253c477d939388f113a9
37.576923
131
0.686612
4.169439
false
false
false
false
juyka/Rating-VolSU-iOS
Rating-VolSU-iOS/Rating-VolSU-iOS/AppDelegate.swift
1
5878
// // AppDelegate.swift // Rating-VolSU-iOS // // Created by Настя on 30.09.14. // Copyright (c) 2014 VolSU. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "ru.VolSU.Rating_VolSU_iOS" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Rating_VolSU_iOS", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Rating_VolSU_iOS.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
c1fcb48650e56dad7ce3b2a1aef7afa5
51.90991
287
0.749872
5.27673
false
false
false
false
practicalswift/swift
stdlib/public/core/Optional.swift
4
26385
//===----------------------------------------------------------------------===// // // 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 that represents either a wrapped value or `nil`, the absence of a /// value. /// /// You use the `Optional` type whenever you use optional values, even if you /// never type the word `Optional`. Swift's type system usually shows the /// wrapped type's name with a trailing question mark (`?`) instead of showing /// the full type name. For example, if a variable has the type `Int?`, that's /// just another way of writing `Optional<Int>`. The shortened form is /// preferred for ease of reading and writing code. /// /// The types of `shortForm` and `longForm` in the following code sample are /// the same: /// /// let shortForm: Int? = Int("42") /// let longForm: Optional<Int> = Int("42") /// /// The `Optional` type is an enumeration with two cases. `Optional.none` is /// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped /// value. For example: /// /// let number: Int? = Optional.some(42) /// let noNumber: Int? = Optional.none /// print(noNumber == nil) /// // Prints "true" /// /// You must unwrap the value of an `Optional` instance before you can use it /// in many contexts. Because Swift provides several ways to safely unwrap /// optional values, you can choose the one that helps you write clear, /// concise code. /// /// The following examples use this dictionary of image names and file paths: /// /// let imagePaths = ["star": "/glyphs/star.png", /// "portrait": "/images/content/portrait.jpg", /// "spacer": "/images/shared/spacer.gif"] /// /// Getting a dictionary's value using a key returns an optional value, so /// `imagePaths["star"]` has type `Optional<String>` or, written in the /// preferred manner, `String?`. /// /// Optional Binding /// ---------------- /// /// To conditionally bind the wrapped value of an `Optional` instance to a new /// variable, use one of the optional binding control structures, including /// `if let`, `guard let`, and `switch`. /// /// if let starPath = imagePaths["star"] { /// print("The star image is at '\(starPath)'") /// } else { /// print("Couldn't find the star image") /// } /// // Prints "The star image is at '/glyphs/star.png'" /// /// Optional Chaining /// ----------------- /// /// To safely access the properties and methods of a wrapped instance, use the /// postfix optional chaining operator (postfix `?`). The following example uses /// optional chaining to access the `hasSuffix(_:)` method on a `String?` /// instance. /// /// if imagePaths["star"]?.hasSuffix(".png") == true { /// print("The star image is in PNG format") /// } /// // Prints "The star image is in PNG format" /// /// Using the Nil-Coalescing Operator /// --------------------------------- /// /// Use the nil-coalescing operator (`??`) to supply a default value in case /// the `Optional` instance is `nil`. Here a default path is supplied for an /// image that is missing from `imagePaths`. /// /// let defaultImagePath = "/images/default.png" /// let heartPath = imagePaths["heart"] ?? defaultImagePath /// print(heartPath) /// // Prints "/images/default.png" /// /// The `??` operator also works with another `Optional` instance on the /// right-hand side. As a result, you can chain multiple `??` operators /// together. /// /// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath /// print(shapePath) /// // Prints "/images/default.png" /// /// Unconditional Unwrapping /// ------------------------ /// /// When you're certain that an instance of `Optional` contains a value, you /// can unconditionally unwrap the value by using the forced /// unwrap operator (postfix `!`). For example, the result of the failable `Int` /// initializer is unconditionally unwrapped in the example below. /// /// let number = Int("42")! /// print(number) /// // Prints "42" /// /// You can also perform unconditional optional chaining by using the postfix /// `!` operator. /// /// let isPNG = imagePaths["star"]!.hasSuffix(".png") /// print(isPNG) /// // Prints "true" /// /// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime /// error. @_frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral { // The compiler has special knowledge of Optional<Wrapped>, including the fact // that it is an `enum` with cases named `none` and `some`. /// The absence of a value. /// /// In code, the absence of a value is typically written using the `nil` /// literal rather than the explicit `.none` enumeration case. case none /// The presence of a value, stored as `Wrapped`. case some(Wrapped) /// Creates an instance that stores the given value. @_transparent public init(_ some: Wrapped) { self = .some(some) } /// Evaluates the given closure when this `Optional` instance is not `nil`, /// passing the unwrapped value as a parameter. /// /// Use the `map` method with a closure that returns a non-optional value. /// This example performs an arithmetic operation on an /// optional integer. /// /// let possibleNumber: Int? = Int("42") /// let possibleSquare = possibleNumber.map { $0 * $0 } /// print(possibleSquare) /// // Prints "Optional(1764)" /// /// let noNumber: Int? = nil /// let noSquare = noNumber.map { $0 * $0 } /// print(noSquare) /// // Prints "nil" /// /// - Parameter transform: A closure that takes the unwrapped value /// of the instance. /// - Returns: The result of the given closure. If this instance is `nil`, /// returns `nil`. @inlinable public func map<U>( _ transform: (Wrapped) throws -> U ) rethrows -> U? { switch self { case .some(let y): return .some(try transform(y)) case .none: return .none } } /// Evaluates the given closure when this `Optional` instance is not `nil`, /// passing the unwrapped value as a parameter. /// /// Use the `flatMap` method with a closure that returns an optional value. /// This example performs an arithmetic operation with an optional result on /// an optional integer. /// /// let possibleNumber: Int? = Int("42") /// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in /// let (result, overflowed) = x.multipliedReportingOverflow(by: x) /// return overflowed ? nil : result /// } /// print(nonOverflowingSquare) /// // Prints "Optional(1764)" /// /// - Parameter transform: A closure that takes the unwrapped value /// of the instance. /// - Returns: The result of the given closure. If this instance is `nil`, /// returns `nil`. @inlinable public func flatMap<U>( _ transform: (Wrapped) throws -> U? ) rethrows -> U? { switch self { case .some(let y): return try transform(y) case .none: return .none } } /// Creates an instance initialized with `nil`. /// /// Do not call this initializer directly. It is used by the compiler when you /// initialize an `Optional` instance with a `nil` literal. For example: /// /// var i: Index? = nil /// /// In this example, the assignment to the `i` variable calls this /// initializer behind the scenes. @_transparent public init(nilLiteral: ()) { self = .none } /// The wrapped value of this instance, unwrapped without checking whether /// the instance is `nil`. /// /// The `unsafelyUnwrapped` property provides the same value as the forced /// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no /// check is performed to ensure that the current instance actually has a /// value. Accessing this property in the case of a `nil` value is a serious /// programming error and could lead to undefined behavior or a runtime /// error. /// /// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same /// behavior as using the postfix `!` operator and triggers a runtime error /// if the instance is `nil`. /// /// The `unsafelyUnwrapped` property is recommended over calling the /// `unsafeBitCast(_:)` function because the property is more restrictive /// and because accessing the property still performs checking in debug /// builds. /// /// - Warning: This property trades safety for performance. Use /// `unsafelyUnwrapped` only when you are confident that this instance /// will never be equal to `nil` and only after you've tried using the /// postfix `!` operator. @inlinable public var unsafelyUnwrapped: Wrapped { @inline(__always) get { if let x = self { return x } _debugPreconditionFailure("unsafelyUnwrapped of nil optional") } } /// - Returns: `unsafelyUnwrapped`. /// /// This version is for internal stdlib use; it avoids any checking /// overhead for users, even in Debug builds. @inlinable internal var _unsafelyUnwrappedUnchecked: Wrapped { @inline(__always) get { if let x = self { return x } _internalInvariantFailure("_unsafelyUnwrappedUnchecked of nil optional") } } } extension Optional : CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { switch self { case .some(let value): var result = "Optional(" debugPrint(value, terminator: "", to: &result) result += ")" return result case .none: return "nil" } } } extension Optional : CustomReflectable { public var customMirror: Mirror { switch self { case .some(let value): return Mirror( self, children: [ "some": value ], displayStyle: .optional) case .none: return Mirror(self, children: [:], displayStyle: .optional) } } } @_transparent public // COMPILER_INTRINSIC func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word, _isImplicitUnwrap: Builtin.Int1) { _preconditionFailure( Bool(_isImplicitUnwrap) ? "Unexpectedly found nil while implicitly unwrapping an Optional value" : "Unexpectedly found nil while unwrapping an Optional value", file: StaticString(_start: _filenameStart, utf8CodeUnitCount: _filenameLength, isASCII: _filenameIsASCII), line: UInt(_line)) } extension Optional : Equatable where Wrapped : Equatable { /// Returns a Boolean value indicating whether two optional instances are /// equal. /// /// Use this equal-to operator (`==`) to compare any two optional instances of /// a type that conforms to the `Equatable` protocol. The comparison returns /// `true` if both arguments are `nil` or if the two arguments wrap values /// that are equal. Conversely, the comparison returns `false` if only one of /// the arguments is `nil` or if the two arguments wrap values that are not /// equal. /// /// let group1 = [1, 2, 3, 4, 5] /// let group2 = [1, 3, 5, 7, 9] /// if group1.first == group2.first { /// print("The two groups start the same.") /// } /// // Prints "The two groups start the same." /// /// You can also use this operator to compare a non-optional value to an /// optional that wraps the same type. The non-optional value is wrapped as an /// optional before the comparison is made. In the following example, the /// `numberToMatch` constant is wrapped as an optional before comparing to the /// optional `numberFromString`: /// /// let numberToFind: Int = 23 /// let numberFromString: Int? = Int("23") // Optional(23) /// if numberToFind == numberFromString { /// print("It's a match!") /// } /// // Prints "It's a match!" /// /// An instance that is expressed as a literal can also be used with this /// operator. In the next example, an integer literal is compared with the /// optional integer `numberFromString`. The literal `23` is inferred as an /// `Int` instance and then wrapped as an optional before the comparison is /// performed. /// /// if 23 == numberFromString { /// print("It's a match!") /// } /// // Prints "It's a match!" /// /// - Parameters: /// - lhs: An optional value to compare. /// - rhs: Another optional value to compare. @inlinable public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l == r case (nil, nil): return true default: return false } } } extension Optional: Hashable where Wrapped: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { switch self { case .none: hasher.combine(0 as UInt8) case .some(let wrapped): hasher.combine(1 as UInt8) hasher.combine(wrapped) } } } // Enable pattern matching against the nil literal, even if the element type // isn't equatable. @_fixed_layout public struct _OptionalNilComparisonType : ExpressibleByNilLiteral { /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { } } extension Optional { /// Returns a Boolean value indicating whether an argument matches `nil`. /// /// You can use the pattern-matching operator (`~=`) to test whether an /// optional instance is `nil` even when the wrapped value's type does not /// conform to the `Equatable` protocol. The pattern-matching operator is used /// internally in `case` statements for pattern matching. /// /// The following example declares the `stream` variable as an optional /// instance of a hypothetical `DataStream` type, and then uses a `switch` /// statement to determine whether the stream is `nil` or has a configured /// value. When evaluating the `nil` case of the `switch` statement, this /// operator is called behind the scenes. /// /// var stream: DataStream? = nil /// switch stream { /// case nil: /// print("No data stream is configured.") /// case let x?: /// print("The data stream has \(x.availableBytes) bytes available.") /// } /// // Prints "No data stream is configured." /// /// - Note: To test whether an instance is `nil` in an `if` statement, use the /// equal-to operator (`==`) instead of the pattern-matching operator. The /// pattern-matching operator is primarily intended to enable `case` /// statement pattern matching. /// /// - Parameters: /// - lhs: A `nil` literal. /// - rhs: A value to match against `nil`. @_transparent public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool { switch rhs { case .some: return false case .none: return true } } // Enable equality comparisons against the nil literal, even if the // element type isn't equatable /// Returns a Boolean value indicating whether the left-hand-side argument is /// `nil`. /// /// You can use this equal-to operator (`==`) to test whether an optional /// instance is `nil` even when the wrapped value's type does not conform to /// the `Equatable` protocol. /// /// The following example declares the `stream` variable as an optional /// instance of a hypothetical `DataStream` type. Although `DataStream` is not /// an `Equatable` type, this operator allows checking whether `stream` is /// `nil`. /// /// var stream: DataStream? = nil /// if stream == nil { /// print("No data stream is configured.") /// } /// // Prints "No data stream is configured." /// /// - Parameters: /// - lhs: A value to compare to `nil`. /// - rhs: A `nil` literal. @_transparent public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool { switch lhs { case .some: return false case .none: return true } } /// Returns a Boolean value indicating whether the left-hand-side argument is /// not `nil`. /// /// You can use this not-equal-to operator (`!=`) to test whether an optional /// instance is not `nil` even when the wrapped value's type does not conform /// to the `Equatable` protocol. /// /// The following example declares the `stream` variable as an optional /// instance of a hypothetical `DataStream` type. Although `DataStream` is not /// an `Equatable` type, this operator allows checking whether `stream` wraps /// a value and is therefore not `nil`. /// /// var stream: DataStream? = fetchDataStream() /// if stream != nil { /// print("The data stream has been configured.") /// } /// // Prints "The data stream has been configured." /// /// - Parameters: /// - lhs: A value to compare to `nil`. /// - rhs: A `nil` literal. @_transparent public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool { switch lhs { case .some: return true case .none: return false } } /// Returns a Boolean value indicating whether the right-hand-side argument is /// `nil`. /// /// You can use this equal-to operator (`==`) to test whether an optional /// instance is `nil` even when the wrapped value's type does not conform to /// the `Equatable` protocol. /// /// The following example declares the `stream` variable as an optional /// instance of a hypothetical `DataStream` type. Although `DataStream` is not /// an `Equatable` type, this operator allows checking whether `stream` is /// `nil`. /// /// var stream: DataStream? = nil /// if nil == stream { /// print("No data stream is configured.") /// } /// // Prints "No data stream is configured." /// /// - Parameters: /// - lhs: A `nil` literal. /// - rhs: A value to compare to `nil`. @_transparent public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool { switch rhs { case .some: return false case .none: return true } } /// Returns a Boolean value indicating whether the right-hand-side argument is /// not `nil`. /// /// You can use this not-equal-to operator (`!=`) to test whether an optional /// instance is not `nil` even when the wrapped value's type does not conform /// to the `Equatable` protocol. /// /// The following example declares the `stream` variable as an optional /// instance of a hypothetical `DataStream` type. Although `DataStream` is not /// an `Equatable` type, this operator allows checking whether `stream` wraps /// a value and is therefore not `nil`. /// /// var stream: DataStream? = fetchDataStream() /// if nil != stream { /// print("The data stream has been configured.") /// } /// // Prints "The data stream has been configured." /// /// - Parameters: /// - lhs: A `nil` literal. /// - rhs: A value to compare to `nil`. @_transparent public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool { switch rhs { case .some: return true case .none: return false } } } /// Performs a nil-coalescing operation, returning the wrapped value of an /// `Optional` instance or a default value. /// /// A nil-coalescing operation unwraps the left-hand side if it has a value, or /// it returns the right-hand side as a default. The result of this operation /// will have the non-optional type of the left-hand side's `Wrapped` type. /// /// This operator uses short-circuit evaluation: `optional` is checked first, /// and `defaultValue` is evaluated only if `optional` is `nil`. For example: /// /// func getDefault() -> Int { /// print("Calculating default...") /// return 42 /// } /// /// let goodNumber = Int("100") ?? getDefault() /// // goodNumber == 100 /// /// let notSoGoodNumber = Int("invalid-input") ?? getDefault() /// // Prints "Calculating default..." /// // notSoGoodNumber == 42 /// /// In this example, `goodNumber` is assigned a value of `100` because /// `Int("100")` succeeded in returning a non-`nil` result. When /// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns /// `nil`, and so the `getDefault()` method is called to supply a default /// value. /// /// - Parameters: /// - optional: An optional value. /// - defaultValue: A value to use as a default. `defaultValue` is the same /// type as the `Wrapped` type of `optional`. @_transparent public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T { switch optional { case .some(let value): return value case .none: return try defaultValue() } } /// Performs a nil-coalescing operation, returning the wrapped value of an /// `Optional` instance or a default `Optional` value. /// /// A nil-coalescing operation unwraps the left-hand side if it has a value, or /// returns the right-hand side as a default. The result of this operation /// will be the same type as its arguments. /// /// This operator uses short-circuit evaluation: `optional` is checked first, /// and `defaultValue` is evaluated only if `optional` is `nil`. For example: /// /// let goodNumber = Int("100") ?? Int("42") /// print(goodNumber) /// // Prints "Optional(100)" /// /// let notSoGoodNumber = Int("invalid-input") ?? Int("42") /// print(notSoGoodNumber) /// // Prints "Optional(42)" /// /// In this example, `goodNumber` is assigned a value of `100` because /// `Int("100")` succeeds in returning a non-`nil` result. When /// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns /// `nil`, and so `Int("42")` is called to supply a default value. /// /// Because the result of this nil-coalescing operation is itself an optional /// value, you can chain default values by using `??` multiple times. The /// first optional value that isn't `nil` stops the chain and becomes the /// result of the whole expression. The next example tries to find the correct /// text for a greeting in two separate dictionaries before falling back to a /// static default. /// /// let greeting = userPrefs[greetingKey] ?? /// defaults[greetingKey] ?? "Greetings!" /// /// If `userPrefs[greetingKey]` has a value, that value is assigned to /// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and /// if not that, `greeting` will be set to the non-optional default value, /// `"Greetings!"`. /// /// - Parameters: /// - optional: An optional value. /// - defaultValue: A value to use as a default. `defaultValue` and /// `optional` have the same type. @_transparent public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T? { switch optional { case .some(let value): return value case .none: return try defaultValue() } } //===----------------------------------------------------------------------===// // Bridging //===----------------------------------------------------------------------===// #if _runtime(_ObjC) extension Optional : _ObjectiveCBridgeable { // The object that represents `none` for an Optional of this type. internal static var _nilSentinel : AnyObject { @_silgen_name("_swift_Foundation_getOptionalNilSentinelObject") get } public func _bridgeToObjectiveC() -> AnyObject { // Bridge a wrapped value by unwrapping. if let value = self { return _bridgeAnythingToObjectiveC(value) } // Bridge nil using a sentinel. return type(of: self)._nilSentinel } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout Optional<Wrapped>? ) { // Map the nil sentinel back to .none. // NB that the signature of _forceBridgeFromObjectiveC adds another level // of optionality, so we need to wrap the immediate result of the conversion // in `.some`. if source === _nilSentinel { result = .some(.none) return } // Otherwise, force-bridge the underlying value. let unwrappedResult = source as! Wrapped result = .some(.some(unwrappedResult)) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout Optional<Wrapped>? ) -> Bool { // Map the nil sentinel back to .none. // NB that the signature of _forceBridgeFromObjectiveC adds another level // of optionality, so we need to wrap the immediate result of the conversion // in `.some` to indicate success of the bridging operation, with a nil // result. if source === _nilSentinel { result = .some(.none) return true } // Otherwise, try to bridge the underlying value. if let unwrappedResult = source as? Wrapped { result = .some(.some(unwrappedResult)) return true } else { result = .none return false } } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> Optional<Wrapped> { if let nonnullSource = source { // Map the nil sentinel back to none. if nonnullSource === _nilSentinel { return .none } else { return .some(nonnullSource as! Wrapped) } } else { // If we unexpectedly got nil, just map it to `none` too. return .none } } } #endif
apache-2.0
e4796374353a6ab2ea23d99dd1da33fd
34.607287
82
0.629032
4.299332
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_fixed/00222-swift-modulefile-modulefile.swift
65
966
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f() { ({}) } a } s: X.Type) { } } class c { func b((Any, c))(a: { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } prtocolAny) -> Any in return p }) } b(a(1, a(2, 3))) func f Boolean>(b: T) { } f( func b( d { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F fu { o } } s m { class func s() } class p: m{ cl
apache-2.0
52788eb712c064310a62b164d35a7046
16.25
79
0.536232
2.668508
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/Mixpanel-swift/Mixpanel/TakeoverNotificationViewController.swift
1
9953
// // TakeoverNotificationViewController.swift // Mixpanel // // Created by Yarden Eitan on 8/11/16. // Copyright © 2016 Mixpanel. All rights reserved. // import UIKit class TakeoverNotificationViewController: BaseNotificationViewController { var takeoverNotification: TakeoverNotification! { get { return super.notification as? TakeoverNotification } } @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var firstButton: UIButton! @IBOutlet weak var secondButton: UIButton! @IBOutlet weak var secondButtonContainer: UIView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var viewMask: UIView! @IBOutlet weak var fadingView: FadingView! @IBOutlet weak var bottomImageSpacing: NSLayoutConstraint! convenience init(notification: TakeoverNotification) { self.init(notification: notification, nameOfClass: TakeoverNotificationViewController.notificationXibToLoad()) } static func notificationXibToLoad() -> String { var xibName = String(describing: TakeoverNotificationViewController.self) guard MixpanelInstance.sharedUIApplication() != nil else { return xibName } if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone { if UIDevice.current.orientation.isLandscape { xibName += "~iphonelandscape" } else { xibName += "~iphoneportrait" } } else { xibName += "~ipad" } return xibName } override func viewDidLoad() { super.viewDidLoad() if let notificationImage = notification.image, let image = UIImage(data: notificationImage, scale: 2) { imageView.image = image if let width = imageView.image?.size.width, width / UIScreen.main.bounds.width <= 0.6, let height = imageView.image?.size.height, height / UIScreen.main.bounds.height <= 0.3 { imageView.contentMode = UIView.ContentMode.center } } else { Logger.error(message: "notification image failed to load from data") } if takeoverNotification.title == nil || takeoverNotification.body == nil { NSLayoutConstraint(item: titleLabel!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: bodyLabel!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 0).isActive = true } else { titleLabel.text = takeoverNotification.title bodyLabel.text = takeoverNotification.body } viewMask.backgroundColor = UIColor(MPHex: takeoverNotification.backgroundColor) titleLabel.textColor = UIColor(MPHex: takeoverNotification.titleColor) bodyLabel.textColor = UIColor(MPHex: takeoverNotification.bodyColor) let origImage = closeButton.image(for: UIControl.State.normal) let tintedImage = origImage?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate) closeButton.setImage(tintedImage, for: UIControl.State.normal) closeButton.tintColor = UIColor(MPHex: takeoverNotification.closeButtonColor) closeButton.imageView?.contentMode = UIView.ContentMode.scaleAspectFit if takeoverNotification.buttons.count >= 1 { setupButtonView(buttonView: firstButton, buttonModel: takeoverNotification.buttons[0], index: 0) if takeoverNotification.buttons.count == 2 { setupButtonView(buttonView: secondButton, buttonModel: takeoverNotification.buttons[1], index: 1) } else { NSLayoutConstraint(item: secondButtonContainer!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 0).isActive = true } } if !takeoverNotification.shouldFadeImage { if bottomImageSpacing != nil { bottomImageSpacing.constant = 30 } fadingView.layer.mask = nil } if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { self.view.backgroundColor = UIColor(MPHex: takeoverNotification.backgroundColor) self.view.backgroundColor = self.view.backgroundColor?.withAlphaComponent(0.8) viewMask.clipsToBounds = true viewMask.layer.cornerRadius = 6 } } func setupButtonView(buttonView: UIButton, buttonModel: InAppButton, index: Int) { buttonView.setTitle(buttonModel.text, for: UIControl.State.normal) buttonView.titleLabel?.adjustsFontSizeToFitWidth = true buttonView.layer.cornerRadius = 5 buttonView.layer.borderWidth = 2 buttonView.setTitleColor(UIColor(MPHex: buttonModel.textColor), for: UIControl.State.normal) buttonView.setTitleColor(UIColor(MPHex: buttonModel.textColor), for: UIControl.State.highlighted) buttonView.setTitleColor(UIColor(MPHex: buttonModel.textColor), for: UIControl.State.selected) buttonView.layer.borderColor = UIColor(MPHex: buttonModel.borderColor).cgColor buttonView.backgroundColor = UIColor(MPHex: buttonModel.backgroundColor) buttonView.addTarget(self, action: #selector(buttonTapped(_:)), for: UIControl.Event.touchUpInside) buttonView.tag = index } override func show(animated: Bool) { window = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) if let window = window { window.alpha = 0 window.windowLevel = UIWindow.Level.alert window.rootViewController = self window.isHidden = false } let duration = animated ? 0.25 : 0 UIView.animate(withDuration: duration, animations: { self.window?.alpha = 1 }, completion: { _ in }) } override func hide(animated: Bool, completion: @escaping () -> Void) { let duration = animated ? 0.25 : 0 UIView.animate(withDuration: duration, animations: { self.window?.alpha = 0 }, completion: { _ in self.window?.isHidden = true self.window?.removeFromSuperview() self.window = nil completion() }) } @objc func buttonTapped(_ sender: AnyObject) { var whichButton = "primary" if self.takeoverNotification.buttons.count == 2 { whichButton = sender.tag == 0 ? "secondary" : "primary" } delegate?.notificationShouldDismiss(controller: self, callToActionURL: takeoverNotification.buttons[sender.tag].callToActionURL, shouldTrack: true, additionalTrackingProperties: ["button": whichButton]) } @IBAction func tappedClose(_ sender: AnyObject) { delegate?.notificationShouldDismiss(controller: self, callToActionURL: nil, shouldTrack: false, additionalTrackingProperties: nil) } override var shouldAutorotate: Bool { return false } } class FadingView: UIView { var gradientMask: CAGradientLayer! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) gradientMask = CAGradientLayer() layer.mask = gradientMask gradientMask.colors = [UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.clear.cgColor] gradientMask.locations = [0, 0.4, 0.9, 1] gradientMask.startPoint = CGPoint(x: 0, y: 0) gradientMask.endPoint = CGPoint(x: 0, y: 1) } override func layoutSubviews() { super.layoutSubviews() gradientMask.frame = bounds } } class InAppButtonView: UIButton { var origColor: UIColor? var wasCalled = false let overlayColor = UIColor(MPHex: 0x33868686) override var isHighlighted: Bool { didSet { switch isHighlighted { case true: if !wasCalled { origColor = backgroundColor if origColor == UIColor(red: 0, green: 0, blue: 0, alpha: 0) { backgroundColor = overlayColor } else { backgroundColor = backgroundColor?.add(overlay: overlayColor) } wasCalled = true } case false: backgroundColor = origColor wasCalled = false } } } }
mit
4d22472a366cbc56c00f25ab347f437d
40.466667
141
0.59375
5.435281
false
false
false
false
EricHein/Swift3.0Practice2016
01.Applicatons/Blog Reader/Blog Reader/AppDelegate.swift
1
6028
// // AppDelegate.swift // Blog Reader // // Created by Eric H on 29/10/2016. // Copyright © 2016 FabledRealm. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.persistentContainer.viewContext return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Blog_Reader") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
49c6a75dc559a3f5ad4786367e48b881
52.8125
285
0.709474
6.219814
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/Font/FontCustom.swift
1
1191
// // FontCustom.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit import OOBase public final class FontCustom: OOFont { // MARK: init public init(_ name: OOString, size: OOInt) { self.name = name self.size = size } // MARK: protocol OOFont public var value: UIFont { let name = self.name.value let font = UIFont(name: name, size: CGFloat(size.value)) guard font != nil else { fatalError("There is no font \(name)! Maybe file/fontid are different (check with DoPrintFontFamilies) or you forget to insert font into info.plist as UIAppFonts!") } return font! } // MARK: private private let name: OOString private let size: OOInt } // convenience initializer public extension FontCustom { convenience init(_ name: String, size: Int) { self.init(StringConst(name), size: IntConst(size)) } convenience init(_ name: String, size: OOInt) { self.init(StringConst(name), size: size) } convenience init(_ name: OOString, size: Int) { self.init(name, size: IntConst(size)) } }
mit
bf54d47f7df82d9a1b6427be7bb6395c
21.903846
199
0.607053
3.917763
false
false
false
false
PlugForMac/HypeMachineAPI
Source/Artist.swift
1
1589
// // Artist.swift // HypeMachineAPI // // Created by Alex Marchant on 5/11/15. // Copyright (c) 2015 Plug. All rights reserved. // import Cocoa public struct Artist { public let name: String public let thumbURL: URL? public let cnt: Int? public let rank: Int? public init(name: String, thumbURL: URL?, cnt: Int?, rank: Int?) { self.name = name self.thumbURL = thumbURL self.cnt = cnt self.rank = rank } } extension Artist: CustomStringConvertible { public var description: String { return "Artist: { name: \(name) }" } } extension Artist: ResponseObjectSerializable, ResponseCollectionSerializable { public init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? [String: Any], let name = representation["artist"] as? String else { return nil } func urlForJSONKey(_ key: String) -> URL? { guard let urlString = representation[key] as? String else { return nil } return URL(string: urlString) } self.name = name self.thumbURL = urlForJSONKey("thumb_url_artist") self.cnt = representation["cnt"] as? Int self.rank = representation["rank"] as? Int } } extension Artist: Equatable { public static func == (lhs: Artist, rhs: Artist) -> Bool { return lhs.name == rhs.name } } extension Artist: Hashable { public var hashValue: Int { return name.hashValue } }
mit
1b9731ef21a47880f395ce1a4b89ea23
24.629032
78
0.597231
4.317935
false
false
false
false
JaSpa/swift
test/IRGen/generic_metatypes_arm.swift
3
16735
// RUN: %swift -Xllvm -new-mangling-for-tests -target armv7-apple-ios7.0 -module-name generic_metatypes -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s // RUN: %swift -Xllvm -new-mangling-for-tests -target arm64-apple-ios7.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s // RUN: %swift -Xllvm -new-mangling-for-tests -target armv7-apple-tvos9.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s // RUN: %swift -Xllvm -new-mangling-for-tests -target arm64-apple-tvos9.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s // RUN: %swift -Xllvm -new-mangling-for-tests -target armv7k-apple-watchos2.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s // REQUIRES: CODEGENERATOR=ARM // CHECK: define hidden %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]]) func genericTypeof<T>(_ x: T) -> T.Type { // CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* {{.*}}, %swift.type* [[TYPE]], i1 false) // CHECK: ret %swift.type* [[METATYPE]] return type(of: x) } struct Foo {} class Bar {} // CHECK: define hidden %swift.type* @_T017generic_metatypes27remapToSubstitutedMetatypes{{.*}}(%C17generic_metatypes3Bar*) {{.*}} { func remapToSubstitutedMetatypes(_ x: Foo, y: Bar) -> (Foo.Type, Bar.Type) { // CHECK: call %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture undef, %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: [[BAR_META:%.*]] = call %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[T0]]) // CHECK: ret %swift.type* [[BAR_META]] return (genericTypeof(x), genericTypeof(y)) } // CHECK: define hidden void @_T017generic_metatypes23remapToGenericMetatypesyyF() func remapToGenericMetatypes() { // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: call void @_T017generic_metatypes0A9Metatypes{{.*}}(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}} %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}} %swift.type* [[T0]]) genericMetatypes(Foo.self, Bar.self) } func genericMetatypes<T, U>(_ t: T.Type, _ u: U.Type) {} protocol Bas {} // CHECK: define hidden { %swift.type*, i8** } @_T017generic_metatypes14protocolTypeof{{.*}}(%P17generic_metatypes3Bas_* noalias nocapture dereferenceable({{.*}})) func protocolTypeof(_ x: Bas) -> Bas.Type { // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X:%.*]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]] // CHECK: [[BUFFER:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X]], i32 0, i32 0 // CHECK: [[METADATA_I8:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-32: [[VW_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_I8]], i32 -1 // CHECK-64: [[VW_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_I8]], i64 -1 // CHECK: [[VW:%.*]] = load i8**, i8*** [[VW_ADDR]] // CHECK: [[PROJECT_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VW]], i32 2 // CHECK-32: [[PROJECT_PTR:%.*]] = load i8*, i8** [[PROJECT_ADDR]], align 4 // CHECK-64: [[PROJECT_PTR:%.*]] = load i8*, i8** [[PROJECT_ADDR]], align 8 // CHECK-32: [[PROJECT:%.*]] = bitcast i8* [[PROJECT_PTR]] to %swift.opaque* ([12 x i8]*, %swift.type*)* // CHECK-64: [[PROJECT:%.*]] = bitcast i8* [[PROJECT_PTR]] to %swift.opaque* ([24 x i8]*, %swift.type*)* // CHECK-32: [[PROJECTION:%.*]] = call %swift.opaque* [[PROJECT]]([12 x i8]* [[BUFFER]], %swift.type* [[METADATA]]) // CHECK-64: [[PROJECTION:%.*]] = call %swift.opaque* [[PROJECT]]([24 x i8]* [[BUFFER]], %swift.type* [[METADATA]]) // CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* [[PROJECTION]], %swift.type* [[METADATA]], i1 true) // CHECK: [[T0:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X]], i32 0, i32 2 // CHECK-32: [[WTABLE:%.*]] = load i8**, i8*** [[T0]], align 4 // CHECK-64: [[WTABLE:%.*]] = load i8**, i8*** [[T0]], align 8 // CHECK: [[T0:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* [[METATYPE]], 0 // CHECK: [[T1:%.*]] = insertvalue { %swift.type*, i8** } [[T0]], i8** [[WTABLE]], 1 // CHECK: ret { %swift.type*, i8** } [[T1]] return type(of: x) } struct Zim : Bas {} class Zang : Bas {} // CHECK-LABEL: define hidden { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA3ZimVmF() #0 func metatypeErasure(_ z: Zim.Type) -> Bas.Type { // CHECK: ret { %swift.type*, i8** } {{.*}} @_T017generic_metatypes3ZimVMf, {{.*}} @_T017generic_metatypes3ZimVAA3BasAAWP return z } // CHECK-LABEL: define hidden { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA4ZangCmF(%swift.type*) #0 func metatypeErasure(_ z: Zang.Type) -> Bas.Type { // CHECK: [[RET:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* %0, 0 // CHECK: [[RET2:%.*]] = insertvalue { %swift.type*, i8** } [[RET]], i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T017generic_metatypes4ZangCAA3BasAAWP, i32 0, i32 0), 1 // CHECK: ret { %swift.type*, i8** } [[RET2]] return z } struct OneArg<T> {} struct TwoArgs<T, U> {} struct ThreeArgs<T, U, V> {} struct FourArgs<T, U, V, W> {} struct FiveArgs<T, U, V, W, X> {} func genericMetatype<A>(_ x: A.Type) {} // CHECK-LABEL: define hidden void @_T017generic_metatypes20makeGenericMetatypesyyF() {{.*}} { func makeGenericMetatypes() { // CHECK: call %swift.type* @_T017generic_metatypes6OneArgVyAA3FooVGMa() [[NOUNWIND_READNONE:#[0-9]+]] genericMetatype(OneArg<Foo>.self) // CHECK: call %swift.type* @_T017generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa() [[NOUNWIND_READNONE]] genericMetatype(TwoArgs<Foo, Bar>.self) // CHECK: call %swift.type* @_T017generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa() [[NOUNWIND_READNONE]] genericMetatype(ThreeArgs<Foo, Bar, Foo>.self) // CHECK: call %swift.type* @_T017generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa() [[NOUNWIND_READNONE]] genericMetatype(FourArgs<Foo, Bar, Foo, Bar>.self) // CHECK: call %swift.type* @_T017generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa() [[NOUNWIND_READNONE]] genericMetatype(FiveArgs<Foo, Bar, Foo, Bar, Foo>.self) } // CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes6OneArgVyAA3FooVGMa() [[NOUNWIND_READNONE_OPT:#[0-9]+]] // CHECK: call %swift.type* @_T017generic_metatypes6OneArgVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]] // CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes6OneArgVMa(%swift.type*) // CHECK: [[BUFFER:%.*]] = alloca { %swift.type* } // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.start // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type* }, { %swift.type* }* [[BUFFER]], i32 0, i32 0 // CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8* // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes6OneArgVMP {{.*}}, i8* [[BUFFER_PTR]]) // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.end // CHECK: ret %swift.type* [[METADATA]] // CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa() [[NOUNWIND_READNONE_OPT]] // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: call %swift.type* @_T017generic_metatypes7TwoArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]]) // CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes7TwoArgsVMa(%swift.type*, %swift.type*) // CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type* } // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.start // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0 // CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1 // CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes7TwoArgsVMP {{.*}}, i8* [[BUFFER_PTR]]) // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.end // CHECK: ret %swift.type* [[METADATA]] // CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa() [[NOUNWIND_READNONE_OPT]] // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: call %swift.type* @_T017generic_metatypes9ThreeArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE]] // CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes9ThreeArgsVMa(%swift.type*, %swift.type*, %swift.type*) // CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type* } // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.start // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0 // CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1 // CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2 // CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes9ThreeArgsVMP {{.*}}, i8* [[BUFFER_PTR]]) // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.end // CHECK: ret %swift.type* [[METADATA]] // CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa() [[NOUNWIND_READNONE_OPT]] // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: call %swift.type* @_T017generic_metatypes8FourArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]]) [[NOUNWIND_READNONE]] // CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes8FourArgsVMa(%swift.type*, %swift.type*, %swift.type*, %swift.type*) // CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type*, %swift.type* } // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.start // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0 // CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1 // CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2 // CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 3 // CHECK: store %swift.type* %3, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes8FourArgsVMP {{.*}}, i8* [[BUFFER_PTR]]) // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.end // CHECK: ret %swift.type* [[METADATA]] // CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa() [[NOUNWIND_READNONE_OPT]] // CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa() // CHECK: call %swift.type* @_T017generic_metatypes8FiveArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE]] // CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes8FiveArgsVMa(%swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type*) // CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* } // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.start // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0 // CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1 // CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2 // CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 3 // CHECK: store %swift.type* %3, %swift.type** [[BUFFER_ELT]] // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes8FiveArgsVMP {{.*}}, i8* [[BUFFER_PTR]]) // CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8* // CHECK: call void @llvm.lifetime.end // CHECK: ret %swift.type* [[METADATA]] // CHECK: attributes [[NOUNWIND_READNONE_OPT]] = { nounwind readnone "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu" // CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
apache-2.0
581e1a54bec1b7a30cb101f12f2a83d9
79.07177
309
0.638841
3.061094
false
false
false
false
lquigley/Game
Game/Game/Views/SKYGoButton.swift
1
1069
// // SKYGoButton.swift // Sky High // // Created by Luke Quigley on 2/19/15. // Copyright (c) 2015 VOKAL. All rights reserved. // import UIKit class SKYGoButton: UIButton { var centerCircle:UIView! var borderWidth:CGFloat = 10.0 override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clearColor() self.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) centerCircle = UIView() centerCircle.backgroundColor = UIColor.whiteColor() centerCircle.frame = CGRectMake(borderWidth, borderWidth, CGRectGetWidth(self.frame) - borderWidth * 2, CGRectGetHeight(self.frame) - borderWidth * 2) centerCircle.userInteractionEnabled = false centerCircle.layer.cornerRadius = CGRectGetHeight(self.centerCircle.frame) / 2 centerCircle.layer.borderWidth = borderWidth centerCircle.layer.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.1).CGColor self.addSubview(centerCircle) } }
mit
22e6d4ebc9492d3ed88200c94fcb3c8e
31.424242
158
0.684752
4.815315
false
false
false
false
devxoul/Drrrible
DrrribleTests/Sources/Views/ShotTileCellSpec.swift
1
2182
// // ShotTileCellTests.swift // Drrrible // // Created by Suyeol Jeon on 23/07/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import Nimble import Quick @testable import Drrrible final class ShotTileCellSpec: QuickSpec { override func spec() { var reactor: ShotCellReactor! var cell: ShotTileCell! beforeEach { reactor = ShotCellReactor(shot: ShotFixture.shot1) reactor.isStubEnabled = true cell = ShotTileCell() } it("has subviews") { let cell = ShotTileCell() expect(cell.cardView.superview) === cell.contentView expect(cell.imageView.superview) === cell.cardView expect(cell.gifLabel.superview) === cell.imageView } describe("a gif label") { beforeEach { cell.dependency = .stub() cell.reactor = reactor } context("when an image is animated") { it("is not hidden") { reactor.stub.state.value.isAnimatedImage = true expect(cell.gifLabel.isHidden) == false } } context("when an image is not animated") { it("is hidden") { reactor.stub.state.value.isAnimatedImage = false expect(cell.gifLabel.isHidden) == true } } } describe("a card view") { context("when taps") { it("navigates to a shot view controller") { var isShotViewControllerFactoryExecuted = false cell.dependency = .stub( shotViewControllerFactory: { id, shot in isShotViewControllerFactoryExecuted = true let reactor = ShotViewReactor.stub(shotID: id) reactor.isStubEnabled = true return ShotViewController( reactor: reactor, analytics: .stub(), shotSectionDelegateFactory: { .stub() } ) } ) cell.reactor = reactor let gestureRecognizer = cell.cardView.gestureRecognizers?.lazy.compactMap { $0 as? UITapGestureRecognizer }.first gestureRecognizer?.sendAction(withState: .ended) expect(isShotViewControllerFactoryExecuted) == true } } } } }
mit
fa8d15f7b6a3866a48096ac5acb8fb84
27.697368
123
0.600183
4.496907
false
false
false
false
pcperini/Thrust
Thrust/Source/UIView+AnimationExtensions.swift
1
3620
// // UIView+AnimationExtensions.swift // Thrust // // Created by Patrick Perini on 9/14/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation import UIKit /** Animate changes to one or more views using the specified duration, delay, options, and completion handler. This method initiates a set of animations to perform on the view. The block object in the animations parameter contains the code for animating the properties of one or more views. During an animation, user interactions are temporarily disabled for the views being animated. If you want users to be able to interact with the views, include the UIViewAnimationOptionAllowUserInteraction constant in the options parameter. This function is queue-safe, as it will always execute on the main queue. :param: duration The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them. :param: delay The amount of time (measured in seconds) to wait before beginning the animations. Specify a value of 0 to begin the animations immediately. :param: options A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions. :param: animations A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. :param: completion A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. */ func animate(#duration: NSTimeInterval, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions.allZeros, #animations: () -> Void, completion: ((finished: Bool) -> Void)? = nil) { on (Queue.main) { UIView.animateWithDuration(duration, delay: delay, options: options, animations: animations, completion: completion) } } /// Overloads animate() to allow for Any-returning animations(). func animate(#duration: NSTimeInterval, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions.allZeros, #animations: () -> Any, completion: ((finished: Bool) -> Void)? = nil) { animate(duration: duration, delay: delay, options: options, animations: {animations(); return}, completion: completion) } /// Overloads animate() to allow for Any-returning completion(). func animate(#duration: NSTimeInterval, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions.allZeros, #animations: () -> Void, completion: ((finished: Bool) -> Any)? = nil) { animate(duration: duration, delay: delay, options: options, animations: animations, completion: {completion?(finished: $0); return}) } /// Overloads animate() to allow for Any-returning animations() and completion(). func animate(#duration: NSTimeInterval, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions.allZeros, #animations: () -> Any, completion: ((finished: Bool) -> Any)? = nil) { animate(duration: duration, delay: delay, options: options, animations: {animations(); return}, completion: {completion?(finished: $0); return}) }
mit
3d064dc05f914a85fff5d0706e4ecefd
55.5625
362
0.737845
4.801061
false
false
false
false
cornerstonecollege/402
Jorge_Juri/Mi_Ejemplo/GestureRecognizers/CustomViews/ViewController.swift
2
1384
// // ViewController.swift // CustomViews // // Created by Luiz on 2016-10-13. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let frame = CGRect(x: 0, y: 50, width: 100, height: 100) let view1 = FirstCustomView(frame: frame) self.view.addSubview(view1) let frame2 = CGRect(x: 200, y: 50, width: 100, height: 100) let view2 = FirstCustomView(frame: frame2) self.view.addSubview(view2) let frame3 = CGRect(x: 0, y: 0, width: 200, height: 250) let view3 = FirstCustomView(frame: frame3) view3.center = self.view.center self.view.addSubview(view3) let circleFrame = CGRect(x: 100, y: 100, width: 100, height: 100) let circle = CircleView(frame: circleFrame) //circle.backgroundColor = UIColor.yellow self.view.addSubview(circle) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didPanGesture(_ pan: UIPanGestureRecognizer) { pan.view!.center = pan.location(in: self.view) } }
gpl-3.0
8e4e6751cf4b53edd24e64b54184e72a
29.065217
80
0.625452
4.128358
false
false
false
false
haawa799/WaniKit2
Sources/WaniKit/Apple NSOperation/Convenience extensions/UIUserNotifications+Operations.swift
2
1712
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A convenient extension to UIKit.UIUserNotificationSettings. */ import Foundation #if os(iOS) import UIKit extension UIUserNotificationSettings { /// Check to see if one Settings object is a superset of another Settings object. func contains(settings: UIUserNotificationSettings) -> Bool { // our types must contain all of the other types if !types.contains(settings.types) { return false } let otherCategories = settings.categories ?? [] let myCategories = categories ?? [] return myCategories.isSupersetOf(otherCategories) } /** Merge two Settings objects together. `UIUserNotificationCategories` with the same identifier are considered equal. */ func settingsByMerging(settings: UIUserNotificationSettings) -> UIUserNotificationSettings { let mergedTypes = types.union(settings.types) let myCategories = categories ?? [] var existingCategoriesByIdentifier = Dictionary(sequence: myCategories) { $0.identifier } let newCategories = settings.categories ?? [] let newCategoriesByIdentifier = Dictionary(sequence: newCategories) { $0.identifier } for (newIdentifier, newCategory) in newCategoriesByIdentifier { existingCategoriesByIdentifier[newIdentifier] = newCategory } let mergedCategories = Set(existingCategoriesByIdentifier.values) return UIUserNotificationSettings(forTypes: mergedTypes, categories: mergedCategories) } } #endif
mit
76f7dd5d74b725f73ec92d72bdffd1c5
32.529412
97
0.688889
5.662252
false
false
false
false
imex94/KCLTech-iOS-2015
Hackalendar/Hackalendar/Hackalendar/HCHackathonTableViewController.swift
1
5140
// // HTLHackathonTableViewController.swift // HackTheList // // Created by Alex Telek on 03/11/2015. // Copyright © 2015 Alex Telek. All rights reserved. // import UIKit class HCHackathonTableViewController: UITableViewController, HCHackathonTableViewDelegate { var selectedRow = 0 var hackathons = [HackathonItem]() var currentYear = HCCalendarUtility.getCurrentYear() var currentMonth = HCCalendarUtility.getCurrentMonth() override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "HCHackathonTableViewCell", bundle: nil), forCellReuseIdentifier: "hackathonCell") self.navigationController?.navigationBar.topItem?.title = "Hackathons" hackathons = HCHackathonProvider.loadHackathons(currentYear, month: currentMonth) if hackathons.count == 0 { fetchData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func fetchData() { print("Year: \(currentYear), Month: \(currentMonth)") HCHackathonProvider.provideHackathonsFor(currentYear, month: currentMonth) { (hackathons) -> Void in self.hackathons.appendContentsOf(hackathons) self.locateHackathons() self.tableView.reloadData() } } func locateHackathons() { for hackathon in hackathons { HCLocationUtility.locateCityForLocationName(hackathon.city, completitionHandler: { (coordinate) -> Void in if let location = coordinate { hackathon.latitude = location.latitude hackathon.longitude = location.longitude // Save context again as we changed the managed object's latitude and longitude HCDataManager.saveContext() } self.tableView.reloadData() }) } } // MARK: - Table view data source override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 260.0 } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hackathons.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("hackathonCell", forIndexPath: indexPath) as! HCHackathonTableViewCell cell.delegate = self let currentHackathon = hackathons[indexPath.row] cell.tag = indexPath.row cell.hackathonName.text = currentHackathon.title cell.hackathonDate.text = currentHackathon.startDate cell.HackathonPlace.text = HCLocationUtility.extractCityNameFromLocation(currentHackathon.city) cell.addLocation(currentHackathon.latitude?.doubleValue, longitude: currentHackathon.longitude?.doubleValue) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // This was missing from the previous code, clicking on the transparent view // passed the same hackathon name to the detail view - Now it is fixed selectedRow = indexPath.row performSegueWithIdentifier("showDetails", sender: self) tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "Delete") { (rowAction, indexPath) -> Void in tableView.editing = false } return [deleteAction] } // MARK: - HTLHackathonTableViewDelegate func performSegueOnMapClick(index: Int) { selectedRow = index performSegueWithIdentifier("showDetails", sender: self) } // MARK: - Navigation /** In a storyboard-based application, you will often want to do a little preparation before navigation Get the new view controller using segue.destinationViewController. Pass the selected object to the new view controller. */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destinationViewController = segue.destinationViewController as! HCHackathonDetailViewController destinationViewController.title = hackathons[selectedRow].title // Passing the hackathon object to the detail view destinationViewController.hackathon = hackathons[selectedRow] } }
mit
6dc2d575b494c0d34a7b1dc05b976bb2
33.489933
146
0.652851
5.591948
false
false
false
false
danielmartin/swift
stdlib/public/core/UnicodeScalar.swift
1
14973
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Unicode.Scalar Type //===----------------------------------------------------------------------===// extension Unicode { /// A Unicode scalar value. /// /// The `Unicode.Scalar` type, representing a single Unicode scalar value, is /// the element type of a string's `unicodeScalars` collection. /// /// You can create a `Unicode.Scalar` instance by using a string literal that /// contains a single character representing exactly one Unicode scalar value. /// /// let letterK: Unicode.Scalar = "K" /// let kim: Unicode.Scalar = "김" /// print(letterK, kim) /// // Prints "K 김" /// /// You can also create Unicode scalar values directly from their numeric /// representation. /// /// let airplane = Unicode.Scalar(9992) /// print(airplane) /// // Prints "✈︎" @_fixed_layout public struct Scalar { @inlinable internal init(_value: UInt32) { self._value = _value } @usableFromInline internal var _value: UInt32 } } extension Unicode.Scalar : _ExpressibleByBuiltinUnicodeScalarLiteral, ExpressibleByUnicodeScalarLiteral { /// A numeric representation of the Unicode scalar. @inlinable public var value: UInt32 { return _value } @_transparent public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self._value = UInt32(value) } /// Creates a Unicode scalar with the specified value. /// /// Do not call this initializer directly. It may be used by the compiler /// when you use a string literal to initialize a `Unicode.Scalar` instance. /// /// let letterK: Unicode.Scalar = "K" /// print(letterK) /// // Prints "K" /// /// In this example, the assignment to the `letterK` constant is handled by /// this initializer behind the scenes. @_transparent public init(unicodeScalarLiteral value: Unicode.Scalar) { self = value } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of an emoji character: /// /// let codepoint: UInt32 = 127881 /// let emoji = Unicode.Scalar(codepoint) /// print(emoji!) /// // Prints "🎉" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value---that is, /// if `v` is in the range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is /// an invalid Unicode scalar value, the result is `nil`. @inlinable public init?(_ v: UInt32) { // Unicode 6.3.0: // // D9. Unicode codespace: A range of integers from 0 to 10FFFF. // // D76. Unicode scalar value: Any Unicode code point except // high-surrogate and low-surrogate code points. // // * As a result of this definition, the set of Unicode scalar values // consists of the ranges 0 to D7FF and E000 to 10FFFF, inclusive. if (v < 0xD800 || v > 0xDFFF) && v <= 0x10FFFF { self._value = v return } // Return nil in case of an invalid unicode scalar value. return nil } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"밥"`, the Korean word for rice: /// /// let codepoint: UInt16 = 48165 /// let bap = Unicode.Scalar(codepoint) /// print(bap!) /// // Prints "밥" /// /// In case of an invalid input value, the result is `nil`. /// /// let codepoint: UInt16 = extValue // This might be an invalid value /// if let bap = Unicode.Scalar(codepoint) { /// print(bap) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value, in the /// range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is an invalid /// unicode scalar value, the result is `nil`. @inlinable public init?(_ v: UInt16) { self.init(UInt32(v)) } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"7"`: /// /// let codepoint: UInt8 = 55 /// let seven = Unicode.Scalar(codepoint) /// print(seven) /// // Prints "7" /// /// - Parameter v: The code point to use for the scalar. @inlinable public init(_ v: UInt8) { self._value = UInt32(v) } /// Creates a duplicate of the given Unicode scalar. @inlinable public init(_ v: Unicode.Scalar) { // This constructor allows one to provide necessary type context to // disambiguate between function overloads on 'String' and 'Unicode.Scalar'. self = v } /// Returns a string representation of the Unicode scalar. /// /// Scalar values representing characters that are normally unprintable or /// that otherwise require escaping are escaped with a backslash. /// /// let tab = Unicode.Scalar(9) /// print(tab) /// // Prints " " /// print(tab.escaped(asASCII: false)) /// // Prints "\t" /// /// When the `forceASCII` parameter is `true`, a `Unicode.Scalar` instance /// with a value greater than 127 is represented using an escaped numeric /// value; otherwise, non-ASCII characters are represented using their /// typical string value. /// /// let bap = Unicode.Scalar(48165) /// print(bap.escaped(asASCII: false)) /// // Prints "밥" /// print(bap.escaped(asASCII: true)) /// // Prints "\u{BC25}" /// /// - Parameter forceASCII: Pass `true` if you need the result to use only /// ASCII characters; otherwise, pass `false`. /// - Returns: A string representation of the scalar. public func escaped(asASCII forceASCII: Bool) -> String { func lowNibbleAsHex(_ v: UInt32) -> String { let nibble = v & 15 if nibble < 10 { return String(Unicode.Scalar(nibble+48)!) // 48 = '0' } else { return String(Unicode.Scalar(nibble-10+65)!) // 65 = 'A' } } if self == "\\" { return "\\\\" } else if self == "\'" { return "\\\'" } else if self == "\"" { return "\\\"" } else if _isPrintableASCII { return String(self) } else if self == "\0" { return "\\0" } else if self == "\n" { return "\\n" } else if self == "\r" { return "\\r" } else if self == "\t" { return "\\t" } else if UInt32(self) < 128 { return "\\u{" + lowNibbleAsHex(UInt32(self) >> 4) + lowNibbleAsHex(UInt32(self)) + "}" } else if !forceASCII { return String(self) } else if UInt32(self) <= 0xFFFF { var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } else { // FIXME: Type checker performance prohibits this from being a // single chained "+". var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 28) result += lowNibbleAsHex(UInt32(self) >> 24) result += lowNibbleAsHex(UInt32(self) >> 20) result += lowNibbleAsHex(UInt32(self) >> 16) result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } } /// A Boolean value indicating whether the Unicode scalar is an ASCII /// character. /// /// ASCII characters have a scalar value between 0 and 127, inclusive. For /// example: /// /// let canyon = "Cañón" /// for scalar in canyon.unicodeScalars { /// print(scalar, scalar.isASCII, scalar.value) /// } /// // Prints "C true 67" /// // Prints "a true 97" /// // Prints "ñ false 241" /// // Prints "ó false 243" /// // Prints "n true 110" @inlinable public var isASCII: Bool { return value <= 127 } // FIXME: Unicode makes this interesting. internal var _isPrintableASCII: Bool { return (self >= Unicode.Scalar(0o040) && self <= Unicode.Scalar(0o176)) } } extension Unicode.Scalar : CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the Unicode scalar. @inlinable public var description: String { return String(self) } /// An escaped textual representation of the Unicode scalar, suitable for /// debugging. public var debugDescription: String { return "\"\(escaped(asASCII: true))\"" } } extension Unicode.Scalar : LosslessStringConvertible { @inlinable public init?(_ description: String) { let scalars = description.unicodeScalars guard let v = scalars.first, scalars.count == 1 else { return nil } self = v } } extension Unicode.Scalar : Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.value) } } extension Unicode.Scalar { /// Creates a Unicode scalar with the specified numeric value. /// /// - Parameter v: The Unicode code point to use for the scalar. `v` must be /// a valid Unicode scalar value, in the ranges `0...0xD7FF` or /// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is /// returned. /// /// For example, the following code sample creates a `Unicode.Scalar` instance /// with a value of an emoji character: /// /// let codepoint = 127881 /// let emoji = Unicode.Scalar(codepoint) /// print(emoji) /// // Prints "🎉" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value. /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } @inlinable public init?(_ v: Int) { if let us = Unicode.Scalar(UInt32(v)) { self = us } else { return nil } } } extension UInt8 { /// Construct with value `v.value`. /// /// - Precondition: `v.value` can be represented as ASCII (0..<128). @inlinable public init(ascii v: Unicode.Scalar) { _precondition(v.value < 128, "Code point value does not fit into ASCII") self = UInt8(v.value) } } extension UInt32 { /// Construct with value `v.value`. @inlinable public init(_ v: Unicode.Scalar) { self = v.value } } extension UInt64 { /// Construct with value `v.value`. @inlinable public init(_ v: Unicode.Scalar) { self = UInt64(v.value) } } extension Unicode.Scalar : Equatable { @inlinable public static func == (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value == rhs.value } } extension Unicode.Scalar : Comparable { @inlinable public static func < (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value < rhs.value } } extension Unicode.Scalar { @_fixed_layout public struct UTF16View { @inlinable internal init(value: Unicode.Scalar) { self.value = value } @usableFromInline internal var value: Unicode.Scalar } @inlinable public var utf16: UTF16View { return UTF16View(value: self) } } extension Unicode.Scalar.UTF16View : RandomAccessCollection { public typealias Indices = Range<Int> /// The position of the first code unit. @inlinable public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the collection is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { return 0 + UTF16.width(value) } /// Accesses the code unit at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. @inlinable public subscript(position: Int) -> UTF16.CodeUnit { return position == 0 ? ( endIndex == 1 ? UTF16.CodeUnit(value.value) : UTF16.leadSurrogate(value) ) : UTF16.trailSurrogate(value) } } extension Unicode.Scalar { internal static var _replacementCharacter: Unicode.Scalar { return Unicode.Scalar(_value: UTF32._replacementCodeUnit) } } extension Unicode.Scalar { /// Creates an instance of the NUL scalar value. @available(*, unavailable, message: "use 'Unicode.Scalar(0)'") public init() { Builtin.unreachable() } } // Access the underlying code units extension Unicode.Scalar { // Access the scalar as encoded in UTF-16 internal func withUTF16CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt16>) throws -> Result ) rethrows -> Result { var codeUnits: (UInt16, UInt16) = (self.utf16[0], 0) let utf16Count = self.utf16.count if utf16Count > 1 { _internalInvariant(utf16Count == 2) codeUnits.1 = self.utf16[1] } return try Swift.withUnsafePointer(to: &codeUnits) { return try $0.withMemoryRebound(to: UInt16.self, capacity: 2) { return try body(UnsafeBufferPointer(start: $0, count: utf16Count)) } } } // Access the scalar as encoded in UTF-8 @inlinable internal func withUTF8CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { let encodedScalar = UTF8.encode(self)! var (codeUnits, utf8Count) = encodedScalar._bytes return try Swift.withUnsafePointer(to: &codeUnits) { return try $0.withMemoryRebound(to: UInt8.self, capacity: 4) { return try body(UnsafeBufferPointer(start: $0, count: utf8Count)) } } } }
apache-2.0
5979e4a76a4980a81b006eac1dc3042d
29.886364
82
0.614824
3.915401
false
false
false
false
nicolastinkl/swift
ListerAProductivityAppBuiltinSwift/Lister/AppDelegate.swift
1
4337
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The application delegate. */ import UIKit import ListerKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow! struct MainStoryboard { static let name = "Main" struct Identifiers { static let emptyViewController = "emptyViewController" } } // MARK: View Controller Accessor Convenience // The root view controller of the window will always be a UISplitViewController. This is setup in the main storyboard. var splitViewController: UISplitViewController { return window.rootViewController as UISplitViewController } // The primary view controller of the split view controller defined in the main storyboard. var primaryViewController: UINavigationController { return splitViewController.viewControllers[0] as UINavigationController } // The view controller that displays the list of documents. If it's not visible, then this value is nil. var listDocumentsViewController: ListDocumentsViewController? { return primaryViewController.topViewController as? ListDocumentsViewController } // MARK: UIApplicationDelegate func application(UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary) -> Bool { AppConfiguration.sharedConfiguration.runHandlerOnFirstLaunch { ListCoordinator.sharedListCoordinator.copyInitialDocuments() } splitViewController.preferredDisplayMode = .AllVisible splitViewController.delegate = self return true } // MARK: UISplitViewControllerDelegate func targetDisplayModeForActionInSplitViewController(_: UISplitViewController) -> UISplitViewControllerDisplayMode { return .AllVisible } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController _: UIViewController) -> Bool { splitViewController.preferredDisplayMode = .Automatic // If there's a list that's currently selected in separated mode and we want to show it in collapsed mode, we'll transfer over the view controller's settings. if let secondaryViewController = secondaryViewController as? UINavigationController { primaryViewController.navigationBar.titleTextAttributes = secondaryViewController.navigationBar.titleTextAttributes primaryViewController.navigationBar.tintColor = secondaryViewController.navigationBar.tintColor primaryViewController.toolbar.tintColor = secondaryViewController.toolbar.tintColor primaryViewController.showDetailViewController(secondaryViewController.topViewController, sender: nil) } return true } func splitViewController(splitViewController: UISplitViewController, separateSecondaryViewControllerFromPrimaryViewController _: UIViewController) -> UIViewController? { // If no list is on the stack, fill the detail area with an empty controller. if primaryViewController.topViewController === primaryViewController.viewControllers[0] { let storyboard = UIStoryboard(name: MainStoryboard.name, bundle: nil) return storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.Identifiers.emptyViewController) as? UIViewController } let textAttributes = primaryViewController.navigationBar.titleTextAttributes let tintColor = primaryViewController.navigationBar.tintColor let poppedViewController = primaryViewController.popViewControllerAnimated(false) let navigationViewController = UINavigationController(rootViewController: poppedViewController) navigationViewController.navigationBar.titleTextAttributes = textAttributes navigationViewController.navigationBar.tintColor = tintColor navigationViewController.toolbar.tintColor = tintColor return navigationViewController } }
mit
fdf932467396b1e9f1d59fbd28d45833
44.15625
204
0.737255
7.285714
false
false
false
false
cnoon/swift-compiler-crashes
crashes-duplicates/05843-swift-type-walk.swift
11
270
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { struct c<T.B == e: e: A? { let end = B<T where T.Element == "\() -> Void{ class B<T : B<T>()
mit
a6eb2be725e86b9a3d178602470d8297
32.75
87
0.67037
3.333333
false
true
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Expectation.swift
174
2470
import Foundation internal func expressionMatches<T, U where U: Matcher, U.ValueType == T>(expression: Expression<T>, matcher: U, to: String, description: String?) -> (Bool, FailureMessage) { let msg = FailureMessage() msg.userDescription = description msg.to = to do { let pass = try matcher.matches(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(try expression.evaluate()))>" } return (pass, msg) } catch let error { msg.actualValue = "an unexpected error thrown: <\(error)>" return (false, msg) } } internal func expressionDoesNotMatch<T, U where U: Matcher, U.ValueType == T>(expression: Expression<T>, matcher: U, toNot: String, description: String?) -> (Bool, FailureMessage) { let msg = FailureMessage() msg.userDescription = description msg.to = toNot do { let pass = try matcher.doesNotMatch(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(try expression.evaluate()))>" } return (pass, msg) } catch let error { msg.actualValue = "an unexpected error thrown: <\(error)>" return (false, msg) } } public struct Expectation<T> { let expression: Expression<T> public func verify(pass: Bool, _ message: FailureMessage) { NimbleAssertionHandler.assert(pass, message: message, location: expression.location) } /// Tests the actual value using a matcher to match. public func to<U where U: Matcher, U.ValueType == T>(matcher: U, description: String? = nil) { let (pass, msg) = expressionMatches(expression, matcher: matcher, to: "to", description: description) verify(pass, msg) } /// Tests the actual value using a matcher to not match. public func toNot<U where U: Matcher, U.ValueType == T>(matcher: U, description: String? = nil) { let (pass, msg) = expressionDoesNotMatch(expression, matcher: matcher, toNot: "to not", description: description) verify(pass, msg) } /// Tests the actual value using a matcher to not match. /// /// Alias to toNot(). public func notTo<U where U: Matcher, U.ValueType == T>(matcher: U, description: String? = nil) { toNot(matcher, description: description) } // see: // - AsyncMatcherWrapper for extension // - NMBExpectation for Objective-C interface }
mit
3045830093638ed5624a4e5e6b634974
37.59375
181
0.641296
4.243986
false
false
false
false
exponent/exponent
packages/expo-modules-core/ios/Swift/Exceptions/Exception.swift
2
1949
// Copyright 2022-present 650 Industries. All rights reserved. open class Exception: CodedError, ChainableException, CustomStringConvertible, CustomDebugStringConvertible { open var name: String { return String(describing: Self.self) } /** String describing the reason of the exception. */ open var reason: String { "undefined reason" } /** The origin in code where the exception was created. */ open var origin: ExceptionOrigin /** The default initializer that captures the place in the code where the exception was created. - Warning: Call it only without arguments! */ public init(file: String = #fileID, line: UInt = #line, function: String = #function) { self.origin = ExceptionOrigin(file: file, line: line, function: function) } // MARK: ChainableException open var cause: Error? // MARK: CustomStringConvertible open var description: String { return concatDescription(reason, withCause: cause, debug: false) } // MARK: CustomDebugStringConvertible open var debugDescription: String { let debugDescription = "\(name): \(reason) (at \(origin.file):\(origin.line))" return concatDescription(debugDescription, withCause: cause, debug: true) } } /** Concatenates the exception description with its cause description. */ private func concatDescription(_ description: String, withCause cause: Error?, debug: Bool = false) -> String { let causeSeparator = "\n→ Caused by: " switch cause { case let cause as Exception: return description + causeSeparator + (debug ? cause.debugDescription : cause.description) case let cause as CodedError: // `CodedError` is deprecated but we need to provide backwards compatibility as some modules already used it. return description + causeSeparator + cause.description case let cause?: return description + causeSeparator + cause.localizedDescription default: return description } }
bsd-3-clause
6f9e58ac93d95e81d9a18044cd24f09d
30.403226
113
0.72265
4.624703
false
false
false
false
box/box-ios-sdk
Sources/Network/PagingIterator.swift
1
7188
// // PagingIterator.swift // BoxSDK-iOS // // Created by Matthew Willer, Albert Wu. // Copyright © 2019 box. All rights reserved. // import Foundation /// Stores offset, marker or stream position for the iterator public enum PagingParameter { /// Offset case offset(Int) /// Marker case marker(String?) /// Stream position case streamPosition(String?) var asQueryParams: QueryParameters { switch self { case let .offset(offset): return ["offset": offset] case let .marker(marker): return ["marker": marker] case let .streamPosition(streamPosition): return ["stream_position": streamPosition] } } } /// Provides paged iterator access for a collection of BoxModel's public class PagingIterator<Element: BoxModel> { private let client: BoxClient /// Gets offset, marker or stream position for the next page private var nextPage: PagingParameter? private var isDone: Bool private var isStreamEmpty: Bool private let url: URL private let headers: BoxHTTPHeaders private var queryParams: QueryParameters private var dispatchQueue: DispatchQueue private var nextPageQueue: [Callback<EntryContainer<Element>>] = [] /// The total count of the result set, if known public private(set) var totalCount: Int? /// Initializer /// /// - Parameters: /// - client: A BoxClient that will be used for any API calls the iterator makes internally in order to get more data. /// - url: The endpoint from which to get pages, using HTTP GET. /// - queryParams: The query parameters for the initial page. Paging parameters are updated for subsequent pages. /// - headers: The HTTP headers to send with each request (authorization is handled by the client). init(client: BoxClient, url: URL, queryParameters: QueryParameters, headers: BoxHTTPHeaders = [:]) { self.client = client self.url = url self.headers = headers.filter { $0.key.lowercased() != "authorization" } queryParams = queryParameters isDone = false isStreamEmpty = false dispatchQueue = DispatchQueue(label: "com.box.swiftsdk.pagingiterator", qos: .userInitiated) } /// Update internal paging parameters to be used for the next API call private func updatePaging(page: EntryContainer<Element>) { // Update total count if available if let totalCountFromPage = page.totalCount { totalCount = totalCountFromPage } // Handle offset-based paging if let previousOffset = page.offset { let limit = page.limit ?? page.entries.count nextPage = .offset(previousOffset + limit) if let totalCount = totalCount { isDone = previousOffset + limit > totalCount } else { isDone = page.entries.isEmpty } } // Handle stream position paging else if let nextStreamPosition = page.nextStreamPosition { if page.entries.isEmpty { isStreamEmpty = true } nextPage = .streamPosition(nextStreamPosition) } // Handle marker based paging else if let nextPageMarker = page.nextMarker { nextPage = .marker(nextPageMarker) } // Handle unexpected value with no paging information else { // Default to a finished marker collection when there's no field present, // since some endpoints indicate completed paging this way nextPage = .marker(nil) isDone = true } if let updatedParams = nextPage?.asQueryParams { queryParams = queryParams.merging(updatedParams) { _, right in right } } } /// Gets next page of elements from the iterator /// /// - Parameter completion: Returns either the next page of elements or an error. /// If the iterator has no more elements, a BoxSDKError with a /// message of BoxSDKErrorEnum.endOfList is passed to the completion. public func next(completion: @escaping Callback<EntryContainer<Element>>) { dispatchQueue.async { // 1. Return end-failure if iterator is done if self.isDone { completion(.failure(BoxSDKError(message: .endOfList))) return } // 2. If a completion queue is already set up, that means another page of results // is already on its way; we can just wait for it to arrive by adding this completion // to the completion queue guard self.nextPageQueue.isEmpty else { self.nextPageQueue.append(completion) return } // 3. There are no more results in the buffer and we need to request more from the API // 3a. Set up the completion queue and insert this completion as the first item, // so subsequent requests can queue behind this one self.nextPageQueue = [completion] // 3b. Get the next page of results from the API and load them into the buffer self.getData() } } /// Get the next page of items from the API private func getData() { client.get( url: url, httpHeaders: headers, queryParameters: queryParams ) { result in // Add an item on the dispatch queue to process the new page of results; this guarantees // that any previous calls to next() have already been added to the completion queue self.dispatchQueue.async { let pageResult: Result<EntryContainer<Element>, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } let queuedCompletion = self.nextPageQueue.removeFirst() queuedCompletion(pageResult) switch pageResult { case let .success(page): // Update paging parameters for next API call self.updatePaging(page: page) if self.isDone || self.isStreamEmpty { for queuedCompletion in self.nextPageQueue { queuedCompletion(.failure(BoxSDKError(message: .endOfList))) } self.nextPageQueue = [] return } if !self.nextPageQueue.isEmpty { self.getData() return } case let .failure(error): // If an API call fails completely, pass the error to all waiting completions for queuedCompletion in self.nextPageQueue { queuedCompletion(.failure(error)) } // Clear the completion queue so future calls to next() can retry self.nextPageQueue = [] } } } } }
apache-2.0
f02b3515e002a5485cde8074eeb68a53
36.432292
124
0.589954
5.296242
false
false
false
false
HongliYu/firefox-ios
Client/Extensions/UIImageViewExtensions.swift
1
3589
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import SDWebImage import Shared public extension UIImageView { public func setIcon(_ icon: Favicon?, forURL url: URL?, completed completion: ((UIColor, URL?) -> Void)? = nil ) { func finish(filePath: String?, bgColor: UIColor) { if let filePath = filePath { self.image = UIImage(contentsOfFile: filePath) } // If the background color is clear, we may decide to set our own background based on the theme. let color = bgColor.components.alpha < 0.01 ? UIColor.theme.general.faviconBackground : bgColor self.backgroundColor = color completion?(color, url) } if let url = url, let defaultIcon = FaviconFetcher.getDefaultIconForURL(url: url) { finish(filePath: defaultIcon.url, bgColor: defaultIcon.color) } else { let imageURL = URL(string: icon?.url ?? "") let defaults = defaultFavicon(url) self.sd_setImage(with: imageURL, placeholderImage: defaults.image, options: []) {(img, err, _, _) in guard let image = img, let dUrl = url, err == nil else { finish(filePath: nil, bgColor: defaults.color) return } self.color(forImage: image, andURL: dUrl) { color in finish(filePath: nil, bgColor: color) } } } } /* * Fetch a background color for a specfic favicon UIImage. It uses the URL to store the UIColor in memory for subsequent requests. */ private func color(forImage image: UIImage, andURL url: URL, completed completionBlock: ((UIColor) -> Void)? = nil) { guard let domain = url.baseDomain else { self.backgroundColor = UIColor.Photon.Grey50 completionBlock?(UIColor.Photon.Grey50) return } if let color = FaviconFetcher.colors[domain] { self.backgroundColor = color completionBlock?(color) } else { image.getColors(scaleDownSize: CGSize(width: 25, height: 25)) {colors in let isSame = [colors.primary, colors.secondary, colors.detail].every { $0 == colors.primary } if isSame { completionBlock?(UIColor.Photon.White100) FaviconFetcher.colors[domain] = UIColor.Photon.White100 } else { completionBlock?(colors.background) FaviconFetcher.colors[domain] = colors.background } } } } public func setFavicon(forSite site: Site, onCompletion completionBlock: ((UIColor, URL?) -> Void)? = nil ) { self.setIcon(site.icon, forURL: site.tileURL, completed: completionBlock) } private func defaultFavicon(_ url: URL?) -> (image: UIImage, color: UIColor) { if let url = url { return (FaviconFetcher.getDefaultFavicon(url), FaviconFetcher.getDefaultColor(url)) } else { return (FaviconFetcher.defaultFavicon, .white) } } } open class ImageOperation: NSObject, SDWebImageOperation { open var cacheOperation: Operation? var cancelled: Bool { return cacheOperation?.isCancelled ?? false } @objc open func cancel() { cacheOperation?.cancel() } }
mpl-2.0
49662c6abaa090a7be0dd39b7e51b30d
38.43956
133
0.59766
4.734828
false
false
false
false
PD-Jell/Swift_study
SwiftStudy/SwiftUI/SwiftUI-multiView/SwiftUIView.swift
1
4131
// // ContentView.swift // SwiftStudy // // Created by YooHG on 6/18/20. // Copyright © 2020 Jell PD. All rights reserved. // import SwiftUI //여성: 655 + (9.6 x 체중(kg)) + (1.8 x 신장(cm)) -(4.7 x 나이) //남성: 66 + (13.7 x 체중(kg)) + (5 x 신장(cm)) -(6.5 x 나이) //주로 좌식 생활을 하는 사람: BMR x 1.2 //약간 활동적인 사람 (주당 1일~3일 운동): BMR x 1.3 //보통 (주당 3일~5일 이상 운동): BMR x 1.5 //상당히 활동적인 사람 (매일 운동): BMR x 1.7 //매우 활동적(운동선수와 비슷한 강도로 매일 운동): BMR x 1.9 struct SwiftUIView: View { @ObservedObject var viewModel: SwiftUIViewModel @State var touchedCount = 0 @State var name = "0" let genderArr = ["남성", "여성", "무언가"] let actArr = [(key: "거의 안해요", value: 1.2), (key: "1~3일", value: 1.3), (key: "3~5일", value: 1.5), (key: "매일", value: 1.7), (key: "격하게 매일", value: 1.9)] @State var selectedAct = 0 @State var act: Double = 0.0 init(viewModel: SwiftUIViewModel) { self.viewModel = viewModel } var body: some View { NavigationView { Form { Section(header: Text("칼로리 계산")) { TextField("이름을 입력해주세요", text: $viewModel.name) Picker(selection: $viewModel.gender, label: Text("성별")) { ForEach(0 ..< genderArr.count) { Text(self.genderArr[$0]) } } TextField("신장을 입력해주세요", value: $viewModel.height, formatter: NumberFormatter()).keyboardType(.numberPad) TextField("체중을 입력해주세요", value: $viewModel.weight, formatter: NumberFormatter()).keyboardType(.numberPad) TextField("나이를 입력해주세요", value: $viewModel.age, formatter: NumberFormatter()).keyboardType(.numberPad) Picker(selection: $selectedAct, label: Text("일주일에 운동을 어느정도 하시나요?")) { ForEach(0 ..< actArr.count) { Text(self.actArr[$0].key) } } Text("\(actArr[selectedAct].value)") Text("\(viewModel.act)") NavigationLink(destination: SecondSwiftUIView(touchedCount: $viewModel.act)) { Text("계산하기") } } Section{ Text("버튼을 클릭한 횟수 \(touchedCount)") Button("this is a Button") { self.touchedCount += 1 } } HStack { Image(systemName: "goforward.90") NavigationLink(destination: SecondSwiftUIView(touchedCount: self.$touchedCount)) { Text("다음꺼") } } Section(header: Text("이름")){ TextField("이름을 입력해주세요", text: $name) } Section(header: Text("나이")){ TextField("나이를 입력해주세요", value: $viewModel.age, formatter: NumberFormatter()).keyboardType(.numberPad) } Section(header: Text("결과")){ Text("\(name)님의 나이는 \(viewModel.age)살입니다.") } // Group { // Text("hi?") // Text("hi?") // Text("hi?") // Text("hi?") // Text("hi?") // } }.navigationBarTitle("this is title") }.onAppear { print("view appeared") } } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { SwiftUIView(viewModel: SwiftUIViewModel()) } }
mit
eb71bd3295305c84981dea6d89ae8ccc
35
154
0.460086
3.462185
false
false
false
false
bettkd/Securus
Securus/TimelineTableViewController.swift
1
11026
// // TimelineTableViewController.swift // Securus // // Created by Dominic Bett on 11/30/15. // Copyright © 2015 DominicBett. All rights reserved. // import UIKit import Parse class TimelineTableViewController: UITableViewController { var timelineData = NSMutableArray() func loadData(){ timelineData.removeAllObjects() let findTimelineData:PFQuery = PFQuery(className: "Events") findTimelineData.findObjectsInBackgroundWithBlock{ (events, error)->Void in if error == nil{ for myEvent in events! { let event:PFObject = myEvent as! PFObject self.timelineData.addObject(event) } let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects self.timelineData = NSMutableArray(array: array) self.tableView.reloadData() } } } func refresh(sender:AnyObject) { loadData() self.refreshControl?.endRefreshing() } override func viewDidLoad() { super.viewDidLoad() // Refreshing timeline self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Check first if logged in override func viewWillAppear(animated: Bool) { if (PFUser.currentUser() == nil) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Login") self.presentViewController(viewController, animated: true, completion: nil) }) } } override func viewDidAppear(animated: Bool) { self.loadData() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return timelineData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: TimelineTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimelineTableViewCell // Retrieve data let event: PFObject = self.timelineData.objectAtIndex(indexPath.row) as! PFObject // Get username let findUser: PFQuery = PFUser.query()! //findUser.whereKey("objectId", equalTo: (PFUser.currentUser()?.objectId!)!) findUser.whereKey("objectId", equalTo: (event.valueForKey("user")?.objectId)!) findUser.findObjectsInBackgroundWithBlock{ (users, error)->Void in if error == nil{ cell.usernameText.text = users?.last?.username } } // DateTime let dateFormatter:NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" cell.dateTimeText.text = dateFormatter.stringFromDate(event.createdAt!) // Description cell.descriptionText.text = event.objectForKey("event") as! String // Vote Count cell.voteUp.tag = indexPath.row cell.voteUp.addTarget(self, action: "voteUp:", forControlEvents: .TouchUpInside) cell.voteDown.tag = indexPath.row cell.voteDown.addTarget(self, action: "voteDown:", forControlEvents: .TouchUpInside) cell.voteCountText.text = event.objectForKey("votes")?.stringValue UIView.animateWithDuration(0.2, animations: { cell.usernameText.alpha = 1 cell.dateTimeText.alpha = 1 cell.descriptionText.alpha = 1 cell.voteCountText.alpha = 1 }) // Configure the cell... return cell } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let event = self.timelineData.objectAtIndex(indexPath.row) as! PFObject let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete"){(action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in let query = PFQuery(className: "Events") query.whereKey("objectId", equalTo: event.objectId!) query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in if error == nil{ objects?.last!.deleteInBackground() } else { print (error) } usleep(200000) self.loadData() } } deleteAction.backgroundColor = UIColor.redColor() let query1 = PFQuery(className: "Events") query1.whereKey("user", equalTo: (event.objectId)!) query1.findObjectsInBackgroundWithBlock {(users, error) -> Void in if error == nil{ if users?.last!.objectId == PFUser.currentUser()?.objectId { print("Deleting someone else's stuff is illegal!") } } else { print (error) } } let viewMap = UITableViewRowAction(style: .Normal, title: "Map") {(action: UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in print("Will write code for map view") } return [deleteAction, viewMap] } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } @IBAction func voteUp(sender: AnyObject){ let event: PFObject = self.timelineData.objectAtIndex(sender.tag) as! PFObject let votes = (event.objectForKey("votes")?.integerValue)! + 1 let query = PFQuery(className: "Events") query.getObjectInBackgroundWithId(event.objectId!, block: {(object:PFObject?, error) -> Void in if error != nil { print(error) } else if let the_event = object{ the_event["votes"] = votes the_event.saveInBackground() usleep(100000) } }) refresh(self) } @IBAction func voteDown(sender: AnyObject){ let event: PFObject = self.timelineData.objectAtIndex(sender.tag) as! PFObject let votes = (event.objectForKey("votes")?.integerValue)! - 1 let query = PFQuery(className: "Events") query.getObjectInBackgroundWithId(event.objectId!, block: {(object:PFObject?, error) -> Void in if error != nil { print(error) } else if let the_event = object{ the_event["votes"] = votes the_event.saveInBackground() usleep(100000) } }) refresh(self) } @IBAction func postEvent(sender: AnyObject) { self.performSegueWithIdentifier("compose", sender: self) } @IBAction func logout(sender: AnyObject) { // Create the alert controller to confirm logout let alertController = UIAlertController(title: "Confirm logout", message: "Are you sure you want to logout?", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { UIAlertAction in // Send a request to log out a user PFUser.logOut() // Navigate to the Login Screen dispatch_async(dispatch_get_main_queue(), { () -> Void in let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Login") self.presentViewController(viewController, animated: true, completion: nil) }) print("Logged out!") } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in print("Logout Dismissed!") } alertController.addAction(okAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } // Allow next screen (create/post event) to navigate back to this screen @IBAction func unwindToTimelineScreen(segue:UIStoryboardSegue) { } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
2f0677381a22bcb813f4eeb259e7b644
37.414634
157
0.621134
5.46333
false
false
false
false
tzef/BmoViewPager
Example/BmoViewPager/MainViewController.swift
1
2711
// // MainViewController.swift // BmoViewPager // // Created by LEE ZHE YU on 2017/6/4. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import BmoViewPager class MainViewController: UIViewController { @IBOutlet weak var viewPager: BmoViewPager! override func viewDidLoad() { super.viewDidLoad() viewPager.dataSource = self viewPager.scrollable = false let navigationBar = BmoViewPagerNavigationBar(frame: CGRect(origin: .zero, size: .init(width: 200, height: 30))) self.navigationItem.titleView = navigationBar navigationBar.backgroundColor = UIColor.clear navigationBar.viewPager = viewPager } } extension MainViewController: BmoViewPagerDataSource { // Optional func bmoViewPagerDataSourceNaviagtionBarItemNormalAttributed(_ viewPager: BmoViewPager, navigationBar: BmoViewPagerNavigationBar, forPageListAt page: Int) -> [NSAttributedString.Key : Any]? { return [ NSAttributedString.Key.strokeWidth : 1.0, NSAttributedString.Key.strokeColor : UIColor.black, NSAttributedString.Key.foregroundColor : UIColor.groupTableViewBackground ] } func bmoViewPagerDataSourceNaviagtionBarItemHighlightedAttributed(_ viewPager: BmoViewPager, navigationBar: BmoViewPagerNavigationBar, forPageListAt page: Int) -> [NSAttributedString.Key : Any]? { return [ NSAttributedString.Key.foregroundColor : UIColor.black ] } func bmoViewPagerDataSourceNaviagtionBarItemTitle(_ viewPager: BmoViewPager, navigationBar: BmoViewPagerNavigationBar, forPageListAt page: Int) -> String? { return page == 0 ? "DEMO" : "ABOUT" } func bmoViewPagerDataSourceNaviagtionBarItemSize(_ viewPager: BmoViewPager, navigationBar: BmoViewPagerNavigationBar, forPageListAt page: Int) -> CGSize { return CGSize(width: navigationBar.bounds.width / 2, height: navigationBar.bounds.height) } // Required func bmoViewPagerDataSourceNumberOfPage(in viewPager: BmoViewPager) -> Int { return 2 } func bmoViewPagerDataSource(_ viewPager: BmoViewPager, viewControllerForPageAt page: Int) -> UIViewController { switch page { case 0: if let vc = storyboard?.instantiateViewController(withIdentifier: "DemoViewController") as? DemoViewController { return vc } case 1: if let vc = storyboard?.instantiateViewController(withIdentifier: "AboutViewController") as? AboutViewController { return vc } default: break } return UIViewController() } }
mit
3f15b9edb186c9f7c2e63166f9d2c890
39.41791
200
0.689808
5.033457
false
false
false
false
petrpavlik/AsyncChat
Chat/Classes/LoadingCellNode.swift
1
1037
// // LoadingCellNode.swift // Chat // // Created by Petr Pavlik on 03/10/15. // Copyright © 2015 Petr Pavlik. All rights reserved. // import UIKit import AsyncDisplayKit class LoadingCellNode: ASCellNode { private let loadingNode = ASDisplayNode { () -> UIView! in let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityIndicator.hidesWhenStopped = false return activityIndicator } override init!() { super.init() addSubnode(loadingNode) } override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { return CGSizeMake(constrainedSize.width, 44) } override func layout() { loadingNode.frame = CGRectMake((bounds.width-20)/2, (bounds.height-20)/2, 20, 20) } func startAnimating() { assert(NSThread.isMainThread()) let activityIndicator = loadingNode.view as! UIActivityIndicatorView activityIndicator.startAnimating() } }
mit
625bc98f2944a4391234715bd965f343
24.268293
89
0.653475
4.933333
false
false
false
false
VoIPGRID/vialer-ios
Vialer/Calling/Dialer/Controllers/DialerViewController.swift
1
9385
// // DialerViewController.swift // Copyright © 2017 VoIPGRID. All rights reserved. // import UIKit import AVFoundation class DialerViewController: UIViewController, SegueHandler { enum SegueIdentifier: String { case sipCalling = "SIPCallingSegue" case twoStepCalling = "TwoStepCallingSegue" case reachabilityBar = "ReachabilityBarSegue" } fileprivate struct Config { struct ReachabilityBar { static let animationDuration = 0.3 static let height: CGFloat = 30.0 } } // MARK: - Properties var numberText: String? { didSet { if let number = numberText { numberText = PhoneNumberUtils.cleanPhoneNumber(number) } numberLabel.text = numberText setupButtons() } } var sounds = [String: AVAudioPlayer]() var lastCalledNumber: String? { didSet { setupButtons() } } var user = SystemUser.current()! fileprivate let reachability = ReachabilityHelper.instance.reachability! fileprivate var notificationCenter = NotificationCenter.default fileprivate var reachabilityChanged: NotificationToken? fileprivate var sipDisabled: NotificationToken? fileprivate var sipChanged: NotificationToken? fileprivate var encryptionUsageChanged: NotificationToken? // MARK: - Outlets @IBOutlet weak var leftDrawerButton: UIBarButtonItem! @IBOutlet weak var numberLabel: PasteableUILabel! { didSet { numberLabel.delegate = self } } @IBOutlet weak var callButton: UIButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var reachabilityBarHeigthConstraint: NSLayoutConstraint! @IBOutlet weak var reachabilityBar: UIView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } } // MARK: - Lifecycle extension DialerViewController { override func viewDidLoad() { super.viewDidLoad() setupLayout() setupSounds() reachabilityChanged = notificationCenter.addObserver(descriptor: Reachability.changed) { [weak self] _ in self?.updateReachabilityBar() } sipDisabled = notificationCenter.addObserver(descriptor: SystemUser.sipDisabledNotification) { [weak self] _ in self?.updateReachabilityBar() } sipChanged = notificationCenter.addObserver(descriptor: SystemUser.sipChangedNotification) { [weak self] _ in self?.updateReachabilityBar() } encryptionUsageChanged = notificationCenter.addObserver(descriptor:SystemUser.encryptionUsageNotification) { [weak self] _ in self?.updateReachabilityBar() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateReachabilityBar() VialerGAITracker.trackScreenForController(name: controllerName) try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: AVAudioSession.Category.ambient.rawValue)) setupButtons() } } // MARK: - Actions extension DialerViewController { @IBAction func leftDrawerButtonPressed(_ sender: UIBarButtonItem) { mm_drawerController.toggle(.left, animated: true, completion: nil) } @IBAction func deleteButtonPressed(_ sender: UIButton) { if let number = numberText { numberText = String(number.dropLast()) setupButtons() } } @IBAction func deleteButtonLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { numberText = nil } } @IBAction func callButtonPressed(_ sender: UIButton) { guard numberText != nil else { numberText = lastCalledNumber return } lastCalledNumber = numberText if ReachabilityHelper.instance.connectionFastEnoughForVoIP() { VialerGAITracker.setupOutgoingSIPCallEvent() DispatchQueue.main.async { self.performSegue(segueIdentifier: .sipCalling) } } else { VialerGAITracker.setupOutgoingConnectABCallEvent() DispatchQueue.main.async { self.performSegue(segueIdentifier: .twoStepCalling) } } } @IBAction func numberPressed(_ sender: NumberPadButton) { numberPadPressed(character: sender.number) playSound(character: sender.number) } @IBAction func zeroButtonLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { playSound(character: "0") numberPadPressed(character: "+") } } } // MARK: - Segues extension DialerViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segueIdentifier(segue: segue) { case .sipCalling: let sipCallingVC = segue.destination as! SIPCallingViewController if (UIApplication.shared.delegate as! AppDelegate).isScreenshotRun { sipCallingVC.handleOutgoingCallForScreenshot(phoneNumber: numberText!) } else { sipCallingVC.handleOutgoingCall(phoneNumber: numberText!, contact: nil) } numberText = nil case .twoStepCalling: let twoStepCallingVC = segue.destination as! TwoStepCallingViewController twoStepCallingVC.handlePhoneNumber(numberText!) numberText = nil case .reachabilityBar: break } } } // MARK: - PasteableUILabelDelegate extension DialerViewController : PasteableUILabelDelegate { func pasteableUILabel(_ label: UILabel!, didReceivePastedText text: String!) { numberText = text } } // MARK: - Helper functions layout extension DialerViewController { fileprivate func setupUI() { title = NSLocalizedString("Keypad", comment: "Keypad") tabBarItem.image = UIImage(asset: .tabKeypad) tabBarItem.selectedImage = UIImage(asset: .tabKeypadActive) } fileprivate func setupLayout() { navigationItem.titleView = UIImageView(image: UIImage(asset: .logo)) updateReachabilityBar() } fileprivate func setupSounds() { DispatchQueue.global(qos: .userInteractive).async { var sounds = [String: AVAudioPlayer]() for soundNumber in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "#", "*"] { let soundFileName = "dtmf-\(soundNumber)" let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: "aif") assert(soundURL != nil, "No sound available") do { let player = try AVAudioPlayer(contentsOf: soundURL!) player.prepareToPlay() sounds[soundNumber] = player } catch let error { VialerLogError("Couldn't load sound: \(error)") } } self.sounds = sounds } } fileprivate func setupButtons() { // Enable callbutton if: // - status isn't offline or // - there is a number in memory or // - there is a number to be called if reachability.status == .notReachable || (lastCalledNumber == nil && numberText == nil) { callButton.isEnabled = false } else { callButton.isEnabled = true } UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.callButton.alpha = self.callButton.isEnabled ? 1.0 : 0.5 }, completion: nil) deleteButton.isEnabled = numberText != nil UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.deleteButton.alpha = self.deleteButton.isEnabled ? 1.0 : 0.0 }, completion: nil) } fileprivate func numberPadPressed(character: String) { if character == "+" { if numberText == "0" || numberText == nil { numberText = "+" } } else if numberText != nil { numberText = "\(numberText!)\(character)" } else { numberText = character } } fileprivate func playSound(character: String) { if let player = sounds[character] { player.currentTime = 0 player.play() } } fileprivate func updateReachabilityBar() { DispatchQueue.main.async { self.setupButtons() if (!self.user.sipEnabled) { self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height } else if (!self.reachability.hasHighSpeed) { self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height } else if (!self.user.sipUseEncryption){ self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height } else { self.reachabilityBarHeigthConstraint.constant = 0 } UIView.animate(withDuration: Config.ReachabilityBar.animationDuration) { self.reachabilityBar.setNeedsUpdateConstraints() self.view.layoutIfNeeded() } } } }
gpl-3.0
c75e0c043899b9f2e82699b2f0aa8729
34.146067
133
0.622762
5.158879
false
false
false
false
ECP-CANDLE/Supervisor
archives/workflows/p1b1_hyperopt/swift/workflow.swift
1
7156
import files; import string; import sys; import io; import stats; import python; import math; import location; import assert; import R; import EQPy; string emews_root = getenv("EMEWS_PROJECT_ROOT"); string turbine_output = getenv("TURBINE_OUTPUT"); string resident_work_ranks = getenv("RESIDENT_WORK_RANKS"); string r_ranks[] = split(resident_work_ranks,","); int max_evals = toint(argv("max_evals", "100")); int param_batch_size = toint(argv("param_batch_size", "10")); string space_file = argv("space_description_file"); string data_dir = argv("data_directory"); string read_space_code = """ with open("%s", 'r') as space_file: space = space_file.read() """; // this is the "model" string p1b1_template = """ # tensoflow.__init__ calls _os.path.basename(_sys.argv[0]) # so we need to create a synthetic argv. import sys if not hasattr(sys, 'argv'): sys.argv = ['p1b1'] import p1b1_baseline import p1b1 params = %s test_path = '%s/P1B1.test.csv' train_path = '%s/P1B1.train.csv' X_train, X_test = p1b1.load_data(test_path=test_path, train_path=train_path) # this assumes a simple space. A more complicated space # will require additional unpacking. Note that hp.choice returns # the index into its list / tuple. epochs = int(params['epochs'][0]) encoder, decoder, history = p1b1_baseline.run_p1b1(X_train, X_test, epochs=epochs) # works around this error: # https://github.com/tensorflow/tensorflow/issues/3388 from keras import backend as K K.clear_session() # use the last validation_loss as the value to minimize val_loss = history.history['val_loss'] a = val_loss[-1] """; // algorithm params format is a string representation // of a python dictionary. eqpy_hyperopt evals this // string to create the dictionary. This, unfortunately, string algo_params_template = """ {'space' : %s, 'algo' : %s, 'max_evals' : %d, 'param_batch_size' : %d, 'seed' : %d} """; (string parameter_combos[]) create_parameter_combinations(string params, int trials) { // TODO // Given the parameter string and the number of trials for that // those parameters, create an array of parameter combinations // Typically, this involves at least appending a different random // seed to the parameter string for each trial } (string obj_result) obj(string params, int trials, string iter_indiv_id) { // Typical code might create multiple sets of parameters from a single // set by duplicating that set some number of times and appending a // different random seed to each of the new sets. The example doesn't // do that so we only need to run obj rather than create those new // parameters and iterate over them. // string parameter_combos[] = create_parameter_combinations(params, trials); // float fresults[]; //foreach f,i in params { // string id_suffix = "%s_%i" % (iter_indiv_id,i); // fresults[i] = run_obj(f, id_suffix); //} // not using unique id suffix but we could use it to create // a per run unique directory if we need such string id_suffix = "%s_%i" % (iter_indiv_id,1); string p1b1_code = p1b1_template % (params, data_dir, data_dir); obj_result = python_persist(p1b1_code, "str(a)"); } (void v) loop (location ME, int ME_rank, int trials) { for (boolean b = true, int i = 1; b; b=c, i = i + 1) { // gets the model parameters from the python algorithm string params = EQPy_get(ME); boolean c; // TODO // Edit the finished flag, if necessary. // when the python algorithm is finished it should // pass "DONE" into the queue, and then the // final set of parameters. If your python algorithm // passes something else then change "DONE" to that if (params == "FINAL") { string finals = EQPy_get(ME); printf("Final Result: %s" % finals); // TODO if appropriate // split finals string and join with "\\n" // e.g. finals is a ";" separated string and we want each // element on its own line: // multi_line_finals = join(split(finals, ";"), "\\n"); string fname = "%s/final_result_%i" % (turbine_output, ME_rank); file results_file <fname> = write(finals + "\n") => printf("Writing final result to %s", fname) => // printf("Results: %s", finals) => v = make_void() => c = false; } else { string param_array[] = split(params, ";"); string results[]; foreach p, j in param_array { printf(p); results[j] = obj(p, trials, "%i_%i_%i" % (ME_rank,i,j)); } string res = join(results, ","); EQPy_put(ME, res) => c = true; } } } // TODO // Edit function arguments to include those passed from main function // below (void o) start (int ME_rank, int num_variations, int random_seed) { location ME = locationFromRank(ME_rank); // create the python dictionary representation of the // parameters for the hyperopt algorithm // see https://github.com/hyperopt/hyperopt/wiki/FMin#2-defining-a-search-space // for more info the search space // "hyperopt.hp.choice(\\'epochs\\', )"; string code = read_space_code % space_file; string space = python(code, "space"); // this can also be hyperopt.tpe.suggest, but in that case // we might not get much parallelism. string algo = "hyperopt.rand.suggest"; string algo_params = algo_params_template % (space, algo, max_evals, param_batch_size, random_seed); // python raises an error if we pass a multiline string using EQPy_put // so the \n are removed. algo_params_template is easier to read and edit // as a multiline string so I left it like that and fixed it here. string trimmed_algo_params = trim(replace_all(algo_params, "\n", " ", 0)); EQPy_init_package(ME,"eqpy_hyperopt.hyperopt_runner") => EQPy_get(ME) => EQPy_put(ME, trimmed_algo_params) => loop(ME, ME_rank, num_variations) => { EQPy_stop(ME); o = propagate(); } } // deletes the specified directory app (void o) rm_dir(string dirname) { "rm" "-rf" dirname; } // call this to create any required directories app (void o) make_dir(string dirname) { "mkdir" "-p" dirname; } // anything that need to be done prior to a model runs // (e.g. file creation) can be done here //app (void o) run_prerequisites() { // //} main() { // TODO // Retrieve arguments to this script here // these are typically used for initializing the python algorithm // Here, as an example, we retrieve the number of variations (i.e. trials) // for each model run, and the random seed for the python algorithm. int num_variations = toint(argv("nv", "1")); int random_seed = toint(argv("seed", "0")); // PYTHONPATH needs to be set for python code to be run assert(strlen(getenv("PYTHONPATH")) > 0, "Set PYTHONPATH!"); assert(strlen(emews_root) > 0, "Set EMEWS_PROJECT_ROOT!"); int ME_ranks[]; foreach r_rank, i in r_ranks{ ME_ranks[i] = toint(r_rank); } //run_prerequisites() => { foreach ME_rank, i in ME_ranks { start(ME_rank, num_variations, random_seed); } //} }
mit
172544b81c5ef6897f05422da3065337
30.946429
86
0.649106
3.383452
false
false
false
false
NaughtyOttsel/swift-corelibs-foundation
TestFoundation/TestNSDictionary.swift
2
6115
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSDictionary : XCTestCase { static var allTests: [(String, (TestNSDictionary) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_ArrayConstruction", test_ArrayConstruction), ("test_description", test_description), ("test_enumeration", test_enumeration), ("test_equality", test_equality), ("test_copying", test_copying), ("test_mutableCopying", test_mutableCopying), ] } func test_BasicConstruction() { let dict = NSDictionary() let dict2: NSDictionary = ["foo": "bar"].bridge() XCTAssertEqual(dict.count, 0) XCTAssertEqual(dict2.count, 1) } func test_description() { // Disabled due to [SR-251] // Assertion disabled since it fails on linux targets due to heterogenious collection conversion failure /* let d1: NSDictionary = [ "foo": "bar", "baz": "qux"].bridge() XCTAssertEqual(d1.description, "{\n baz = qux;\n foo = bar;\n}") let d2: NSDictionary = ["1" : ["1" : ["1" : "1"]]].bridge() XCTAssertEqual(d2.description, "{\n 1 = {\n 1 = {\n 1 = 1;\n };\n };\n}") */ } func test_HeterogeneousConstruction() { // let dict2: NSDictionary = [ // "foo": "bar", // 1 : 2 // ] // XCTAssertEqual(dict2.count, 2) // XCTAssertEqual(dict2["foo"] as? NSString, NSString(UTF8String:"bar")) // XCTAssertEqual(dict2[1] as? NSNumber, NSNumber(value: 2)) } func test_ArrayConstruction() { // let objects = ["foo", "bar", "baz"] // let keys = ["foo", "bar", "baz"] // let dict = NSDictionary(objects: objects, forKeys: keys as [NSObject]) // XCTAssertEqual(dict.count, 3) } func test_ObjectForKey() { // let dict: NSDictionary = [ // "foo" : "bar" // ] } func test_enumeration() { let dict : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"].bridge() let e = dict.keyEnumerator() var keys = Set<String>() keys.insert((e.nextObject()! as! NSString).bridge()) keys.insert((e.nextObject()! as! NSString).bridge()) keys.insert((e.nextObject()! as! NSString).bridge()) XCTAssertNil(e.nextObject()) XCTAssertNil(e.nextObject()) XCTAssertEqual(keys, ["foo", "whiz", "toil"]) let o = dict.objectEnumerator() var objs = Set<String>() objs.insert((o.nextObject()! as! NSString).bridge()) objs.insert((o.nextObject()! as! NSString).bridge()) objs.insert((o.nextObject()! as! NSString).bridge()) XCTAssertNil(o.nextObject()) XCTAssertNil(o.nextObject()) XCTAssertEqual(objs, ["bar", "bang", "trouble"]) } func test_sequenceType() { let dict : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"].bridge() var result = [String:String]() for (key, value) in dict { result[key as! String] = (value as! NSString).bridge() } XCTAssertEqual(result, ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"]) } func test_equality() { let keys = ["foo", "whiz", "toil"].bridge().bridge() let objects1 = ["bar", "bang", "trouble"].bridge().bridge() let objects2 = ["bar", "bang", "troubl"].bridge().bridge() let dict1 = NSDictionary(objects: objects1, forKeys: keys.map({ $0 as! NSObject})) let dict2 = NSDictionary(objects: objects1, forKeys: keys.map({ $0 as! NSObject})) let dict3 = NSDictionary(objects: objects2, forKeys: keys.map({ $0 as! NSObject})) XCTAssertTrue(dict1 == dict2) XCTAssertTrue(dict1.isEqual(dict2)) XCTAssertTrue(dict1.isEqualToDictionary(dict2.bridge())) XCTAssertEqual(dict1.hash, dict2.hash) XCTAssertEqual(dict1.hashValue, dict2.hashValue) XCTAssertFalse(dict1 == dict3) XCTAssertFalse(dict1.isEqual(dict3)) XCTAssertFalse(dict1.isEqualToDictionary(dict3.bridge())) XCTAssertFalse(dict1.isEqual(nil)) XCTAssertFalse(dict1.isEqual(NSObject())) } func test_copying() { let inputDictionary : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"].bridge() let copy: NSDictionary = inputDictionary.copy() as! NSDictionary XCTAssertTrue(inputDictionary === copy) let dictMutableCopy = inputDictionary.mutableCopy() as! NSMutableDictionary let dictCopy2 = dictMutableCopy.copy() as! NSDictionary XCTAssertTrue(dictCopy2.dynamicType === NSDictionary.self) XCTAssertFalse(dictMutableCopy === dictCopy2) XCTAssertTrue(dictMutableCopy == dictCopy2) } func test_mutableCopying() { let inputDictionary : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"].bridge() let dictMutableCopy1 = inputDictionary.mutableCopy() as! NSMutableDictionary XCTAssertTrue(dictMutableCopy1.dynamicType === NSMutableDictionary.self) XCTAssertFalse(inputDictionary === dictMutableCopy1) XCTAssertTrue(inputDictionary == dictMutableCopy1) let dictMutableCopy2 = dictMutableCopy1.mutableCopy() as! NSMutableDictionary XCTAssertTrue(dictMutableCopy2.dynamicType === NSMutableDictionary.self) XCTAssertFalse(dictMutableCopy2 === dictMutableCopy1) XCTAssertTrue(dictMutableCopy2 == dictMutableCopy1) } }
apache-2.0
25f7f9d2720f96be83528d4aeb55532a
37.949045
124
0.606214
4.157036
false
true
false
false
argent-os/argent-ios
app-ios/WebTermsViewController.swift
1
3192
// // WebTermsViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 3/27/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import UIKit import WebKit import CWStatusBarNotification class WebTermsViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { @IBOutlet var containerView : UIView! var webView: WKWebView? override func loadView() { super.loadView() self.navigationController?.navigationBar.tintColor = UIColor.darkGrayColor() self.webView = WKWebView() self.webView?.UIDelegate = self self.view = self.webView! } override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string:"https://www.argentapp.com/terms") let req = NSURLRequest(URL:url!) self.webView!.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } lazy var previewActions: [UIPreviewActionItem] = { func previewActionForTitle(title: String, style: UIPreviewActionStyle = .Default) -> UIPreviewAction { return UIPreviewAction(title: title, style: style) { previewAction, viewController in // guard let detailViewController = viewController as? DetailViewController, // item = detailViewController.detailItemTitle else { return } // print("\(previewAction.title) triggered from `DetailViewController` for item: \(item)") if title == "Copy Link" { UIPasteboard.generalPasteboard().string = "https://www.argentapp.com/terms" showGlobalNotification("Link copied!", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.skyBlue()) } if title == "Share" { let activityViewController = UIActivityViewController( activityItems: ["Argent Terms and Conditions https://www.argentapp.com/terms" as NSString], applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList] self.presentViewController(activityViewController, animated: true, completion: nil) } } } let action1 = previewActionForTitle("Copy Link") // return [action1] let action2 = previewActionForTitle("Share") return [action1, action2] // let action2 = previewActionForTitle("Share", style: .Destructive) // let subAction1 = previewActionForTitle("Sub Action 1") // let subAction2 = previewActionForTitle("Sub Action 2") // let groupedActions = UIPreviewActionGroup(title: "More", style: .Default, actions: [subAction1, subAction2] ) // return [action1, action2, groupedActions] }() override func previewActionItems() -> [UIPreviewActionItem] { return previewActions } }
mit
2dc051efb50abdfbe3f02da30e8e1011
39.405063
248
0.644939
5.130225
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Example-iOS/RootViewController.swift
1
1091
import UIKit class RootViewController: UIViewController { private var current: UIViewController var initialController: UIViewController = { let dataSourceExampleSceneViewController = UIStoryboard(name: Constants.StoryboardIdentifiers.layoutExampleScene.rawValue, bundle: nil).instantiateInitialViewController()! return dataSourceExampleSceneViewController }() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } init() { let navigationController = MainNavigationController(rootViewController: initialController) current = navigationController super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("Not required in the current implementation") } override func viewDidLoad() { super.viewDidLoad() addChild(current) current.view.frame = view.bounds view.addSubview(current.view) current.didMove(toParent: self) } }
mit
ded43e6d47f99931269c49062305a0cc
30.171429
130
0.670944
6.234286
false
false
false
false
midoks/Swift-Learning
EampleApp/EampleApp/Controllers/User/UserSudokuViewController.swift
1
1948
// // UserSudokuViewController.swift // // Created by midoks on 15/8/20. // Copyright © 2015年 midoks. All rights reserved. // import UIKit //九宫格视图 class UserSudokuViewController: UIViewController, SudokuViewDelegate { var tmpBarColor:UIColor? override func viewDidLoad() { super.viewDidLoad() self.title = "九宫格验证" self.view.backgroundColor = UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1) tmpBarColor = UINavigationBar.appearance().barTintColor UINavigationBar.appearance().barTintColor = UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1) let leftButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UserSudokuViewController.close(_:))) self.navigationItem.leftBarButtonItem = leftButton let sudoku = SudokuView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)) sudoku.delegate = self //设置正确的密码 //如果正在设置密码,就不需要填写了 sudoku.setPwd("012345678") self.view.addSubview(sudoku) } func SudokuViewFail(_ pwd: NSString, status: NSString) { NSLog("pwd:%@, status:%@", pwd, status) } func SudokuViewOk(_ pwd: NSString, status: NSString) { NSLog("pwd:%@, status:%@", pwd, status) if("end" == status){ noticeText("您的结果", text: pwd as NSString, time: 2.0) } } //离开本页面 override func viewWillDisappear(_ animated: Bool) { UINavigationBar.appearance().barTintColor = tmpBarColor } //关闭 func close(_ button: UIButton){ self.dismiss(animated: true) { () -> Void in //print("close") } } }
apache-2.0
edfcff99a96aab2e5bc0a42d56d99baf
27.106061
157
0.593531
4.149888
false
false
false
false
tskorte/vaporizer
Sources/App/Models/User.swift
1
2183
// // User.swift // HelloVapor // // Created by Karl Kristian Forfang on 10.06.2017. // // import Vapor import Foundation import FluentProvider import AuthProvider private var _userPasswordVerifier: PasswordVerifier? = nil public final class User: Model { public let storage = Storage() public let userName: String public let email: String public var password: String? init(name: String, email: String, password: String? = nil) { self.userName = name self.email = email self.password = password } required public init(row: Row) throws { userName = try row.get("name") email = try row.get("email") password = try row.get("password") } public func makeRow() throws -> Row { var row = Row() try row.set("name", userName) try row.set("email", email) try row.set("password", password) return row } } extension User: ResponseRepresentable { } extension User: TokenAuthenticatable{ public typealias TokenType = Token } extension User: JSONConvertible { convenience public init(json: JSON) throws { try self.init( name: json.get("name"), email: json.get("email") ) id = try json.get("id") } public func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("name", userName) try json.set("email", email) return json } } extension User: Preparation{ public static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string("name") builder.string("email") builder.string("password") } } public static func revert(_ database: Database) throws { try database.delete(self) } } extension User: PasswordAuthenticatable { public var hashedPassword: String? { return password } public static var passwordVerifier: PasswordVerifier? { get { return _userPasswordVerifier } set { _userPasswordVerifier = newValue } } }
mit
1d6c19d7df90f80bb349cfa21f90d630
22.728261
64
0.603298
4.357285
false
false
false
false
eCrowdMedia/MooApi
Sources/helper/DeviceData.swift
1
3878
import Foundation ///帳號裝置的資料 public struct DeviceData: Codable { public enum CodingKeys: String, CodingKey { case data = "data" } public let data: ParameterData public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(data, forKey: .data) } public func makeJsonData() -> Data? { let jsonData = try? JSONEncoder().encode(self) return jsonData } public init(keyName: String, keyValue: String, deviceName: String, deviceType: String, userAgent: String) { self.data = ParameterData(keyName: keyName, keyValue: keyValue, deviceName: deviceName, deviceType: deviceType, userAgent: userAgent) } } extension DeviceData { public struct ParameterData: Codable { public enum CodingKeys: String, CodingKey { case type = "type" case id = "id" case attributes = "attributes" } public let type = "devices" public let id = UIDevice.current.identifierForVendor?.uuidString public let attributes: Attributes public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) try container.encode(id, forKey: .id) try container.encode(attributes, forKey: .attributes) } public init(keyName: String, keyValue: String, deviceName: String, deviceType: String, userAgent: String) { self.attributes = Attributes(keyName: keyName, keyValue: keyValue, deviceName: deviceName, deviceType: deviceType, userAgent: userAgent) } } } extension DeviceData.ParameterData { public struct Attributes: Codable { public enum CodingKeys: String, CodingKey { case name = "name" case deviceType = "device_type" case userAgent = "user_agent" case key = "key" } public let name: String public let deviceType: String public let userAgent: String public let key: Key public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(deviceType, forKey: .deviceType) try container.encode(userAgent, forKey: .userAgent) try container.encode(key, forKey: .key) } public init(keyName: String, keyValue: String, deviceName: String, deviceType: String, userAgent: String) { self.name = deviceName self.deviceType = deviceType self.userAgent = userAgent self.key = Key(keyName: keyName, keyValue: keyValue) } } } extension DeviceData.ParameterData.Attributes { public struct Key: Codable { public enum CodingKeys: String, CodingKey { case algorithm = "algorithm" case name = "name" case value = "value" } public let algorithm = "http://www.w3.org/2001/04/xmlenc#rsa-1_5" public let name: String public let value: String public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(algorithm, forKey: .algorithm) try container.encode(name, forKey: .name) try container.encode(value, forKey: .value) } public init(keyName: String, keyValue: String) { self.name = keyName self.value = keyValue } } }
mit
0d7c271eee424efed20742d6e77b787f
27.20438
70
0.595238
4.735294
false
false
false
false
shiguredo/sora-ios-sdk
Sora/MediaStream.swift
1
9206
import Foundation import WebRTC /** ストリームの音声のボリュームの定数のリストです。 */ public enum MediaStreamAudioVolume { /// 最大値 public static let min: Double = 0 /// 最小値 public static let max: Double = 10 } /// ストリームのイベントハンドラです。 public final class MediaStreamHandlers { /// このプロパティは onSwitchVideo に置き換えられました。 @available(*, deprecated, renamed: "onSwitchVideo", message: "このプロパティは onSwitchVideo に置き換えられました。") public var onSwitchVideoHandler: ((_ isEnabled: Bool) -> Void)? { get { onSwitchVideo } set { onSwitchVideo = newValue } } /// このプロパティは onSwitchAudio に置き換えられました。 @available(*, deprecated, renamed: "onSwitchAudio", message: "このプロパティは onSwitchAudio に置き換えられました。") public var onSwitchAudioHandler: ((_ isEnabled: Bool) -> Void)? { get { onSwitchAudio } set { onSwitchAudio = newValue } } /// 映像トラックが有効または無効にセットされたときに呼ばれるクロージャー public var onSwitchVideo: ((_ isEnabled: Bool) -> Void)? /// 音声トラックが有効または無効にセットされたときに呼ばれるクロージャー public var onSwitchAudio: ((_ isEnabled: Bool) -> Void)? /// 初期化します。 public init() {} } /** メディアストリームの機能を定義したプロトコルです。 デフォルトの実装は非公開 (`internal`) であり、カスタマイズはイベントハンドラでのみ可能です。 ソースコードは公開していますので、実装の詳細はそちらを参照してください。 メディアストリームは映像と音声の送受信を行います。 メディアストリーム 1 つにつき、 1 つの映像と 1 つの音声を送受信可能です。 */ public protocol MediaStream: AnyObject { // MARK: - イベントハンドラ /// イベントハンドラ var handlers: MediaStreamHandlers { get } // MARK: - 接続情報 /// ストリーム ID var streamId: String { get } /// 接続開始時刻 var creationTime: Date { get } /// メディアチャンネル var mediaChannel: MediaChannel? { get } // MARK: - 映像と音声の可否 /** 映像の可否。 ``false`` をセットすると、サーバーへの映像の送受信を停止します。 ``true`` をセットすると送受信を再開します。 */ var videoEnabled: Bool { get set } /** 音声の可否。 ``false`` をセットすると、サーバーへの音声の送受信を停止します。 ``true`` をセットすると送受信を再開します。 サーバーへの送受信を停止しても、マイクはミュートされませんので注意してください。 */ var audioEnabled: Bool { get set } /** 受信した音声のボリューム。 0 から 10 (含む) までの値をセットします。 このプロパティはロールがサブスクライバーの場合のみ有効です。 */ var remoteAudioVolume: Double? { get set } // MARK: 映像フレームの送信 /// 映像フィルター var videoFilter: VideoFilter? { get set } /// 映像レンダラー。 var videoRenderer: VideoRenderer? { get set } /** 映像フレームをサーバーに送信します。 送信される映像フレームは映像フィルターを通して加工されます。 映像レンダラーがセットされていれば、加工後の映像フレームが 映像レンダラーによって描画されます。 - parameter videoFrame: 描画する映像フレーム。 `nil` を指定すると空の映像フレームを送信します。 */ func send(videoFrame: VideoFrame?) // MARK: 終了処理 /** ストリームの終了処理を行います。 */ func terminate() } class BasicMediaStream: MediaStream { let handlers = MediaStreamHandlers() var peerChannel: PeerChannel var streamId: String = "" var videoTrackId: String = "" var audioTrackId: String = "" var creationTime: Date var mediaChannel: MediaChannel? { // MediaChannel は必ず存在するが、 MediaChannel と PeerChannel の循環参照を避けるために、 PeerChannel は MediaChannel を弱参照で保持している // mediaChannel を force unwrapping することも検討したが、エラーによる切断処理中なども安全である確信が持てなかったため、 // SDK 側で force unwrapping することは避ける peerChannel.mediaChannel } var videoFilter: VideoFilter? var videoRenderer: VideoRenderer? { get { videoRendererAdapter?.videoRenderer } set { if let value = newValue { videoRendererAdapter = VideoRendererAdapter(videoRenderer: value) value.onAdded(from: self) } else { videoRendererAdapter?.videoRenderer? .onRemoved(from: self) videoRendererAdapter = nil } } } private var videoRendererAdapter: VideoRendererAdapter? { willSet { guard let videoTrack = nativeVideoTrack else { return } guard let adapter = videoRendererAdapter else { return } Logger.debug(type: .videoRenderer, message: "remove old video renderer \(adapter) from nativeVideoTrack") videoTrack.remove(adapter) } didSet { guard let videoTrack = nativeVideoTrack else { return } guard let adapter = videoRendererAdapter else { return } Logger.debug(type: .videoRenderer, message: "add new video renderer \(adapter) to nativeVideoTrack") videoTrack.add(adapter) } } var nativeStream: RTCMediaStream var nativeVideoTrack: RTCVideoTrack? { nativeStream.videoTracks.first } var nativeVideoSource: RTCVideoSource? { nativeVideoTrack?.source } var nativeAudioTrack: RTCAudioTrack? { nativeStream.audioTracks.first } var videoEnabled: Bool { get { nativeVideoTrack?.isEnabled ?? false } set { guard videoEnabled != newValue else { return } if let track = nativeVideoTrack { track.isEnabled = newValue handlers.onSwitchVideo?(newValue) videoRenderer?.onSwitch(video: newValue) } } } var audioEnabled: Bool { get { nativeAudioTrack?.isEnabled ?? false } set { guard audioEnabled != newValue else { return } if let track = nativeAudioTrack { track.isEnabled = newValue handlers.onSwitchAudio?(newValue) videoRenderer?.onSwitch(audio: newValue) } } } var remoteAudioVolume: Double? { get { nativeAudioTrack?.source.volume } set { guard let newValue = newValue else { return } if let track = nativeAudioTrack { var volume = newValue if volume < MediaStreamAudioVolume.min { volume = MediaStreamAudioVolume.min } else if volume > MediaStreamAudioVolume.max { volume = MediaStreamAudioVolume.max } track.source.volume = volume Logger.debug(type: .mediaStream, message: "set audio volume \(volume)") } } } init(peerChannel: PeerChannel, nativeStream: RTCMediaStream) { self.peerChannel = peerChannel self.nativeStream = nativeStream streamId = nativeStream.streamId creationTime = Date() } func terminate() { videoRendererAdapter?.videoRenderer?.onDisconnect(from: peerChannel.mediaChannel ?? nil) } private static let dummyCapturer = RTCVideoCapturer() func send(videoFrame: VideoFrame?) { if let frame = videoFrame { // フィルターを通す let frame = videoFilter?.filter(videoFrame: frame) ?? frame switch frame { case let .native(capturer: capturer, frame: nativeFrame): // RTCVideoSource.capturer(_:didCapture:) の最初の引数は // 現在使われてないのでダミーでも可? -> ダミーにしました nativeVideoSource?.capturer(capturer ?? BasicMediaStream.dummyCapturer, didCapture: nativeFrame) } } else {} } }
apache-2.0
0a354fc2a1f31f342205e6933f5ac70f
26.939623
113
0.58725
3.793033
false
false
false
false
zhangjiewen/sky
sky/Logger.swift
1
1209
/* * Copyright 2016 Zhangjiewen. * * 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 //TODO add color print("\u{001b}[fg150,178,193;test\u{001b}[;") //日志对象 public struct Logger{ let loggerName: String let format: DateFormatter var off = false init(_ name: String){ self.loggerName = name self.format = DateFormatter() self.format.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" } func log(_ toLog: String){ if(!off){ let now = Date() print("\(format.string(from: now)) \(getpid()) \(self.loggerName)-\(toLog)") } } mutating func turnOff(){ self.off = true } }
apache-2.0
14e6f74f0daeafb6bc2240e44ed76e75
28.292683
88
0.646128
3.912052
false
false
false
false
kouky/Algorithms
Algorithms.playground/Pages/Heap.xcplaygroundpage/Contents.swift
1
4865
// Heap Data Structure // https://en.wikipedia.org/wiki/Heap_(data_structure) // https://en.wikipedia.org/wiki/Binary_heap // // The MIT License (MIT) // // Copyright (c) 2015 Michael Koukoullis <http://github.com/kouky> import Darwin // Full and almost full binary heaps may be represented (as an implicit data structure) using an array alone. struct Heap<T: Comparable> { private let items: [T] private let ordering: Ordering<T> } enum Ordering <T: Comparable> { case Min case Max func satisfiedInvariantForParent(parent: T, child: T) -> Bool { switch self { case .Min: return parent <= child case .Max: return parent >= child } } } // Common heap operations extension Heap { // Return highest priority element (i.e. root of heap) func peek() -> T? { return items.first } // Add item to the heap, return the new heap func insert(item: T) -> Heap { let newHeap = Heap(items: self.items + [item], ordering: ordering) return newHeap.upHeap(newHeap.items.endIndex - 1) } // Delete the root from the heap, return the new heap func extract() -> Heap { let newHeap = Heap(items: items.moveLastElementToFront(), ordering: ordering) return newHeap.downHeap(0) } } // Implicit heap data strcuture can be navigated with index arithmentic private extension Heap { func parentIndexForIndex(index: Int) -> Int? { guard index > 0 else { return nil } return (index - 1) / 2 } func rightChildIndexForIndex(index: Int) -> Int? { let rightChildIndex = 2 * index + 2 return (rightChildIndex < items.endIndex) ? rightChildIndex : nil } func leftChildIndexForIndex(index: Int) -> Int? { let leftChildIndex = 2 * index + 1 return (leftChildIndex < items.endIndex) ? leftChildIndex : nil } func downHeapChildIndexForParentIndex(index: Int) -> Int? { switch (self.leftChildIndexForIndex(index), self.rightChildIndexForIndex(index)) { case (.None, .None): return nil case (.Some(let left), .None): return left case (.None, .Some(let right)): return right case (.Some(let left), .Some(let right)): switch ordering { case .Min: return items[left] < items[right] ? left : right case .Max: return items[left] > items[right] ? left : right } } } } // Operations to restore heap invariants private extension Heap { func upHeap(index: Int) -> Heap { guard let parentIndex = self.parentIndexForIndex(index) else { return self } if ordering.satisfiedInvariantForParent(items[parentIndex], child: items[index]) { return self } else { return Heap(items: items.swapValuesForIndices(parentIndex, index), ordering: ordering).upHeap(parentIndex) } } func downHeap(index: Int) -> Heap { guard let childIndex = downHeapChildIndexForParentIndex(index) else { return self } if ordering.satisfiedInvariantForParent(items[index], child: items[childIndex]) { return self } else { return Heap(items: items.swapValuesForIndices(childIndex, index), ordering: ordering).downHeap(childIndex) } } } extension Heap: CustomStringConvertible { var description: String { return items.description } } private extension Array { var lastIndex: Int { return self.endIndex - 1 } var last: Element { return self[self.lastIndex] } private nonmutating func swapValuesForIndices(firstIndex: Int, _ secondIndex: Int) -> [Element] { guard firstIndex >= 0 && secondIndex >= 0 else { fatalError("Invalid indices") } var newItems = self newItems[firstIndex] = self[secondIndex] newItems[secondIndex] = self[firstIndex] return newItems } private nonmutating func moveLastElementToFront() -> [Element] { guard self.count > 1 else { return self } var newElements = Array(self.dropLast()) newElements[0] = self.last return newElements } } // Min Heap let emptyMinHeap = Heap<Int>(items: [], ordering: Ordering.Min) let minHeap = emptyMinHeap.insert(10).insert(8).insert(2).insert(5).insert(7).insert(4) minHeap.peek() minHeap.extract() minHeap.extract().extract() // Max Heap let emptyMaxHeap = Heap<Int>(items: [], ordering: Ordering.Max) let maxHeap = emptyMaxHeap.insert(3).insert(2).insert(10).insert(4).insert(8).insert(7) maxHeap.peek() maxHeap.extract() maxHeap.extract().extract()
mit
e009b1e55e4140034d516e0f490172cb
28.307229
118
0.611511
4.168809
false
false
false
false
prolificinteractive/simcoe
Simcoe/mParticle/MPEvent+Simcoe.swift
1
3842
// // MPEvent+Simcoe.swift // Simcoe // // Created by Christopher Jones on 2/16/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import mParticle_Apple_SDK extension MPEvent { /// Creates a dictionary used to generate an MPEvent object. All of the input parameters map to /// properties on the MPEvent object. Not setting any of the properties will not initialize those respective /// properties of the MPEvent object. /// /// The `info` parameter will generate additional key / value pairs into the root level of the dictionary. /// /// It is safe to additionally add key / values into the root of the dictionary; any key / values passed in that /// are not recognized will be set in the info dictionary of the generated MPEvent object. /// /// - Parameters: /// - type: The event type. Required. /// - name: The event name. Required. /// - category: The category of the event. Optional. /// - duration: The duration of the event. Optional. /// - startTime: The start time of the event. Optional. /// - endTime: The end time of the event. Optional. /// - customFlags: The custom flags for the event. Optional. /// - info: Additional key / value pairs to place into the root level of the dictionary. These will /// map to the `info` dictionary of the generated MPEvent object. /// - Returns: A dictionary containing the information for generating an MPEvent. public static func eventData(type: MPEventType, name: String, category: String? = nil, duration: Float? = nil, startTime: Date? = nil, endTime: Date? = nil, customFlags: [String: [String]]? = nil, info: Properties? = nil) -> Properties { var properties = Properties() properties[MPEventKeys.eventType.rawValue] = type.rawValue properties[MPEventKeys.name.rawValue] = name if let category = category { properties[MPEventKeys.category.rawValue] = category } if let duration = duration { properties[MPEventKeys.duration.rawValue] = duration } if let customFlags = customFlags { properties[MPEventKeys.customFlags.rawValue] = customFlags } if let info = info { for (key, value) in info { properties[key] = value } } return properties } /// Generates a MPEvent object based on the passed in Properties. /// /// - Parameter data: The properties. /// - Returns: A MPEvent. /// - Throws: MPEventGenerationError internal static func toEvent(usingData data: Properties) throws -> MPEvent { guard let name = data[MPEventKeys.name.rawValue] as? String else { throw MPEventGenerationError.nameMissing } guard let eventValue = data[MPEventKeys.eventType.rawValue] as? UInt, let type = MPEventType(rawValue: eventValue) else { throw MPEventGenerationError.typeMissing } guard let event = MPEvent(name: name, type: type) else { throw MPEventGenerationError.eventInitFailed } if let category = data[MPEventKeys.category.rawValue] as? String { event.category = category } if let duration = data[MPEventKeys.duration.rawValue] as? Float { event.duration = NSNumber(value: duration) } if let flags = data[MPEventKeys.customFlags.rawValue] as? [String: [String]] { for (key, flagValues) in flags { event.addCustomFlags(flagValues, withKey: key) } } event.info = MPEventKeys.remaining(properties: data) return event } }
mit
befbc9c7cabf814db5d055538fbf4d11
37.029703
116
0.618849
4.550948
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/Home/Models/Users.swift
1
1836
// // Users.swift // LSYWeiBo // // Created by 李世洋 on 16/5/10. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit import ObjectMapper class Users: Mappable { // 用户ID var id: Int = 0 // 友好显示名称 var name: String? // 用户头像地址(中图),50×50像素 var profile_image_url: String? { didSet{ imageURL = NSURL(string: profile_image_url!) } } // 用于保存用户头像的URL var imageURL: NSURL? // 时候是认证, true是, false不是 var verified: Bool = false // 用户的认证类型 var verified_type: Int = -1{ didSet{ switch verified_type { case 0: acatarImage = UIImage(named: "avatar_vip") case 2, 3, 5: acatarImage = UIImage(named: "avatar_enterprise_vip") case 220: acatarImage = UIImage(named: "avatar_grassroot") default: acatarImage = nil } } } // 认证image var acatarImage: UIImage? // 会员 var mbrank: Int = 0 { didSet{ if mbrank > 0 && mbrank < 7 { mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)") mbrank_Color = UIColor.orangeColor() } } } var mbrankImage: UIImage? // 会员名 高亮 var mbrank_Color = UIColor.blackColor() required init?(_ map: Map) { } func mapping(map: Map) { id <- map["id"] name <- map["name"] profile_image_url <- map["profile_image_url"] verified <- map["verified"] verified_type <- map["verified_type"] mbrank <- map["mbrank"] } }
artistic-2.0
e4c6e7927c8f20e732fc4224a58ee08e
20.948718
85
0.494743
3.953811
false
false
false
false
umino/IPAddressKeyboard
IPAddressKeyboard/Classes/IPAddressKeyboard.swift
1
2617
// // IPAddressKeyboard.swift // IPTextField // // Created by M.Toshima on 2016/05/18. // Copyright © 2016年 M.Toshima. All rights reserved. // import UIKit @objc(IPAddressKeyboard) public class IPAddressKeyboard: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ public var activeTextField : UITextField? = nil @IBOutlet var contentView: IPAddressKeyboard! @IBOutlet weak var backspaceButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var dotButton: UIButton! override init(frame: CGRect) { super.init(frame: frame) commInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commInit() } func commInit() { // let view = NSBundle.mainBundle().loadNibNamed("IPAddressKeyboard", owner: self, options: nil).first as! UIView var nibName : String switch UIDevice.currentDevice().userInterfaceIdiom { case .Phone: nibName = "IPAddressKeyboard" case .Pad: nibName = "IPAddressKeyboard~iPad" default: nibName = "IPAddressKeyboard" } let bundle = NSBundle(forClass: self.dynamicType) bundle.loadNibNamed(nibName, owner: self, options: nil) contentView.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, contentView.frame.height) frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, contentView.frame.height) addSubview(contentView) translatesAutoresizingMaskIntoConstraints = true } @IBAction func pushNumButton(sender: AnyObject) { guard let activeTextField = activeTextField else {return} do { let numtag = String(format: "%d", sender.tag!) activeTextField.text = activeTextField.text?.stringByAppendingString(numtag) } } @IBAction func pushDotButton(sender: AnyObject) { guard let activeTextField = activeTextField else {return} do { activeTextField.text = activeTextField.text?.stringByAppendingString(".") } } @IBAction func pushBackspaceButton(sender: AnyObject) { activeTextField?.deleteBackward() } @IBAction func pushCloseButton(sender: AnyObject) { activeTextField?.resignFirstResponder() } }
apache-2.0
f3ebb61ef2d3597ccc71c037b4f793b2
29.045977
120
0.63772
4.849722
false
false
false
false
Reggian/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Utilities/ZipArchive.swift
3
5203
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 Zip internal class ZipArchive { fileprivate init() { // Forbid creating instance of this class // Use this class only in static way } /** Opens the ZIP archive and returs a list of URLs to all unzipped files. Unzipped files were moved to a temporary destination in Cache Directory. - parameter url: URL to a ZIP file - throws: an error if unzipping, or obtaining the list of files failed - returns: list of URLs to unzipped files in the tmp folder */ internal static func unzip(_ url:URL) throws -> [URL] { let fileName = url.lastPathComponent let destinationPath = try createTemporaryFolderPath(fileName) // Unzip file to the destination folder let destination = URL.init(fileURLWithPath: destinationPath) try Zip.unzipFile(url, destination: destination, overwrite: true, password: nil, progress: nil) // Get folder content let files = try getFilesFromDirectory(destinationPath) // Convert Strings to NSURLs var urls = [URL]() for file in files { urls.append(URL(fileURLWithPath: destinationPath + file)) } return urls } /** A path to a newly created temp directory or nil in case of an error. - throws: an error when creating the tmp directory failed - returns: a path to the tmp folder */ internal static func createTemporaryFolderPath(_ name:String) throws -> String { // Build the temp folder path. Content of the ZIP file will be copied into it let tempPath = NSTemporaryDirectory() + ".dfu/unzip/" + name + "/" // Check if folder exists. Remove it if so let fileManager = FileManager.default if fileManager.fileExists(atPath: tempPath) { do { try fileManager.removeItem(atPath: tempPath) } catch let error as NSError { NSLog("Error while removing old temp file: \(error.localizedDescription)") throw error } } // Create a new temporary folder do { try fileManager.createDirectory(atPath: tempPath, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { NSLog("Error while creating temp file: \(error.localizedDescription)") throw error } return tempPath } /** Returns a list of paths to all files from a given directory. - parameter path: a path to the directory to get files from - throws: an error if could not get contents of the directory - returns: list of paths to files from the directory at given path */ internal static func getFilesFromDirectory(_ path:String) throws -> [String] { let fileManager = FileManager.default do { return try fileManager.contentsOfDirectory(atPath: path) } catch let error as NSError { NSLog("Error while obtaining content of temp folder: \(error.localizedDescription)") throw error } } /** Looks for a file with given name inside an array or file URLs. - parameter name: file name - parameter urls: list of files URLs to search in - returns: URL to a file or nil */ internal static func findFile(_ name:String, inside urls:[URL]) -> URL? { for url in urls { if url.lastPathComponent == name { return url } } return nil } }
mit
37a88d3313e0d871f1f29330fdb0400d
39.023077
144
0.659427
5.182271
false
false
false
false
pixelmaid/DynamicBrushes
swift/Palette-Knife/views/ColorPicker/ColorUtils.swift
3
2249
// // ColorUtils.swift // SwiftHSVColorPicker // // Created by johankasperi on 2015-08-20. // import UIKit // Typealias for RGB color values typealias RGB = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) // Typealias for HSV color values typealias HSV = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) func hsv2rgb(_ hsv: HSV) -> RGB { // Converts HSV to a RGB color var rgb: RGB = (red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) var r: CGFloat var g: CGFloat var b: CGFloat let i = Int(hsv.hue * 6) let f = hsv.hue * 6 - CGFloat(i) let p = hsv.brightness * (1 - hsv.saturation) let q = hsv.brightness * (1 - f * hsv.saturation) let t = hsv.brightness * (1 - (1 - f) * hsv.saturation) switch (i % 6) { case 0: r = hsv.brightness; g = t; b = p; break; case 1: r = q; g = hsv.brightness; b = p; break; case 2: r = p; g = hsv.brightness; b = t; break; case 3: r = p; g = q; b = hsv.brightness; break; case 4: r = t; g = p; b = hsv.brightness; break; case 5: r = hsv.brightness; g = p; b = q; break; default: r = hsv.brightness; g = t; b = p; } rgb.red = r rgb.green = g rgb.blue = b rgb.alpha = hsv.alpha return rgb } func rgb2hsv(_ rgb: RGB) -> HSV { // Converts RGB to a HSV color var hsb: HSV = (hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 0.0) let rd: CGFloat = rgb.red let gd: CGFloat = rgb.green let bd: CGFloat = rgb.blue let maxV: CGFloat = max(rd, max(gd, bd)) let minV: CGFloat = min(rd, min(gd, bd)) var h: CGFloat = 0 var s: CGFloat = 0 let b: CGFloat = maxV let d: CGFloat = maxV - minV s = maxV == 0 ? 0 : d / minV; if (maxV == minV) { h = 0 } else { if (maxV == rd) { h = (gd - bd) / d + (gd < bd ? 6 : 0) } else if (maxV == gd) { h = (bd - rd) / d + 2 } else if (maxV == bd) { h = (rd - gd) / d + 4 } h /= 6; } hsb.hue = h hsb.saturation = s hsb.brightness = b hsb.alpha = rgb.alpha return hsb }
mit
fd703f0e6f5cf83354e36d2dc3b2ae5a
24.556818
88
0.508226
3.059864
false
false
false
false
uasys/swift
test/SILOptimizer/inout_capture_diagnostics.swift
22
1003
// RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s // // This is an adjunct to access_enforcement_noescape.swift to cover early static diagnostics. // Helper func doOneInout(_: ()->(), _: inout Int) {} // Error: Cannot capture nonescaping closure. // expected-note@+1{{parameter 'fn' is implicitly non-escaping}} func reentrantCapturedNoescape(fn: (() -> ()) -> ()) { // expected-error@+1{{closure use of non-escaping parameter 'fn' may allow it to escape}} let c = { fn {} } fn(c) } // Error: inout cannot be captured. func inoutReadBoxWriteInout(x: inout Int) { // expected-error@+1{{escaping closures can only capture inout parameters explicitly by value}} let c = { _ = x } doOneInout(c, &x) } // Error: Cannot capture inout func inoutWriteBoxWriteInout(x: inout Int) { // expected-error@+1{{escaping closures can only capture inout parameters explicitly by value}} let c = { x = 42 } doOneInout(c, &x) }
apache-2.0
99d5842d9fc84ea38247aea023300271
34.821429
122
0.691924
3.569395
false
false
false
false
crashoverride777/SwiftyAds
Tests/Public/SwiftyAdsEnvironmentTests.swift
1
1481
import XCTest @testable import SwiftyAds final class SwiftyAdsEnvironmentTests: XCTestCase { // MARK: - Consent Configuration // MARK: Geography func testConsentConfigurationGeography_whenDefault_returnsGeography() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .default(geography: .EEA) XCTAssertEqual(sut.geography, .EEA) } func testConsentConfigurationGeography_whenResetOnLaunch_returnsGeography() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .resetOnLaunch(geography: .notEEA) XCTAssertEqual(sut.geography, .notEEA) } func testConsentConfigurationGeography_whenDisabled_returnsDisabled() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .disabled XCTAssertEqual(sut.geography, .disabled) } // MARK: Is Disabled func testConsentConfigurationIsDisabled_whenDefault_returnsFalse() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .default(geography: .EEA) XCTAssertFalse(sut.isDisabled) } func testConsentConfigurationIsDisabled_whenResetOnLaunch_returnsFalse() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .resetOnLaunch(geography: .notEEA) XCTAssertFalse(sut.isDisabled) } func testConsentConfigurationIsDisabled_whenDisabled_returnsTrue() { let sut: SwiftyAdsEnvironment.ConsentConfiguration = .disabled XCTAssertTrue(sut.isDisabled) } }
mit
94b170dd11901c53eeb914881277b64f
35.121951
95
0.728562
4.953177
false
true
false
false