repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringlengths
1
4
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
TonnyTao/HowSwift
Funny Swift.playground/Pages/associated_object.xcplaygroundpage/Contents.swift
1
432
import Foundation class MyClass { } extension MyClass { private static var titleKey: UInt8 = 0 var title: String? { get { return objc_getAssociatedObject(self, &Self.titleKey) as? String } set { objc_setAssociatedObject(self, &Self.titleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } let a = MyClass() a.title = "Swifter.tips" print(a.title!)
mit
Rep2/IRSocket
SimpleSocketExample/SimpleSocketExample/main.swift
1
602
// // main.swift // SimpleSocketExample // // Created by Rep on 12/14/15. // Copyright © 2015 Rep. All rights reserved. // import Foundation // Creates UDP socket if let socket = IRSocket(domain: AF_INET, type: SOCK_DGRAM, proto: 0){ do{ // Binds socket to OS given address let addr = IRSockaddr() try socket.bind(addr) }catch IRSocketError.BindFailed{ print("Socket bind failed") exit(1) }catch{ print("Get name failed") exit(1) } }else{ print("Server socket creation failed") exit(1) }
mit
TwoRingSoft/SemVer
Vrsnr/File Types/PlistFile.swift
1
1930
// // PlistFile.swift // Vrsnr // // Created by Andrew McKnight on 7/9/16. // Copyright © 2016 Two Ring Software. All rights reserved. // import Foundation public struct PlistFile { public let path: String } extension PlistFile: File { public func getPath() -> String { return path } public static func defaultKeyForVersionType(_ type: VersionType) -> String { switch(type) { case .Numeric: return "CFBundleVersion" case .Semantic: return "CFBundleShortVersionString" } } public func defaultKeyForVersionType(_ type: VersionType) -> String { return PlistFile.defaultKeyForVersionType(type) } public func versionStringForKey(_ key: String?, versionType: VersionType) -> String? { guard let data = NSDictionary(contentsOfFile: self.path) else { return nil } if key == nil { return data[defaultKeyForVersionType(versionType)] as? String } else { return data[key!] as? String } } public func replaceVersionString<V>(_ original: V, new: V, key: String?) throws where V: Version { guard let dictionary = NSDictionary(contentsOfFile: self.path) else { throw NSError(domain: errorDomain, code: Int(ErrorCode.couldNotReadFile.rawValue), userInfo: [ NSLocalizedDescriptionKey: "Failed to read current state of file for updating." ]) } if key == nil { dictionary.setValue(new.description, forKey: defaultKeyForVersionType(new.type)) } else { dictionary.setValue(new.description, forKey: key!) } if !dictionary.write(toFile: self.path, atomically: true) { throw NSError(domain: errorDomain, code: Int(ErrorCode.unwritableFile.rawValue), userInfo: [ NSLocalizedDescriptionKey: "Failed to write updated version to file" ]) } } }
apache-2.0
skylib/SnapImagePicker
SnapImagePicker/ImagePicker/Presenter/SnapImagePickerEventHandlerProtocol.swift
1
489
import UIKit protocol SnapImagePickerEventHandlerProtocol: class { var cameraRollAccess: Bool { get set } func viewWillAppearWithCellSize(_ cellSize: CGSize) func albumImageClicked(_ index: Int) -> Bool func numberOfItemsInSection(_ section: Int) -> Int func presentCell(_ cell: ImageCell, atIndex: Int) -> ImageCell func scrolledToCells(_ range: CountableRange<Int>, increasing: Bool) func albumTitlePressed(_ navigationController: UINavigationController?) }
bsd-3-clause
auiom/DYZB
斗鱼/斗鱼/AppDelegate.swift
1
2172
// // AppDelegate.swift // 斗鱼 // // Created by 王文发 on 2016/12/27. // Copyright © 2016年 王文发. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
VolodymyrShlikhta/InstaClone
InstaClone/SignInViewController.swift
1
2700
// // SignInViewController.swift // InstaClone // // Created by Relorie on 6/4/17. // Copyright © 2017 Relorie. All rights reserved. // import UIKit import FirebaseAuth import SVProgressHUD class SignInViewController: UIViewController { @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var signInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() Utilities.configureTextFieldsAppearence([emailTextField, passwordTextField]) handleTextFields() signInButton.isEnabled = false signInButton.tintColor = .lightGray } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if Auth.auth().currentUser != nil { let currentUserUid = Auth.auth().currentUser?.uid Utilities.getFromDatabaseUserInfo(forUser: CurrentUser.sharedInstance, withUid: currentUserUid!) self.performSegue(withIdentifier: "signInToTabbsVC", sender: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @IBAction func performSignIn(_ sender: UIButton) { view.endEditing(true) SVProgressHUD.show(withStatus: "Logging in...") AuthService.signIn(email: emailTextField.text!, password: passwordTextField.text!, onSuccess: { self.performSegue(withIdentifier: "signInToTabbsVC", sender: nil); SVProgressHUD.showSuccess(withStatus: "Welcome")}, onError: { error in SVProgressHUD.showError(withStatus: "\(error!)")} ) } func handleTextFields() { emailTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged) passwordTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged) } @objc func textFieldDidChange() { guard let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty else { signInButton.setTitleColor(UIColor.lightText, for: UIControlState.normal) signInButton.isEnabled = false return } signInButton.setTitleColor(UIColor.white, for: UIControlState.normal) signInButton.isEnabled = true } }
mit
thankmelater23/MyFitZ
MyFitZ/DetailedViewController.swift
1
26584
// DetailedViewController.swift // myFitz // // Created by Andre Villanueva on 1/13/15. // Copyright (c) 2015 BangBangStudios. All rights reserved. // import UIKit import CRToast //import DKChainableAnimationKit //import Crashlytics //MARK: - DetailedViewController Class class DetailedViewController: UIViewController{ //MARK: -Outlets @IBOutlet var tableView: UITableView! ///Views main image of the Item being presented @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var wearButton: UIButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var editButton: UIButton! //MARK: -Variables @objc var item: Item = Item() ///Dictionary path to item @objc var path: [String: String]! = [String: String]() //Core Data @objc let context = DataBaseController.getContext() //MARK: -View Methods override func viewDidLoad() { super.viewDidLoad() log.verbose(#function) self.setUp() self.view.backgroundColor = Cotton log.debug(self.item) // Do view setup here. // defaults.addAndSend("DETAIL_PAGE_COUNT") // self.logPageView() // Users_Wardrobe.clearAllContainersAndPopulate() } override func prepare(for segue: UIStoryboardSegue, sender: Any?){ // defer{ // log.verbose("Segue transfer: \(segue.identifier)") // } // // if segue.identifier == Segue.SEGUE_DETAIL_TO_MODEL // { // let modelTableViewController = segue.destination as! ModelTableViewController // // modelTableViewController.path = self.path // }else if segue.identifier == Segue.SEGUE_DETAIL_TO_EDIT{ // let editItemViewController = segue.destination as! EditItemViewController // editItemViewController.path = self.path // editItemViewController.viewItem = self.itemOfObject // editItemViewController.previousItem = self.itemOfObject // }else if segue.identifier == Segue.SEGUE_DETAIL_TO_CREATION{ // let createItemViewController: CreateItemViewController! = segue.destination as! CreateItemViewController // createItemViewController.lastVCSegue = Segue.SEGUE_DETAIL_TO_CREATION // }else if segue.identifier == Segue.SEGUE_DETAILED_TO_IMAGE{ // let imageViewController: ImageViewController! = segue.destination as! ImageViewController // // imageViewController.path = self.path // // imageViewController.itemName = self.itemOfObject.model // imageViewController.itemBrand = self.itemOfObject.brand // imageViewController.item = itemOfObject // // if item.image != nil{ // imageViewController.imageHolder = itemOfObject.image // }else{ // imageViewController.imageHolder = UIImage(named: BLANK_IMAGE_STRING)! // } // } } deinit{ log.verbose(#function) } } //MARK: -Actions-DetailedViewController Extension extension DetailedViewController{ @IBAction func editButtonPressed(){ playSoundEffects(editSFX) defaults.addAndSend("EDIT_BUTTON_BUTTON_PRESSED") performSegue(withIdentifier: Segue.SEGUE_DETAIL_TO_EDIT, sender: self) } @IBAction func backButtonPressed(_ sender: UIBarButtonItem) { playSoundEffects(backSFX) performSegue(withIdentifier: Segue.SEGUE_DETAIL_TO_MODEL, sender: self) } @IBAction func deleteItem() { // let alert = UIAlertController(title: "Alert!", message:"Are you sure you want to delete", preferredStyle: .alert) // let act = UIAlertAction(title: "cancel", style: .default){_ in} // let action = UIAlertAction(title: "Delete", style: .destructive) { _ in // // Users_Wardrobe.deleteItem(self.itemOfObject.category, funcSubCategory: self.itemOfObject.subCategory, item: self.itemOfObject) // // self.performSegue(withIdentifier: Segue.SEGUE_DETAIL_TO_SELECTION, sender: nil) // } // // alert.addAction(action) // alert.addAction(act) // self.present(alert, animated: true, completion:nil) } @IBAction func wear() { if true{ self.wearActivate() }else{ self.sendItemToMyCloset() } self.performSegue(withIdentifier: Segue.SEGUE_DETAIL_TO_RECENT, sender: self) } //MARK: -Action sum Methods @objc func wearActivate(){ playSoundEffects(wearSFX) // // let dateFormatter = DateFormatter() // dateFormatter.dateStyle = .short // let newDate = dateFormatter.string(from: (Date())) // // // let dicOfOptions = [ // kCRToastTextKey: "Wear date UPDATED-From: " + self.item.lastTimeWorn + "-To : " + newDate, // kCRToastTextAlignmentKey : "NSTextAlignmentCenter", // kCRToastBackgroundColorKey : UIColor.blue, // kCRToastAnimationInTypeKey : "CRToastAnimationTypeGravity", // kCRToastAnimationOutTypeKey : "CRToastAnimationTypeGravity", // kCRToastAnimationInDirectionKey : "CRToastAnimationDirectionLeft", // kCRToastAnimationOutDirectionKey : "CRToastAnimationDirectionRight"] as [String : Any] // // CRToastManager.showNotification(options: dicOfOptions, completionBlock: {[unowned self] in // self.itemOfObject.lastTimeWorn = newDate // // self.itemOfObject.incrementTimesWorn() // // self.itemOfObject.populatePath(Users_Wardrobe.closetSelectionString) // // Users_Wardrobe.updateRecentWornCollectiion(self.itemOfObject.path) // // self.wearButtonAvailable() // // Users_Wardrobe.quickSave() // }) // // // defaults.addAndSend("WEAR_PRESSED_COUNT") } @objc func hideWearButton(){ wearButton.alpha = 0.5 // wearButton.backgroundColor = UIColor.grayColor() wearButton.isUserInteractionEnabled = false } @objc func showWearButton(){ wearButton.alpha = 1.0 // wearButton.backgroundColor = UIColor.clearColor() wearButton.isUserInteractionEnabled = true } @IBAction func showImage(){ self.performSegue(withIdentifier: Segue.SEGUE_DETAILED_TO_IMAGE, sender: self) } } //MARK: - TableView Methods extension DetailedViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1//Create constant }// Return the number of sections. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // if (section == 0){ // return DETAIL_TABLEVIEW_BASIC_SECTION_COUNT // } // // else if (section == 1){ // return DETAIL_TABLEVIEW_MISC_SECTION_COUNT // } // // else{ // log.warning("Incorect section") // return 0 // } return 11 }// Return the number of rows in the section. // func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { // if indexPath.row == 11{ return 500}else{return 250} // }//Random number returned to fix xcode bug func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 10{ return 200}else{return 50} }//Random number returned to fix xcode bug func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return createCellFromRequiredDictionary(row: indexPath.row) as DoubleLabelTableViewCell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { //FIXME: - Fix when item atributes are ready if (section == 0){ return String()//"Basic: " + String(describing: self.item.model) + "-" + String(describing: self.item.brand) }else{ return String()// "Misc: " + String(describing: self.item.model) + "-" + String(describing: self.item.brand) } }//Puts a text label in the header of the specified section func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = LeatherTexture let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.textLabel?.textColor = RawGoldTexture } @objc func createCellFromRequiredDictionary(row: Int) -> DoubleLabelTableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.DOUBLE_LABEL_CELL) as! DoubleLabelTableViewCell var keyAndValue: String! let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short let cal = Calendar.current switch row { case 0 : keyAndValue = ItemAttributeName.ITEM_MODEL_STRING if let value = self.item.model{ cell.configure(name: keyAndValue, infoString: value) }else{ cell.configure(name: keyAndValue, infoString: "N/A") } case 1 : keyAndValue = ItemAttributeName.ITEM_BRAND_STRING if let value = self.item.brand{ cell.configure(name: keyAndValue, infoString: value) }else{ cell.configure(name: keyAndValue, infoString: "N/A") } case 2 : keyAndValue = ItemAttributeName.ITEM_CATEGORY_STRING if let value = self.item.category{ cell.configure(name: keyAndValue, infoString: value) }else{ cell.configure(name: keyAndValue, infoString: "N/A") } case 3 : keyAndValue = ItemAttributeName.ITEM_SUBCATEGORY_STRING cell.configure(name: keyAndValue, infoString: item.subCategory!) case 4 : keyAndValue = ItemAttributeName.ITEM_PRICE_STRING cell.configure(name: keyAndValue, infoString: (item.price.description)) case 5 : keyAndValue = ItemAttributeName.ITEM_FAVORITED_STRING let fav = self.item.isFavorite cell.configure(name: keyAndValue, infoString: (fav.description)) // case 6 : // keyAndValue = ItemAttributeName.ITEM_ISTHISNEW_STRING // let bool = self.item.isThisNew // var value = "No" // if bool == true{ // value = "YES" // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: value) // } case 6: keyAndValue = ItemAttributeName.ITEM_TIMESWORN_STRING cell.configure(name: keyAndValue, infoString: item.timesWorn.description) case 7: keyAndValue = ItemAttributeName.ITEM_LASTTIMEWORN_STRING if let lastDate = self.item.lastTimeWorn{ let today = Date() let unitDay:NSCalendar.Unit = .day let unitMonth:NSCalendar.Unit = .month let unitYear:NSCalendar.Unit = .year let components = (cal as NSCalendar).components(unitDay, from: lastDate as Date, to: today, options: .wrapComponents) if let value = self.item.lastTimeWorn{ switch(components.day!){ case 1: cell.configure(name: keyAndValue, infoString:value.description + "Not Worn") case 0...500: cell.configure(name: keyAndValue, infoString:value.description + "-" + String(describing: (components.day)) + " Days ago") case 500...1000: let components = (cal as NSCalendar).components(unitMonth, from: lastDate as Date, to: today, options: .wrapComponents) cell.configure(name: keyAndValue, infoString:value.description + "-" + (components.month?.description)! + " Mnths ago") case 1000...Int.max: let components = (cal as NSCalendar).components(unitYear, from: lastDate as Date, to: today, options: .wrapComponents) cell.configure(name: keyAndValue, infoString:value.description + "-" + String(describing: (components.year)) + " Years ago") default: assertionFailure("This shouldint happen") } } }else{ cell.configure(name: keyAndValue, infoString: "N/A") } // case 9 : // keyAndValue = ItemAttributeName.ITEM_KIND_STRING // if let value = self.item.kind{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 10 : // keyAndValue = ItemAttributeName.ITEM_SIZE_STRING // if let value = self.item.size{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } case 8 : keyAndValue = ItemAttributeName.ITEM_INDEX_STRING let number = self.item.index cell.configure(name: keyAndValue, infoString: number.description) case 9 : keyAndValue = ItemAttributeName.ITEM_ID_STRING let number = self.item.id cell.configure(name: keyAndValue, infoString: number.description) //TODO: - Put id maker here // case 10 : // keyAndValue = ItemAttributeName.ITEM_DATEPURCHASERD_STRING // if let value = self.item.datePurchased{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 1 : // keyAndValue = ItemAttributeName.ITEM_COLOR_STRING // if let value = self.item.color{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 2 : // keyAndValue = ItemAttributeName.ITEM_SECONDARYCOLOR_STRING // if let value = self.item.secondaryColor{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // // case 3 : // keyAndValue = ItemAttributeName.ITEM_THIRDCOLOR_STRING // if let value = self.item.thirdColor{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } case 10 : keyAndValue = ItemAttributeName.ITEM_ITEMNOTES_STRING if let value = self.item.itemNotes{ cell.configure(name: keyAndValue, infoString: value) }else{ cell.configure(name: keyAndValue, infoString: "N/A") } // case 5 : // keyAndValue = ItemAttributeName.ITEM_DATERELEASED_STRING // if let value = self.item.dateReleased{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 11 : // keyAndValue = ItemAttributeName.ITEM_RETAILPRICE_STRING // if let value = self.item.retailPrice, value != UNSET_DOUBLE_VALUE{ // cell.configure(name: keyAndValue, infoString: value.description) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // // case 7 : // keyAndValue = ItemAttributeName.ITEM_CONDITION_STRING // if let value = self.item.condition{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // // case 8 : // keyAndValue = ItemAttributeName.ITEM_PRIMARYMATERIAL_STRING // if let value = self.item.primaryMaterial{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 9: // keyAndValue = ItemAttributeName.ITEM_SECONDAY_MATERIAL_STRING // if let value = self.item.secondaryMaterial{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 10: // keyAndValue = ItemAttributeName.ITEM_STORELURL_STRING // if let value = self.item.sellerURL{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 11 : // keyAndValue = ItemAttributeName.ITEM_STORELOCATION_STRING // if let value = self.item.storeLocation{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 12 : // keyAndValue = ItemAttributeName.ITEM_SELLERNAME_STRING // if let value = self.item.sellerName{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 0 : // keyAndValue = ItemAttributeName.ITEM_DATEPURCHASERD_STRING // if let value = self.item.datePurchased{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 1 : // keyAndValue = ItemAttributeName.ITEM_COLOR_STRING // if let value = self.item.color{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // case 2 : // keyAndValue = ItemAttributeName.ITEM_SECONDARYCOLOR_STRING // if let value = self.item.secondaryColor{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } // // case 3 : // keyAndValue = ItemAttributeName.ITEM_THIRDCOLOR_STRING // if let value = self.item.thirdColor{ // cell.configure(name: keyAndValue, infoString: value) // }else{ // cell.configure(name: keyAndValue, infoString: "N/A") // } default: assertionFailure("Row does not exist to create cell of required type. ROW: \(row)") } return cell as DoubleLabelTableViewCell } ///Returns cell of Optional dictionary } //MARK: - Initializer Created Methods extension DetailedViewController{ @objc func setUp(){ self.animateAllButtons() self.buttonIsWearOrGot() self.setTitle() self.customizeTableView() self.wearButtonAvailable() self.setItem() //self.wearButton.animation.makeScale(0.0).moveX(-20).moveY(-20).makeBorderWidth(5.0).makeBorderColor(UIColor.blackColor()).animate(1.5) //self.wearButton.animation.makeScale(1.0).animate(0.5).moveX(20).moveY(20).makeBorderColor(UIColor.whiteColor()).animate(3.0) //self.wearButton.animation.makeScale(1.0).animateWithCompletion(1.0, { //self.wearButtonAvailable() //}) }//Sets up view @objc func customizeTableView(){ self.tableView.dataSource = self self.tableView.delegate = self self.tableView.backgroundColor = SiliverSilkSheet self.tableView?.tintColor = LeatherTexture self.tableView.reloadData() } @objc func setTitle(){ // self.title = grabTitle(Users_Wardrobe.closetSelectionString, view: "Detail") if self.title == MY_CLOSET{ self.navigationController?.navigationBar.tintColor = MY_CLOSET_BAR_COLOR }else if self.title == MY_WANTS_CLOSET{ self.navigationController?.navigationBar.tintColor = MY_WANTS_CLOSET_BAR_COLOR } self.navigationController?.navigationBar.isTranslucent = false } @objc func setItem(){ // let entity = Item(context: context) itemImage.image = #imageLiteral(resourceName: "blank image") do{ let items = try context.fetch(Item.fetchRequest()) if items.count > 0{ item = items.first as! Item log.verbose("Count: \(items.count)") }else{ log.warning("No results found") log.debug("Creating new data base") } }catch{ log.error("Fetching Failed") } } } //MARK: - General Methods-DetailedViewController Exension extension DetailedViewController{ @objc func sendItemToMyCloset(){ //Put code here to send to closet } } //MARK: - Animations-DetailedViewController Exension extension DetailedViewController{ @objc func wearButtonAvailable(){ // let daysLastWorn:Int = item.lastTimeWorn.returnDaysInDate() // // if daysLastWorn < 1{ // hideWearButton() // }else{ // showWearButton() // } } @objc func buttonIsWearOrGot(){ // let closet = Users_Wardrobe.closetSelectionString // // if closet == MY_CLOSET{ // wearButton.titleLabel?.text = "WEAR" // }else if closet == MY_WANTS_CLOSET{ // wearButton.titleLabel?.text = "GOT" // } } } //MARK: - UI-DetailedViewController Extension extension DetailedViewController{ @objc func animateAllButtons(){ self.animateImage() self.animateButtons() } @objc func animateLogo(){ // logoCustomization(self.logoImage) } @objc func animateImage(){ imageCustomization(self.itemImage) } @objc func animateButtons(){ clearButtonCustomization(self.editButton) deleteButtonCustomization(self.deleteButton) wearButtonAnimation(self.wearButton) } } //MARK: -Anylitics-MakeTableViewController Extension //extension DetailedViewController{ // func logPageView(){ // GlobalBackgroundQueue.async(execute: { // // // let pageCount:Int? = defaults.returnIntValue("DETAIL_PAGE_COUNT") // let wearPressedCount:Int? = defaults.returnIntValue("WEAR_PRESSED_COUNT") // let editButtonPressed:Int? = defaults.returnIntValue("EDIT_BUTTON_BUTTON_PRESSED") // // Answers.logContentView(withName: "Detail Content View", // contentType: "Detail View", // contentId: "MF5", // customAttributes: ["DETAIL_PAGE_COUNT": pageCount!, // "WEAR_PRESSED_COUNT": wearPressedCount!, // "EDIT_BUTTON_BUTTON_PRESSED": editButtonPressed! // ]) // }) // } //}
mit
Shvier/Dota2Helper
Dota2Helper/Dota2Helper/Global/Network/DHNetworkRequestManager.swift
1
4017
// // DHNetworkRequestManager.swift // Dota2Helper // // Created by Shvier on 9/19/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit enum RequestType { case POST case GET case DEFAULT } class DHNetworkRequestManager: NSObject { static let sharedInstance = DHNetworkRequestManager() func requestWithUrl(type: RequestType, urlHeader: URL?, parameters: Any?, completion: @escaping (Data?, URLResponse?, Error?) -> Void) { let request: URLRequest? switch type { case .POST: request = convertUrlToPOSTRequest(urlHeader: urlHeader, parameters: parameters as! NSDictionary?) break; case .GET: request = convertUrlToGETRequset(urlHeader: urlHeader, parameters: parameters as! NSDictionary?) break; default: request = convertUrlToDEFAULTRequset(urlHeader: urlHeader, parameters: parameters as! NSArray?) break; } let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default let session: URLSession = URLSession(configuration: sessionConfig) let dataTask: URLSessionDataTask = session.dataTask(with: request!, completionHandler: completion) dataTask.resume() } func convertUrlParametersToPOSTUrl(parameters: NSDictionary?) -> String { if parameters != nil { let paramList = NSMutableArray() for subDict in parameters! { let tmpString = "\(subDict.0)=\(subDict.1)" paramList.add(tmpString) } let paramString = paramList.componentsJoined(by: "&") return paramString } else { return "" } } func convertUrlParametersToGETUrl(parameters: NSDictionary?) -> String { if parameters != nil { let paramList = NSMutableArray() for subDict in parameters! { let tmpString = "\(subDict.0)=\(subDict.1)" paramList.add(tmpString) } let paramString = paramList.componentsJoined(by: "&") return paramString } else { return "" } } func convertUrlParametersToDEFAULTUrl(parameters: NSArray?) -> String { if parameters != nil { let paramList = NSMutableArray() for subString in parameters! { paramList.add(subString as! String) } let paramString = paramList.componentsJoined(by: "/") return paramString } else { return "" } } func convertUrlToPOSTRequest(urlHeader: URL?, parameters: NSDictionary?) -> URLRequest { var request = URLRequest(url: urlHeader!) if (parameters != nil) && (parameters?.count)! > 0 { request.httpMethod = "POST" let paramString = convertUrlParametersToPOSTUrl(parameters: parameters!) let paramData = paramString.data(using: String.Encoding.utf8) request.httpBody = paramData } else { request.httpMethod = "GET" } return request } func convertUrlToGETRequset(urlHeader: URL?, parameters: NSDictionary?) -> URLRequest { let paramString = convertUrlParametersToGETUrl(parameters: parameters) let urlString: String = urlHeader!.absoluteString + "?" + paramString let url: URL = URL(string: urlString)! var request: URLRequest = URLRequest(url: url) request.httpMethod = "GET" return request; } func convertUrlToDEFAULTRequset(urlHeader: URL?, parameters: NSArray?) -> URLRequest { let paramString = convertUrlParametersToDEFAULTUrl(parameters: parameters) let urlString: String = urlHeader!.absoluteString + paramString let url: URL = URL(string: urlString)! var request: URLRequest = URLRequest(url: url) request.httpMethod = "GET" return request; } }
apache-2.0
marcusellison/lil-twitter
lil-twitter/ContainerViewController.swift
1
7883
// // ContainerViewController.swift // lil-twitter // // Created by Marcus J. Ellison on 5/31/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit enum SlideOutState { case BothCollapsed case LeftPanelExpanded case RightPanelExpanded } class ContainerViewController: UIViewController, MenuControllerDelegate, TweetCellDelegate { private var profileViewController: ProfileViewController! private var sidePanelViewController: SidePanelViewController! private var mentionsViewController: MentionsViewController! var centerNavigationController: UINavigationController! var centerViewController: TweetsViewController! var currentState: SlideOutState = .BothCollapsed { didSet { let shouldShowShadow = currentState != .BothCollapsed showShadowForCenterViewController(shouldShowShadow) } } var leftViewController: SidePanelViewController? let centerPanelExpandedOffset: CGFloat = 100 override func viewDidLoad() { super.viewDidLoad() centerViewController = UIStoryboard.centerViewController() centerViewController.tweetDelegate = self; centerNavigationController = UINavigationController(rootViewController: centerViewController) centerNavigationController.navigationBar.barTintColor = UIColor(red: 0.33, green: 0.674, blue: 0.933, alpha: 0) profileViewController = UIStoryboard.profileViewController() profileViewController.delegate = self mentionsViewController = UIStoryboard.mentionsViewController() mentionsViewController.delegate = self displayVC(centerNavigationController) // add gesture recognizer // var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:") // tapGesture.delegate = self // view.addGestureRecognizer(tapGesture) // // func handleTapGesture(sender: UITapGestureRecognizer) { // println("handleTap") // // if (sender.state == .Ended) { // animateLeftPanel(shouldExpand: false) // } // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } /* Main View Controller Delegate */ extension ContainerViewController: TweetsViewControllerDelegate { func toggleLeftPanel() { println("adding left panel") let notAlreadyExpanded = (currentState != .LeftPanelExpanded) println(notAlreadyExpanded) if notAlreadyExpanded { addLeftPanelViewController() } animateLeftPanel(shouldExpand: notAlreadyExpanded) } func addLeftPanelViewController() { if (leftViewController == nil) { leftViewController = UIStoryboard.leftViewController() addChildSidePanelController(leftViewController!) leftViewController?.delegate = self } } func addChildSidePanelController(sidePanelController: SidePanelViewController) { view.insertSubview(sidePanelController.view, atIndex: 0) addChildViewController(sidePanelController) sidePanelController.didMoveToParentViewController(self) println("insert child view controller") } func animateLeftPanel(#shouldExpand: Bool) { if (shouldExpand) { println("should open") currentState = .LeftPanelExpanded animateCenterPanelXPosition(targetPosition: CGRectGetWidth(centerNavigationController.view.frame) - centerPanelExpandedOffset) } else { animateCenterPanelXPosition(targetPosition: 0) { finished in self.currentState = .BothCollapsed println("\(self.leftViewController)") // self.leftViewController!.view.removeFromSuperview() self.leftViewController = nil; } } } func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: { self.centerNavigationController.view.frame.origin.x = targetPosition }, completion: completion) } func showShadowForCenterViewController(shouldShowShadow: Bool) { if (shouldShowShadow) { centerNavigationController.view.layer.shadowOpacity = 0.8 } else { centerNavigationController.view.layer.shadowOpacity = 0.0 } } ///////////The Code of the Code!!!///////// // Add gestures // var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:") // tapGesture.delegate = self // containerView.addGestureRecognizer(tapGesture) func showMentions() { displayVC(mentionsViewController) animateLeftPanel(shouldExpand: false) } func showProfile() { profileViewController.user = User.currentUser displayVC(profileViewController) animateLeftPanel(shouldExpand: false) } func showTimeline() { displayVC(centerNavigationController) //added instantiation - is this correct? animateLeftPanel(shouldExpand: false) } func displayVC(vc: UIViewController) { addChildViewController(vc) vc.view.frame = view.bounds view.addSubview(vc.view) vc.didMoveToParentViewController(self) } func userTapped(user: User) { println("code working here") } ///////////The Code of the Code!!!///////// } private extension UIStoryboard { class func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } class func leftViewController() -> SidePanelViewController? { return mainStoryboard().instantiateViewControllerWithIdentifier("LeftViewController") as? SidePanelViewController } class func centerViewController() -> TweetsViewController? { println("instantiated") return mainStoryboard().instantiateViewControllerWithIdentifier("TweetsViewController") as? TweetsViewController } // SETUP Profile class func profileViewController() -> ProfileViewController? { println("instantiating profile view") // profileViewController = storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController // profileViewController.isModal = false // profileViewController.delegate = self return mainStoryboard().instantiateViewControllerWithIdentifier("ProfileViewController") as? ProfileViewController } class func mentionsViewController() -> MentionsViewController? { println("instantiating profile view") // profileViewController = storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController // profileViewController.isModal = false // profileViewController.delegate = self return mainStoryboard().instantiateViewControllerWithIdentifier("MentionsViewController") as? MentionsViewController } }
mit
teamVCH/sway
sway/RecordingControlView.swift
1
2974
// // RecordingControlView.swift // AudioTest // // Created by Christopher McMahon on 10/16/15. // Copyright © 2015 codepath. All rights reserved. // import UIKit protocol RecordingControlViewDelegate { func setBackingAudio(view: RecordingControlView, url: NSURL) func startRecording(view: RecordingControlView, playBackingAudio: Bool) func stopRecording(view: RecordingControlView) func startPlaying(view: RecordingControlView) func stopPlaying(view: RecordingControlView) func bounce(view: RecordingControlView) } class RecordingControlView: UIView { @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var playBackingAudioWhileRecordingSwitch: UIButton! @IBOutlet weak var bounceButton: UIButton! var delegate: RecordingControlViewDelegate? var isRecording: Bool = false { didSet { recordButton.selected = isRecording playButton.enabled = !isRecording } } var isPlaying: Bool = false { didSet { playButton.selected = isPlaying recordButton.enabled = !isPlaying } } var currentTime: NSTimeInterval = 0 { didSet { currentTimeLabel.text = Recording.formatTime(currentTime, includeMs: true) } } @IBAction func onTapRecord(sender: UIButton) { if sender.selected { delegate?.stopRecording(self) isRecording = false } else { delegate?.startRecording(self, playBackingAudio: playBackingAudioWhileRecordingSwitch.selected) isRecording = true } } @IBAction func onTapHeadphones(sender: UIButton) { print("headphones: \(sender.selected)") sender.selected = !sender.selected sender.tintColor = sender.selected ? UIColor.blueColor() : UIColor.blackColor() } @IBAction func onTapPlay(sender: UIButton) { //UIBarButtonPause_2x if sender.selected { delegate?.stopPlaying(self) isPlaying = false } else { delegate?.startPlaying(self) isPlaying = true } } @IBAction func onTapBounce(sender: UIButton) { delegate?.bounce(self) } override func awakeFromNib() { super.awakeFromNib() let image = UIImage(named: "headphones")?.imageWithRenderingMode(.AlwaysTemplate) playBackingAudioWhileRecordingSwitch.setImage(image, forState: .Normal) playBackingAudioWhileRecordingSwitch.setImage(image, forState: .Selected) } /* // just for demo purposes; this will happen automatically in collaborate mode @IBAction func loadBackingTrack(sender: AnyObject) { delegate?.setBackingAudio(self, url: defaultBackingAudio) } */ }
mit
adamnemecek/AudioKit
Tests/AudioKitTests/ValidatedMD5s.swift
1
4667
import AVFoundation import XCTest extension XCTestCase { func testMD5(_ buffer: AVAudioPCMBuffer) { let localMD5 = buffer.md5 let name = self.description XCTAssertFalse(buffer.isSilent) XCTAssert(validatedMD5s[name] == buffer.md5, "\nFAILEDMD5 \"\(name)\": \"\(localMD5)\",") } } let validatedMD5s: [String: String] = [ "-[AmplitudeTapTests testDefault]": "e732ff601fd8b47b3bdb6c4aa65cb7f1", "-[AmplitudeTapTests testLeftStereoMode]": "e732ff601fd8b47b3bdb6c4aa65cb7f1", "-[AmplitudeTapTests testPeakAnalysisMode]": "e732ff601fd8b47b3bdb6c4aa65cb7f1", "-[AmplitudeTapTests testRightStereoMode]": "e732ff601fd8b47b3bdb6c4aa65cb7f1", "-[AppleSamplerTests testAmplitude]": "d0526514c48f769f48e237974a21a2e5", "-[AppleSamplerTests testPan]": "6802732a1a3d132485509187fe476f9a", "-[AppleSamplerTests testSamplePlayback]": "7e38e34c8d052d9730b24cddd160d328", "-[AppleSamplerTests testStop]": "b42b86f6a7ff3a6fc85eb1760226cba0", "-[AppleSamplerTests testVolume]": "0b71c337205812fb30c536a014af7765", "-[AudioPlayerTests testBasic]": "feb1367cee8917a890088b8967b8d422", "-[AudioPlayerTests testEngineRestart]": "b0dd4297f40fd11a2b648f6cb3aad13f", "-[AudioPlayerTests testGetCurrentTime]": "af7c73c8c8c6f43a811401246c10cba4", "-[AudioPlayerTests testToggleEditTime]": "a9efdd751d83178079faf2571fd5c928", "-[AudioPlayerTests testLoop]": "4288a0ae8722e446750e1e0b3b96068a", "-[AudioPlayerTests testPlayAfterPause]": "ff480a484c1995e69022d470d09e6747", "-[AudioPlayerTests testScheduleFile]": "ba487f42fa93379f0b24c7930d51fdd3", "-[AudioPlayerTests testSeek]": "3bba42419e6583797e166b7a6d4bb45d", "-[AudioPlayerTests testVolume]": "ba487f42fa93379f0b24c7930d51fdd3", "-[AudioPlayerTests testSwitchFilesDuringPlayback]": "5bd0d50c56837bfdac4d9881734d0f8e", "-[CompressorTests testAttackTime]": "f2da585c3e9838c1a41f1a5f34c467d0", "-[CompressorTests testDefault]": "3064ef82b30c512b2f426562a2ef3448", "-[CompressorTests testHeadRoom]": "98ac5f20a433ba5a858c461aa090d81f", "-[CompressorTests testMasterGain]": "b8ff41f64341a786bd6533670d238560", "-[CompressorTests testParameters]": "6b99deb194dd53e8ceb6428924d6666b", "-[CompressorTests testThreshold]": "e1133fc525a256a72db31453d293c47c", "-[FFTTapTests testBasic]": "68d1550a306b253f9d4c18cda0824d3a", "-[FFTTapTests testWithoutNormalization]": "68d1550a306b253f9d4c18cda0824d3a", "-[FFTTapTests testWithZeroPadding]": "68d1550a306b253f9d4c18cda0824d3a", "-[MixerTests testSplitConnection]": "6b2d34e86130813c7e7d9f1cf7a2a87c", "-[NodeTests testDisconnect]": "8c5c55d9f59f471ca1abb53672e3ffbf", "-[NodeTests testDynamicConnection]": "c61c69779df208d80f371881346635ce", "-[NodeTests testDynamicConnection2]": "8c5c55d9f59f471ca1abb53672e3ffbf", "-[NodeTests testDynamicConnection3]": "70e6414b0f09f42f70ca7c0b0d576e84", "-[NodeTests testDynamicOutput]": "faf8254c11a6b73eb3238d57b1c14a9f", "-[NodeTests testNodeBasic]": "7e9104f6cbe53a0e3b8ec2d041f56396", "-[NodeTests testNodeConnection]": "5fbcf0b327308ff4fc9b42292986e2d5", "-[NodeTests testNodeDetach]": "8c5c55d9f59f471ca1abb53672e3ffbf", "-[NodeTests testTwoEngines]": "42b1eafdf0fc632f46230ad0497a29bf", "-[PeakLimiterTests testAttackTime]": "8e221adb58aca54c3ad94bce33be27db", "-[PeakLimiterTests testDecayTime]": "5f3ea74e9760271596919bf5a41c5fab", "-[PeakLimiterTests testDecayTime2]": "a2a33f30e573380bdacea55ea9ca2dae", "-[PeakLimiterTests testDefault]": "61c67b55ea69bad8be2bbfe5d5cde055", "-[PeakLimiterTests testParameters]": "e4abd97f9f0a0826823c167fb7ae730b", "-[PeakLimiterTests testPreGain]": "2f1b0dd9020be6b1fa5b8799741baa5f", "-[PeakLimiterTests testPreGainChangingAfterEngineStarted]": "ed14bc85f1732bd77feaa417c0c20cae", "-[ReverbTests testBypass]": "6b2d34e86130813c7e7d9f1cf7a2a87c", "-[ReverbTests testCathedral]": "7f1a07c82349bcd989a7838fd3f5ca9d", "-[ReverbTests testDefault]": "28d2cb7a5c1e369ca66efa8931d31d4d", "-[ReverbTests testSmallRoom]": "747641220002d1c968d62acb7bea552c", "-[SequencerTrackTests testChangeTempo]": "3e05405bead660d36ebc9080920a6c1e", "-[SequencerTrackTests testLoop]": "3a7ebced69ddc6669932f4ee48dabe2b", "-[SequencerTrackTests testOneShot]": "3fbf53f1139a831b3e1a284140c8a53c", "-[SequencerTrackTests testTempo]": "1eb7efc6ea54eafbe616dfa8e1a3ef36", "-[TableTests testReverseSawtooth]": "b3188781c2e696f065629e2a86ef57a6", "-[TableTests testSawtooth]": "6f37a4d0df529995d7ff783053ff18fe", "-[TableTests testTriangle]": "789c1e77803a4f9d10063eb60ca03cea", ]
mit
aryehToDog/DYZB
DYZB/DYZB/Class/Home/View/WKAmuseMenuViewCell.swift
1
1898
// // WKAmuseMenuViewCell.swift // DYZB // // Created by 阿拉斯加的狗 on 2017/9/3. // Copyright © 2017年 阿拉斯加的🐶. All rights reserved. // import UIKit fileprivate let kGameViewCellId = "kGameViewCellId" class WKAmuseMenuViewCell: UICollectionViewCell { var anchorGroupModel: [WKAnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "WKGameViewCell", bundle: nil), forCellWithReuseIdentifier: kGameViewCellId) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW:CGFloat = self.frame.size.width / 4 let itemH:CGFloat = self.frame.size.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 collectionView.dataSource = self } } extension WKAmuseMenuViewCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // let modelGroup = anchorGroupModel[section] return self.anchorGroupModel!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameViewCellId, for: indexPath) as! WKGameViewCell cell.groupM = self.anchorGroupModel?[indexPath.item] cell.clipsToBounds = true return cell } }
apache-2.0
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/ViewControllers/Service/ServiceList/ServiceListViewController.swift
1
2512
// // ServiceListViewController.swift // WczasyNadBialym // // Created by Marek Hać on 26.04.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import UIKit import SVProgressHUD class ServiceListViewController: UITableViewController { let backgroundImageName = "background_blue" // these values will be assigned by parent view controller in prepare for segue var categoryNameShort: String = "" var categoryNameLong: String = "" lazy var viewModel: ServiceListViewModel = { return ServiceListViewModel() }() // init view model func initViewModel () { // initialize callback closures // used [weak self] to avoid retain cycle viewModel.categoryNameShort = self.categoryNameShort viewModel.reloadTableViewClosure = { [weak self] () in DispatchQueue.main.async { self?.tableView.reloadData() SVProgressHUD.dismiss() } } viewModel.fetchServices(for: categoryNameShort) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.addBlurSubview(image: backgroundImageName) } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = viewModel self.tableView.delegate = viewModel self.navigationItem.title = self.categoryNameLong SVProgressHUD.show() initViewModel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedCell = sender as? ServiceListCell { if segue.identifier == "showServiceDetails" { let controller = (segue.destination as! UINavigationController).topViewController as! ServiceDetailsViewController controller.selectedServiceId = String(selectedCell.serviceId!) controller.selectedServiceType = self.categoryNameShort controller.backgroundImage = selectedCell.realServiceImage; controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } }
gpl-3.0
AynurGaliev/Books-Shop
Sources/App/Models/Credential.swift
1
2936
import Vapor import Fluent import Foundation final class Credential: Model { private static let tokenTime: TimeInterval = 86400 //MARK: - Attributes var id: Node? var password: String var login: String var expiration_date: String? var token: String? //MARK: - Relationships var userId: Node? //MARK: - Private variables var exists: Bool = false convenience init(node: Node, userId: Node, in context: Context) throws { try self.init(node: node, in: context) self.userId = userId } init(password: String, login: String) { self.password = password self.login = login } init(node: Node, in context: Context) throws { self.id = try node.extract("id") self.password = try node.extract("password") self.login = try node.extract("login") self.expiration_date = try node.extract("expiration_date") self.token = try node.extract("token") self.userId = try node.extract("user_id") } func isTokenValid() throws -> Bool { guard let date = self.expiration_date, let expirationDate = ISO8601DateFormatter.date(from: date) else { throw Abort.badRequest } return Date() < expirationDate } func makeJSON() throws -> JSON { let node = try Node(node: [ "token" : self.token, "expiration_date" : self.expiration_date ]) return JSON(node) } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": self.id, "password": self.password, "login": self.login, "user_id": self.userId, "token": self.token, "expiration_date": self.expiration_date ]) } class func renewToken(credential: inout Credential) throws { credential.token = UUID().uuidString credential.expiration_date = Date().addingTimeInterval(Credential.tokenTime).ISO8601FormatString } } extension Credential: Preparation { static func prepare(_ database: Database) throws { try database.create("credentials") { (creator) in creator.id() creator.string("password", length: nil, optional: false, unique: true, default: nil) creator.string("login", length: nil, optional: false, unique: true, default: nil) creator.string("token", length: nil, optional: true, unique: false, default: nil) creator.string("expiration_date", length: nil, optional: true, unique: false, default: nil) creator.parent(User.self, optional: false, unique: true, default: nil) } } static func revert(_ database: Database) throws { try database.delete("credentials") } }
mit
blkbrds/intern09_final_project_tung_bien
MyApp/Model/Schema/CartItem.swift
1
491
// // CartItem.swift // MyApp // // Created by AST on 8/9/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import RealmS import RealmSwift final class CartItem: Object { dynamic var id = 0 dynamic var name = "" dynamic var thumbnailImage = "" dynamic var detail = "" dynamic var price = 0.0 dynamic var quantity = 1 dynamic var unit = "" override class func primaryKey() -> String? { return "id" } }
mit
teambition/SwipeableTableViewCell
SwipeableTableViewCellExample/BackgroundViewExampleViewController.swift
1
5193
// // BackgroundViewExampleViewController.swift // SwipeableTableViewCellExample // // Created by 洪鑫 on 16/6/5. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit import SwipeableTableViewCell class BackgroundViewExampleViewController: UITableViewController { fileprivate(set) var pushEnabled = false // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: - Helper fileprivate func setupUI() { tableView.tableFooterView = UIView() let switchView: UIView = { let titleView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 150, height: 40))) titleView.backgroundColor = .clear let titleLabel = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 99, height: 40))) titleLabel.backgroundColor = .clear titleLabel.text = "Push Enabled" titleLabel.font = .systemFont(ofSize: 14) titleLabel.textColor = .red titleView.addSubview(titleLabel) let pushSwitch = UISwitch() pushSwitch.frame.origin.x = 99 pushSwitch.frame.origin.y = (40 - pushSwitch.frame.height) / 2 pushSwitch.isOn = false pushSwitch.addTarget(self, action: #selector(pushSwitchValueChanged(_:)), for: .valueChanged) titleView.addSubview(pushSwitch) return titleView }() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: switchView) if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) } } } @objc func pushSwitchValueChanged(_ sender: UISwitch) { pushEnabled = sender.isOn } // MARK: - Table view data source and delegate override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 65 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "SwipeableCell with background view" case 1: return "UITableViewCell with background view" default: return nil } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: kBackgroundViewSwipeableCellID, for: indexPath) as! BackgroundViewSwipeableCell let delete = NSAttributedString(string: "删除", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var deleteAction = SwipeableCellAction(title: delete, image: UIImage(named: "delete-icon"), backgroundColor: UIColor(red: 255 / 255, green: 90 / 255, blue: 29 / 255, alpha: 1)) { print("删除") } let later = NSAttributedString(string: "稍后处理", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var laterAction = SwipeableCellAction(title: later, image: UIImage(named: "later-icon"), backgroundColor: UIColor(red: 3 / 255, green: 169 / 255, blue: 244 / 255, alpha: 1)) { print("稍后处理") } deleteAction.width = 100 deleteAction.verticalSpace = 6 laterAction.width = 100 laterAction.verticalSpace = 6 cell.actions = [deleteAction, laterAction] return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: kBackgroundViewCellID, for: indexPath) as! BackgroundViewCell return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if pushEnabled { performSegue(withIdentifier: "PushToViewController", sender: self) tableView.deselectRow(at: indexPath, animated: true) } } } @available(iOS 9.0, *) extension BackgroundViewExampleViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } let previewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") previewController.preferredContentSize = .zero previewingContext.sourceRect = cell.frame return previewController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } }
mit
fe9lix/Muon
MuonTests/FeedParserSpec.swift
2
2117
import Quick import Nimble import Muon let feed = "<rss><channel></channel></rss>" class FeedParserSpec: QuickSpec { override func spec() { var subject : FeedParser! = nil describe("Initializing a feedparser with empty string") { beforeEach { subject = FeedParser(string: "") } it("call onFailure if main is called") { let expectation = self.expectationWithDescription("errorShouldBeCalled") subject.failure {error in expect(error.localizedDescription).to(equal("No Feed Found")) expectation.fulfill() } subject.main() self.waitForExpectationsWithTimeout(1, handler: { _ in }) } } describe("Initializing a feedparser with a feed") { beforeEach { subject = FeedParser(string: feed) } it("should succeed when main is called") { var feed: Feed? = nil subject.success { feed = $0 } subject.main() expect(feed).toEventuallyNot(beNil()) } } describe("Initializing a feedparser without data") { beforeEach { subject = FeedParser() } it("immediately call onFailure if main is called") { var error: NSError? = nil subject.failure { error = $0 } subject.main() expect(error).toNot(beNil()) expect(error?.localizedDescription).to(equal("Must be configured with data")) } describe("after configuring") { beforeEach { subject.configureWithString(feed) } it("should succeed when main is called") { var feed: Feed? = nil subject.success { feed = $0 } subject.main() expect(feed).toEventuallyNot(beNil()) } } } } }
mit
pritidesai/incubator-openwhisk-wskdeploy
tests/src/integration/runtimetests/src/hello.swift
4
1015
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ func main(args: [String:Any]) -> [String:Any] { if let name = args["name"] as? String { return [ "greeting" : "Hello \(name)!" ] } else { return [ "greeting" : "Hello stranger!" ] } }
apache-2.0
shoheiyokoyama/Gemini
Example/Gemini/ViewControllers/RollRotationViewController.swift
1
4464
import UIKit import Gemini final class RollRotationViewController: UIViewController { @IBOutlet private weak var collectionView: GeminiCollectionView! { didSet { let nib = UINib(nibName: cellIdentifier, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) collectionView.backgroundColor = .clear collectionView.delegate = self collectionView.dataSource = self if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } collectionView.gemini .rollRotationAnimation() .rollEffect(rotationEffect) .scale(0.7) } } private let cellIdentifier = String(describing: ImageCollectionViewCell.self) private var rotationEffect = RollRotationEffect.rollUp private var scrollDirection = UICollectionView.ScrollDirection.horizontal private let images = Resource.image.images static func make(scrollDirection: UICollectionView.ScrollDirection, effect: RollRotationEffect) -> RollRotationViewController { let storyboard = UIStoryboard(name: "RollRotationViewController", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "RollRotationViewController") as! RollRotationViewController viewController.rotationEffect = effect viewController.scrollDirection = scrollDirection return viewController } override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewPagingFlowLayout() layout.scrollDirection = scrollDirection layout.itemSize = CGSize(width: view.bounds.width - 60, height: view.bounds.height - 100) layout.sectionInset = UIEdgeInsets(top: 50, left: 30, bottom: 50, right: 30) layout.minimumLineSpacing = 30 layout.minimumInteritemSpacing = 30 collectionView.collectionViewLayout = layout collectionView.decelerationRate = UIScrollView.DecelerationRate.fast navigationController?.setNavigationBarHidden(true, animated: false) let gesture = UITapGestureRecognizer(target: self, action: #selector(toggleNavigationBarHidden(_:))) gesture.cancelsTouchesInView = false view.addGestureRecognizer(gesture) let startColor = UIColor(red: 29 / 255, green: 44 / 255, blue: 76 / 255, alpha: 1) let endColor = UIColor(red: 3 / 255, green: 7 / 255, blue: 20 / 255, alpha: 1) let colors: [CGColor] = [startColor.cgColor, endColor.cgColor] let gradientLayer = CAGradientLayer() gradientLayer.colors = colors gradientLayer.frame.size = view.bounds.size view.layer.insertSublayer(gradientLayer, at: 0) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @objc private func toggleNavigationBarHidden(_ gestureRecognizer: UITapGestureRecognizer) { let isNavigationBarHidden = navigationController?.isNavigationBarHidden ?? true navigationController?.setNavigationBarHidden(!isNavigationBarHidden, animated: true) } } // MARK: - UIScrollViewDelegate extension RollRotationViewController { func scrollViewDidScroll(_ scrollView: UIScrollView) { collectionView.animateVisibleCells() } } // MARK: - UICollectionViewDelegate extension RollRotationViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? GeminiCell { self.collectionView.animateCell(cell) } } } // MARK: - UICollectionViewDataSource extension RollRotationViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCollectionViewCell cell.configure(with: images[indexPath.row]) self.collectionView.animateCell(cell) return cell } }
mit
crossroadlabs/Boilerplate
Tests/BoilerplateTests/CollectionsTests.swift
1
2124
// // CollectionsTests.swift // Boilerplate // // Created by Daniel Leping on 3/6/16. // Copyright © 2016 Crossroad Labs, LTD. All rights reserved. // import XCTest import Foundation import Result @testable import Boilerplate /* * Test coming from issue https://github.com/crossroadlabs/Boilerplate/issues/7 * Is here to make sure that Bolerplate zip does not collide with builtin zip function */ extension Dictionary { #if swift(>=3.0) init<S: Sequence> (_ seq: S) where S.Iterator.Element == Element { self.init() for (k, v) in seq { self[k] = v } } #else init<S: SequenceType where S.Generator.Element == Element> (_ seq: S) { self.init() for (k, v) in seq { self[k] = v } } #endif func mapValues<T>(transform: (Value)->T) -> Dictionary<Key,T> { #if swift(>=3.0) return zip(self.keys, self.values.map(transform))^ #else return Dictionary<Key,T>(zip(self.keys, self.values.map(transform))) #endif } } class CollectionsTests: XCTestCase { func enumerateSome(callback:(String)->Void) { callback("one") callback("two") callback("three") } func testEnumerator() { let reference = ["one", "two", "three"] let array = Array(enumerator: enumerateSome) XCTAssertEqual(array, reference) } func testToMap() { let tuples = [("one", 1), ("two", 2), ("three", 3)] let reference1 = ["one": 1, "two": 4, "three": 9] let reference2 = ["one": 1, "two": 2, "three": 3] let map1 = tuples^.map { (k, v) in return (k, v*v) }^ let map2 = toMap(tuples) XCTAssertEqual(map1, reference1) XCTAssertEqual(map2, reference2) } } #if os(Linux) extension CollectionsTests { static var allTests : [(String, (CollectionsTests) -> () throws -> Void)] { return [ ("testEnumerator", testEnumerator), ("testToMap", testToMap), ] } } #endif
apache-2.0
digipost/ios
Digipost/InvoiceBankViewController.swift
1
4218
// // Copyright (C) Posten Norge AS // // 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 class InvoiceBankViewController: UIViewController{ var invoiceBank : InvoiceBank = InvoiceBank() @IBOutlet weak var invoiceBankLogo: UIImageView!{ didSet{ if let logo = UIImage(named:"\(invoiceBank.logo)-large"){ self.invoiceBankLogo.image = logo } } } @IBOutlet weak var invoiceBankName: UILabel! { didSet { if(UIImage(named:"\(invoiceBank.logo)-large") == nil) { self.invoiceBankName.text = invoiceBank.name } } } @IBOutlet weak var invoiceBankContent: UILabel!{ didSet{ let invoiceBankContentString = invoiceBank.activeType2Agreement ? "invoice bank enabled content" : "invoice bank disabled content" self.invoiceBankContent.text = NSLocalizedString(invoiceBankContentString, comment:"invoice bank content") self.invoiceBankContent.sizeToFit() self.invoiceBankContent.lineBreakMode = NSLineBreakMode.byWordWrapping } } @IBOutlet weak var invoiceBankTitle: UILabel!{ didSet{ let invoiceBankTitleString = invoiceBank.activeType2Agreement ? "invoice bank enabled title" : "invoice bank disabled title" self.invoiceBankTitle.text = NSLocalizedString(invoiceBankTitleString, comment:"invoice bank title") } } @IBOutlet weak var openBankUrlButton: UIButton!{ didSet{ if(invoiceBank.haveRegistrationUrl()){ let openBankUrlButtonString = NSLocalizedString("invoice bank button link prefix", comment: "invoice bank button link") + invoiceBank.name + NSLocalizedString("invoice bank button link postfix", comment: "Invoice bank button link") self.openBankUrlButton.setTitle(openBankUrlButtonString, for: UIControlState()) }else{ self.openBankUrlButton.isHidden = true } } } @IBOutlet weak var invoiceBankReadMoreText: UIButton!{ didSet{ let invoiceBankReadMoreLinkString = invoiceBank.activeType2Agreement ? "invoice bank enabled read more link" : "invoice bank disabled read more link" self.invoiceBankReadMoreText.setTitle(NSLocalizedString(invoiceBankReadMoreLinkString, comment:"invoice bank read more link"), for:UIControlState()) } } @IBAction func openBankUrl(_ sender: AnyObject) { GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-oppsett-avtale-type-2-link", label: invoiceBank.name, value: nil) UIApplication.shared.openURL(URL(string:invoiceBank.registrationUrl)!) //Opens external bank website, should be opened in external browser } @IBAction func invoiceBankReadMore(_ sender: AnyObject) { if(invoiceBank.activeType2Agreement){ GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-digipost-faktura-åpne-sider", label: invoiceBank.name, value: nil) openExternalUrl(url: "https://digipost.no/faktura") }else{ GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-oppsett-avtale-type-1-link", label: invoiceBank.name, value: nil) openExternalUrl(url: "https://digipost.no/app/post#/faktura") } } func openExternalUrl(url: String){ if #available(iOS 9.0, *) { let svc = SFSafariViewController(url: NSURL(string: url)! as URL) self.present(svc, animated: true, completion: nil) } } }
apache-2.0
JohnSundell/SwiftKit
Tests/NumberTests.swift
1
1279
import XCTest class NumberTests: XCTestCase { func testFractionalValue() { XCTAssertEqual(Double(7.5).fractionalValue, 0.5) XCTAssertEqual(Double(7).fractionalValue, 0) } func testRoundedValueWithDecimalCount() { XCTAssertEqual(1.12021.roundedValueWithDecimalCount(2), 1.12) XCTAssertEqual(1.12021.roundedValueWithDecimalCount(5), 1.12021) XCTAssertEqual(1.12021.roundedValueWithDecimalCount(7), 1.12021) } func testIsEvenlyDivisible() { XCTAssertTrue(0.isEvenlyDivisibleBy(2)) XCTAssertTrue(4.isEvenlyDivisibleBy(2)) XCTAssertFalse(4.4.isEvenlyDivisibleBy(2)) XCTAssertFalse(3.isEvenlyDivisibleBy(2)) } func testToString() { XCTAssertEqual(7.toString(), "7") XCTAssertEqual(Int(-7).toString(), "-7") XCTAssertEqual(UInt(7).toString(), "7") XCTAssertEqual(UInt32(7).toString(), "7") XCTAssertEqual(Double(7).toString(), "7.0") XCTAssertEqual(Double(7.7).toString(), "7.7") XCTAssertEqual(CGFloat(7).toString(), "7.0") XCTAssertEqual(CGFloat(7.7).toString(), "7.7") } func testFloor() { XCTAssertEqual(Double(7.5).floor(), 7) XCTAssertEqual(Double(7).floor(), 7) } }
mit
ZakariyyaSv/LYNetwork
LYNetwork/Source/LYBatchRequestAgent.swift
1
2080
// // LYBatchRequestAgent.swift // // Copyright (c) 2017 LYNetwork https://github.com/ZakariyyaSv/LYNetwork // // 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 /// LYBatchRequestAgent handles batch request management. It keeps track of all /// the batch requests. public class LYBatchRequestAgent { // MARK: - Properties // MARK: Singleton /// Get the shared batch request agent. static let sharedAgent: LYBatchRequestAgent = LYBatchRequestAgent() // MARK: Private Properties private var requestList: [LYBatchRequest] // MARK: - Methods // MARK: Public Methods /// Add a batch request. public func addBatchRequest(_ request: LYBatchRequest) { lysynchronized(self) { self.requestList.append(request) } } /// Remove a previously added batch request. public func removeBatchRequest(_ request: LYBatchRequest) { lysynchronized(self) { self.requestList.remove(request) } } // MARK: Initializer private init() { self.requestList = [] } }
mit
meninsilicium/apple-swifty
JSON.playground/contents.swift
1
1873
//: # Swifty.JSON import Swift import Swifty import Foundation import Darwin //: # JSON examples //: A json as a string let json_string = "{ \"coordinate\" : { \"latitude\" : 46.2050295, \"longitude\" : 6.1440885, \"city\" : \"Geneva\" }, \"source\" : \"string\" }" //: ## Initialization //: with a raw string or NSData var json: JSONValue = [:] if let maybe_json = JSON.decode( json_string ).value { json = maybe_json } json.prettyprint() //: with literals json = [ "coordinate" : [ "latitude" : 46.2050295, "longitude" : 6.144, "city" : "Geneva" ], "source" : "literals" ] json.prettyprint() //: ## Read //: with direct access var json_longitude = json[ "coordinate", "longitude" ]?.double ?? 0 var json_latitude = json[ "coordinate", "latitude" ]?.double ?? 0 //: with a path var json_path: JSONPath = [ "coordinate", "latitude" ] var json_latitude_number = json[ json_path ]?.number ?? 0 json_latitude = json[ json_path ]?.double ?? 0 var json_city = json[ JSONPath( "coordinate", "city" ) ]?.string ?? "" //: ## Validation var json_validation = JSONValidation() // assess [ "coordinate", "latitude" ] json_validation.assess( json_path, optional: false ) { ( validation, json ) -> Bool in switch json { case .JSONNumber, .JSONDouble, .JSONInteger: let value = json.double return (value >= -180) || (value <= 180) default: return false } } // assess [ "coordinate", "longitude" ] json_validation.assess( [ "coordinate", "longitude" ], optional: true ) { ( validation, json ) -> Bool in switch json { case .JSONNumber, .JSONDouble, .JSONInteger: let value = json.double return (value >= -180) || (value <= 180) default: return false } } //: Validate let valid = json.validate( json_validation ) json_validation.validate( json ) //----------------------------------------------------------------
mpl-2.0
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/unittest_swift_reserved_ext.pb.swift
2
14385
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: unittest_swift_reserved_ext.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ // Protos/unittest_swift_reserved_ext.proto - test proto // // 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// Test Swift reserved words used as enum or message names /// // ----------------------------------------------------------------------------- import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct SwiftReservedTestExt2 { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Extension support defined in unittest_swift_reserved_ext.proto. extension ProtobufUnittest_SwiftReservedTest.TypeMessage { /// Will get _p added because it has no package/swift prefix to scope and /// would otherwise be a problem when added to the message. var debugDescription_p: Bool { get {return getExtensionValue(ext: Extensions_debugDescription) ?? false} set {setExtensionValue(ext: Extensions_debugDescription, value: newValue)} } /// Returns true if extension `Extensions_debugDescription` /// has been explicitly set. var hasDebugDescription_p: Bool { return hasExtensionValue(ext: Extensions_debugDescription) } /// Clears the value of extension `Extensions_debugDescription`. /// Subsequent reads from it will return its default value. mutating func clearDebugDescription_p() { clearExtensionValue(ext: Extensions_debugDescription) } /// These will get _p added for the same reasoning. var `as`: Bool { get {return getExtensionValue(ext: Extensions_as) ?? false} set {setExtensionValue(ext: Extensions_as, value: newValue)} } /// Returns true if extension `Extensions_as` /// has been explicitly set. var hasAs: Bool { return hasExtensionValue(ext: Extensions_as) } /// Clears the value of extension `Extensions_as`. /// Subsequent reads from it will return its default value. mutating func clearAs() { clearExtensionValue(ext: Extensions_as) } var `var`: Bool { get {return getExtensionValue(ext: Extensions_var) ?? false} set {setExtensionValue(ext: Extensions_var, value: newValue)} } /// Returns true if extension `Extensions_var` /// has been explicitly set. var hasVar: Bool { return hasExtensionValue(ext: Extensions_var) } /// Clears the value of extension `Extensions_var`. /// Subsequent reads from it will return its default value. mutating func clearVar() { clearExtensionValue(ext: Extensions_var) } var `try`: Bool { get {return getExtensionValue(ext: Extensions_try) ?? false} set {setExtensionValue(ext: Extensions_try, value: newValue)} } /// Returns true if extension `Extensions_try` /// has been explicitly set. var hasTry: Bool { return hasExtensionValue(ext: Extensions_try) } /// Clears the value of extension `Extensions_try`. /// Subsequent reads from it will return its default value. mutating func clearTry() { clearExtensionValue(ext: Extensions_try) } var `do`: Bool { get {return getExtensionValue(ext: Extensions_do) ?? false} set {setExtensionValue(ext: Extensions_do, value: newValue)} } /// Returns true if extension `Extensions_do` /// has been explicitly set. var hasDo: Bool { return hasExtensionValue(ext: Extensions_do) } /// Clears the value of extension `Extensions_do`. /// Subsequent reads from it will return its default value. mutating func clearDo() { clearExtensionValue(ext: Extensions_do) } var `nil`: Bool { get {return getExtensionValue(ext: Extensions_nil) ?? false} set {setExtensionValue(ext: Extensions_nil, value: newValue)} } /// Returns true if extension `Extensions_nil` /// has been explicitly set. var hasNil: Bool { return hasExtensionValue(ext: Extensions_nil) } /// Clears the value of extension `Extensions_nil`. /// Subsequent reads from it will return its default value. mutating func clearNil() { clearExtensionValue(ext: Extensions_nil) } var SwiftReservedTestExt2_hashValue: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.hashValue_` /// has been explicitly set. var hasSwiftReservedTestExt2_hashValue: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.hashValue_`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_hashValue() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_) } /// Reserved words, since these end up in the "enum Extensions", they /// can't just be get their names, and sanitation kicks. var SwiftReservedTestExt2_as: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.as) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.as, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.as` /// has been explicitly set. var hasSwiftReservedTestExt2_as: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.as) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.as`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_as() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.as) } var SwiftReservedTestExt2_var: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.var) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.var, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.var` /// has been explicitly set. var hasSwiftReservedTestExt2_var: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.var) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.var`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_var() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.var) } var SwiftReservedTestExt2_try: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.try) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.try, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.try` /// has been explicitly set. var hasSwiftReservedTestExt2_try: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.try) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.try`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_try() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.try) } var SwiftReservedTestExt2_do: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.do) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.do, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.do` /// has been explicitly set. var hasSwiftReservedTestExt2_do: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.do) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.do`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_do() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.do) } var SwiftReservedTestExt2_nil: Bool { get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil) ?? false} set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil, value: newValue)} } /// Returns true if extension `SwiftReservedTestExt2.Extensions.nil` /// has been explicitly set. var hasSwiftReservedTestExt2_nil: Bool { return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil) } /// Clears the value of extension `SwiftReservedTestExt2.Extensions.nil`. /// Subsequent reads from it will return its default value. mutating func clearSwiftReservedTestExt2_nil() { clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil) } } /// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by /// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed /// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create /// a larger `SwiftProtobuf.SimpleExtensionMap`. let UnittestSwiftReservedExt_Extensions: SwiftProtobuf.SimpleExtensionMap = [ Extensions_debugDescription, Extensions_as, Extensions_var, Extensions_try, Extensions_do, Extensions_nil, SwiftReservedTestExt2.Extensions.hashValue_, SwiftReservedTestExt2.Extensions.as, SwiftReservedTestExt2.Extensions.var, SwiftReservedTestExt2.Extensions.try, SwiftReservedTestExt2.Extensions.do, SwiftReservedTestExt2.Extensions.nil ] /// Will get _p added because it has no package/swift prefix to scope and /// would otherwise be a problem when added to the message. let Extensions_debugDescription = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1000, fieldName: "debugDescription" ) /// These will get _p added for the same reasoning. let Extensions_as = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1012, fieldName: "as" ) let Extensions_var = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1013, fieldName: "var" ) let Extensions_try = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1014, fieldName: "try" ) let Extensions_do = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1015, fieldName: "do" ) let Extensions_nil = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1016, fieldName: "nil" ) extension SwiftReservedTestExt2 { enum Extensions { static let hashValue_ = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1001, fieldName: "SwiftReservedTestExt2.hashValue" ) /// Reserved words, since these end up in the "enum Extensions", they /// can't just be get their names, and sanitation kicks. static let `as` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1022, fieldName: "SwiftReservedTestExt2.as" ) static let `var` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1023, fieldName: "SwiftReservedTestExt2.var" ) static let `try` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1024, fieldName: "SwiftReservedTestExt2.try" ) static let `do` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1025, fieldName: "SwiftReservedTestExt2.do" ) static let `nil` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>( _protobuf_fieldNumber: 1026, fieldName: "SwiftReservedTestExt2.nil" ) } } // MARK: - Code below here is support for the SwiftProtobuf runtime. extension SwiftReservedTestExt2: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "SwiftReservedTestExt2" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } func _protobuf_generated_isEqualTo(other: SwiftReservedTestExt2) -> Bool { if unknownFields != other.unknownFields {return false} return true } }
gpl-3.0
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Service/Network/BBS3.swift
1
3543
// // BBS3 // // creds = AmazonCredentials(...) // data = NSData() // uploader = ElloS3(credentials: credentials, data: data) // .onSuccess() { (response : NSData) in } // .onFailure() { (error : NSError) in } // // NOT yet supported: // //.onProgress() { (progress : Float) in } // .start() import Foundation public class BBS3 { let filename: String let data: NSData let contentType: String let credentials: AmazonCredentials typealias SuccessHandler = (_ response: NSData) -> Void typealias FailureHandler = (_ error: NSError) -> Void typealias ProgressHandler = (_ progress: Float) -> Void private var successHandler: SuccessHandler? private var failureHandler: FailureHandler? private var progressHandler: ProgressHandler? public init(credentials: AmazonCredentials, filename: String, data: NSData, contentType: String) { self.filename = filename self.data = data self.contentType = contentType self.credentials = credentials } func onSuccess(handler: @escaping SuccessHandler) -> Self { self.successHandler = handler return self } func onFailure(handler: @escaping FailureHandler) -> Self { self.failureHandler = handler return self } func onProgress(handler: @escaping ProgressHandler) -> Self { self.progressHandler = handler return self } // this is just the uploading code, the initialization and handler code is // mostly the same func start() -> Self { let key = "\(credentials.prefix)/\(filename)" let url = NSURL(string: credentials.endpoint)! let builder = MultipartRequestBuilder(url: url, capacity: data.length) builder.addParam(name: "key", value: key) builder.addParam(name: "AWSAccessKeyId", value: credentials.accessKey) builder.addParam(name: "acl", value: "public-read") builder.addParam(name: "success_action_status", value: "201") builder.addParam(name: "policy", value: credentials.policy) builder.addParam(name: "signature", value: credentials.signature) builder.addParam(name: "Content-Type", value: self.contentType) // builder.addParam("Content-MD5", value: md5(data)) builder.addFile(name: "file", filename: filename, data: data, contentType: contentType) let request = builder.buildRequest() let session = URLSession.shared let task = session.dataTaskWithRequest(request as URLRequest) { (data: NSData?, response: URLResponse?, error: NSError?) in nextTick { let httpResponse = response as? NSHTTPURLResponse if let error = error { self.failureHandler?(error: error) } else if httpResponse?.statusCode >= 200 && httpResponse?.statusCode < 300 { if let data = data { self.successHandler?(response: data) } else { self.failureHandler?(error: NSError(domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"])) } } else { self.failureHandler?(error: NSError(domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"])) } } } task.resume() return self } }
mit
stripe/stripe-ios
Tests/Tests/LinkStubs.swift
1
3424
// // LinkStubs.swift // StripeiOS Tests // // Created by Ramon Torres on 3/31/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Foundation @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI struct LinkStubs { private init() {} } extension LinkStubs { struct PaymentMethodIndices { static let card = 0 static let cardWithFailingChecks = 1 static let bankAccount = 2 static let expiredCard = 3 static let notExisting = -1 } static func paymentMethods() -> [ConsumerPaymentDetails] { let calendar = Calendar(identifier: .gregorian) let nextYear = calendar.component(.year, from: Date()) + 1 return [ ConsumerPaymentDetails( stripeID: "1", details: .card( card: .init( expiryYear: nextYear, expiryMonth: 1, brand: "visa", last4: "4242", checks: .init(cvcCheck: .pass, allResponseFields: [:]), allResponseFields: [:] ) ), isDefault: true, allResponseFields: [:] ), ConsumerPaymentDetails( stripeID: "2", details: .card( card: .init( expiryYear: nextYear, expiryMonth: 1, brand: "mastercard", last4: "4444", checks: .init(cvcCheck: .fail, allResponseFields: [:]), allResponseFields: [:] ) ), isDefault: false, allResponseFields: [:] ), ConsumerPaymentDetails( stripeID: "3", details: .bankAccount( bankAccount: .init( iconCode: "capitalone", name: "Capital One", last4: "4242", allResponseFields: [:] ) ), isDefault: false, allResponseFields: [:] ), ConsumerPaymentDetails( stripeID: "4", details: .card( card: .init( expiryYear: 2020, expiryMonth: 1, brand: "american_express", last4: "0005", checks: .init(cvcCheck: .fail, allResponseFields: [:]), allResponseFields: [:] ) ), isDefault: false, allResponseFields: [:] ), ] } static func consumerSession() -> ConsumerSession { return ConsumerSession( clientSecret: "client_secret", emailAddress: "user@example.com", redactedPhoneNumber: "1********55", verificationSessions: [], authSessionClientSecret: nil, supportedPaymentDetailsTypes: [.card, .bankAccount], allResponseFields: [:] ) } }
mit
CodaFi/swift-compiler-crashes
fixed/24080-llvm-errs.swift
9
200
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where T:b{class B<T
mit
imobilize/Molib
Molib/Classes/Networking/DownloadManager/DownloaderOperation.swift
1
2884
import Foundation protocol DownloaderOperationDelegate { func downloaderOperationDidUpdateProgress(progress: Float, forTask: DownloaderTask) func downloaderOperationDidStartDownload(forTask: DownloaderTask) func downloaderOperationDidFailDownload(withError: Error, forTask: DownloaderTask) func downloaderOperationDidComplete(forTask: DownloaderTask) } class DownloaderOperation: Operation { var delegate: DownloaderOperationDelegate? private let downloaderTask: DownloaderTask private let networkOperationService: NetworkRequestService private var networkDownloadOperation: NetworkDownloadOperation? init(downloaderTask: DownloaderTask, networkOperationService: NetworkRequestService) { self.downloaderTask = downloaderTask self.networkOperationService = networkOperationService } override func main() { delegate?.downloaderOperationDidStartDownload(forTask: downloaderTask) let semaphore = DispatchSemaphore(value: 0) let downloadRequest = DataDownloadTask(downloaderTask: downloaderTask) { [weak self](_, errorOptional) in semaphore.signal() if let strongSelf = self { if let error = errorOptional { strongSelf.delegate?.downloaderOperationDidFailDownload(withError: error, forTask: strongSelf.downloaderTask) } else { strongSelf.delegate?.downloaderOperationDidComplete(forTask: strongSelf.downloaderTask) } } } networkDownloadOperation = networkOperationService.enqueueNetworkDownloadRequest(request: downloadRequest) networkDownloadOperation?.registerProgressUpdate(progressUpdate: handleProgressUpdate) semaphore.wait() } override func cancel() { networkDownloadOperation?.cancel() } func pause() { networkDownloadOperation?.pause() } func resume() { networkDownloadOperation?.resume() } func handleProgressUpdate(progress: Float) { delegate?.downloaderOperationDidUpdateProgress(progress: progress, forTask: downloaderTask) } func matchesDownloaderTask(task: DownloaderTask) -> Bool { return downloaderTask == task } override func isEqual(_ object: Any?) -> Bool { if let operation = object as? DownloaderOperation { return operation.downloaderTask.downloadURL == self.downloaderTask.downloadURL } return false } } extension DataDownloadTask { init(downloaderTask: DownloaderTask, taskCompletion: @escaping DataResponseCompletion) { self.fileName = downloaderTask.fileName self.downloadLocationURL = downloaderTask.downloadDestinationURL self.urlRequest = URLRequest(url: downloaderTask.downloadURL) self.taskCompletion = taskCompletion } }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/08248-swift-sourcemanager-getmessage.swift
11
216
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { func d { class c { enum B { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/06856-swift-archetypebuilder-resolvearchetype.swift
11
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct c<T : B<T> class B<T where T.e : B<T>
mit
tapwork/WikiLocation
WikiManager/WikiArticle.swift
1
1496
// // WikiArticle.swift // WikiLocation // // Created by Christian Menschel on 29.06.14. // Copyright (c) 2014 enterprise. All rights reserved. // import Foundation public class WikiArticle : NSObject { //Mark: - Properties public let distance:String! public let identifier:Int! public let latitutde:Double! public let longitude:Double! public let url:NSURL! public let title:String! //MARK: - Init init(json:Dictionary<String,AnyObject>) { super.init() if let title = json["title"] as? NSString { self.title = title } if let distance = json["dist"] as? NSNumber { self.distance = NSString(format: "Distance: %.2f Meter", distance.doubleValue) } if let id = json["pageid"] as? NSNumber { self.identifier = id.integerValue } if let latitutde = json["lat"] as? NSNumber { self.latitutde = latitutde.doubleValue } if let longitude = json["lon"] as? NSNumber { self.longitude = longitude.doubleValue } self.url = NSURL(string: "http://en.wikipedia.org/wiki?curid=\(self.identifier)") } //MARK: - Equality func hash() -> Int { return self.title.hash } override public func isEqual(object: AnyObject!) -> Bool { if self === object || self.hash == object.hash { return true } return false } }
mit
tbaranes/SwiftyUtils
Tests/Extensions/Foundation/NSLayoutConstraint/NSLayoutConstraintExtensionTests.swift
1
1755
// // Created by Tom Baranes on 25/04/16. // Copyright © 2016 Tom Baranes. All rights reserved. // import XCTest import SwiftyUtils final class NSLayoutConstraintExtensionTests: XCTestCase { private var view: SwiftyView! private var superview: SwiftyView! override func setUp() { super.setUp() view = SwiftyView(frame: CGRect(x: 0, y: 0, width: 100, height: 200)) superview = SwiftyView(frame: CGRect(x: 0, y: 0, width: 100, height: 200)) } override func tearDown() { super.tearDown() } } extension NSLayoutConstraintExtensionTests { func testApplyMultiplierWidth() { let constraint = NSLayoutConstraint(item: view!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 10) constraint.apply(multiplier: 0.5, toView: superview) XCTAssertEqual(constraint.constant, 50) } func testApplyMultiplierHeight() { let constraint = NSLayoutConstraint(item: view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 10) constraint.apply(multiplier: 0.5, toView: superview) XCTAssertEqual(constraint.constant, 100) } }
mit
LiskUser1234/SwiftyLisk
Lisk/Multisignature/MultisignatureAPI.swift
1
6352
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG 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 class MultisignatureAPI { private static let moduleName = "multisignatures" /// Create a multisig account /// /// - Parameters: /// - passphrase: The passphrase to sign the account's transactions /// - publicKey: Optional: The expected public key of the account derived from `passphrase` /// - secondPassphrase: Optional: the second passphrase to sign the account's transactions /// - minimumSignatures: The minimum amount of signatures to approve a transaction /// - lifetime: The interval of time within which the minimum amount of signatures per transaction must be recieved /// - keysgroup: Array of public keys that can sign any of the account's tranasactions. Each public key must have a "+" prefix. /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#create-multi-signature-account open class func create(passphrase: String, publicKey: String?, secondPassphrase: String?, minimumSignatures: Int, lifetime: Int, keysgroup: [String], callback: @escaping Callback) { var data = [ "secret": passphrase, "lifetime": String(lifetime), "min": String(minimumSignatures), "keysgroup": keysgroup ] as [String : Any] if let secondPassphrase = secondPassphrase { data["secondSecret"] = secondPassphrase } if let publicKey = publicKey { data["publicKey"] = publicKey } Api.request(module: moduleName, submodule: nil, method: .put, json: data, callback: callback) } /// Gets data relative to the multisig account with the given public key. /// /// - Parameters: /// - publicKey: The public key of the multisig account for which data will be retrieved /// - callback: The function that will be called with information about the request open class func getAccounts(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey" : publicKey ] Api.request(module: moduleName, submodule: "accounts", method: .get, query: data, callback: callback) } /// Signs a pending multisig transaction. /// /// - Parameters: /// - passphrase: The passphrase of the signer /// - publicKey: Optional: the public key of the signer, to check whether the passphrase's public key matches the expected public key /// - secondPassphrase: Optional: the second passphrase of the signer /// - transactionId: The id of the multisig transaction to sign /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#sign-transaction open class func sign(passphrase: String, publicKey: String?, secondPassphrase: String?, transactionId: String, callback: @escaping Callback) { var data = [ "secret": passphrase, "transactionId": transactionId ] if let publicKey = publicKey { data["publicKey"] = publicKey } if let secondPassphrase = secondPassphrase { data["secondPassphrase"] = secondPassphrase } Api.request(module: moduleName, submodule: "sign", method: .post, json: data, callback: callback) } /// Gets all pending transactions of the multisig account with the given public key /// /// - Parameters: /// - publicKey: The public key of the account whose pending transactions will be retrieved /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-pending-multi-signature-transactions open class func getPendingTransasctions(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey": publicKey ] Api.request(module: moduleName, submodule: "pending", method: .get, query: data, callback: callback) } }
mit
kdw9/TIY-Assignments
MuttCutts/MuttCutts/MapViewController.swift
1
1669
// // ViewController.swift // MuttCutts // // Created by Keron Williams on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let tiyOrlando = CLLocationCoordiante2DMake(28.540923, -81.38216) let tiyOrlandoAnnotation.coordinate = tiyOrlando tiyOrlandoAnnotation.coordinate = tiyOrlando tiyOrlandoAnnotation.title = "The Iron Yard" tiyOrlandoAnnotation.subtitle = "Orlando" let annotations = [tiyOrlandoAnnotation] mapView.addAnnotation(annotations) let viewRegion = MKCoodinateRegionMakeWithDistance (tiyOrlando, 2000, 2000) mapView.setRegion(viewRegion, animate: true) let tiyTampa = CLLocationCoordiante2DMake(27.770068, -82.63642) let tiyTampaAnnotation.coordinate = tiyOrlando tiyTampaAnnotation.coordinate = tiyOrlando tiyTampaAnnotation.title = "The Iron Yard" tiyTampaAnnotation.subtitle = "Tampa" let annotations = [tiyTampaAnnotation] mapView.addAnnotation(annotations) mapView.showAnnotations(annotations,animate) //let viewRegion = MKCoodinateRegionMakeWithDistance (tiyTampa, 2000, 2000) mapView.setRegion(viewRegion, animate: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc0-1.0
hollance/swift-algorithm-club
Fixed Size Array/FixedSizeArray.playground/Contents.swift
3
1151
//: Playground - noun: a place where people can play /* An unordered array with a maximum size. Performance is always O(1). */ struct FixedSizeArray<T> { private var maxSize: Int private var defaultValue: T private var array: [T] private (set) var count = 0 init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](repeating: defaultValue, count: maxSize) } subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } mutating func append(_ newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } mutating func removeAt(index: Int) -> T { assert(index >= 0) assert(index < count) count -= 1 let result = array[index] array[index] = array[count] array[count] = defaultValue return result } mutating func removeAll() { for i in 0..<count { array[i] = defaultValue } count = 0 } } var array = FixedSizeArray(maxSize: 5, defaultValue: 0) array.append(4) array.append(2) array[1] array.removeAt(index: 0) array.removeAll()
mit
nkirby/Humber
_lib/HMGithub/_src/Realm/GithubOverviewItem.swift
1
741
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import RealmSwift // ======================================================= public class GithubOverviewItem: Object { public dynamic var itemID = "" public dynamic var sortOrder = 0 public dynamic var type = "" public dynamic var title = "" public dynamic var value = 0 public dynamic var query = "" public dynamic var repoName = "" public dynamic var repoOwner = "" public dynamic var action = "" public dynamic var threshold = -1 public override class func primaryKey() -> String { return "itemID" } }
mit
hffmnn/Swiftz
SwiftzTests/ThoseSpec.swift
2
575
// // ThoseSpec.swift // swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015 TypeLift. All rights reserved. // import XCTest import Swiftz class ThoseSpec : XCTestCase { func testThose() { let this = Those<String, Int>.this("String") let that = Those<String, Int>.that(1) let both = Those<String, Int>.these("String", r: 1) XCTAssert((this.isThis() && that.isThat() && both.isThese()) == true, "") XCTAssert(this.toTuple("String", r: 1) == that.toTuple("String", r: 1), "") XCTAssert(both.bimap(identity, identity) == both, "") } }
bsd-3-clause
apple/swift
validation-test/compiler_crashers_fixed/01192-swift-constraints-constraintsystem-gettypeofmemberreference.swift
65
726
// 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 class Foo<T>: NSObject { init(foo: T) { (b: Int = 0) { } struct c<d : Sequence> { struct e : d { } } class d: f{ class func i {} protocol A { } class B { func d() -> String { } } class C: B, A { override func d() -> String { } func c() -> String { } } func e<T where T: A, T: B>(t: T) { } func i(c: () -> ()) { } var _ = i() {
apache-2.0
iosexample/LearnSwift
YourFirstiOSApp/MyApp/MyAppTests/MyAppTests.swift
1
906
// // MyAppTests.swift // MyAppTests // // Created by Dong on 16/7/16. // // import XCTest @testable import MyApp class MyAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
apache-2.0
KyoheiG3/RxSwift
Tests/RxCocoaTests/DelegateProxyTest+UIKit.swift
1
19132
// // DelegateProxyTest+UIKit.swift // Tests // // Created by Krunoslav Zaher on 12/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit @testable import RxCocoa @testable import RxSwift import XCTest // MARK: Protocols @objc protocol UITableViewDelegateSubclass : UITableViewDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc protocol UITableViewDataSourceSubclass : UITableViewDataSource , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc protocol UICollectionViewDelegateSubclass : UICollectionViewDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc protocol UICollectionViewDataSourceSubclass : UICollectionViewDataSource , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc protocol UIScrollViewDelegateSubclass : UIScrollViewDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } #if os(iOS) @objc protocol UISearchBarDelegateSubclass : UISearchBarDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } #endif @objc protocol UITextViewDelegateSubclass : UITextViewDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } #if os(iOS) extension RxSearchControllerDelegateProxy: TestDelegateProtocol { } extension RxPickerViewDelegateProxy: TestDelegateProtocol { } extension RxWebViewDelegateProxy: TestDelegateProtocol {} #endif @objc protocol UITabBarControllerDelegateSubclass : UITabBarControllerDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } @objc protocol UITabBarDelegateSubclass : UITabBarDelegate , TestDelegateProtocol { @objc optional func testEventHappened(_ value: Int) } // MARK: Tests // MARK: UITableView extension DelegateProxyTest { func test_UITableViewDelegateExtension() { performDelegateTest(UITableViewSubclass1(frame: CGRect.zero)) } func test_UITableViewDataSourceExtension() { performDelegateTest(UITableViewSubclass2(frame: CGRect.zero)) } } // MARK: UICollectionView extension DelegateProxyTest { func test_UICollectionViewDelegateExtension() { let layout = UICollectionViewFlowLayout() performDelegateTest(UICollectionViewSubclass1(frame: CGRect.zero, collectionViewLayout: layout)) } func test_UICollectionViewDataSourceExtension() { let layout = UICollectionViewFlowLayout() performDelegateTest(UICollectionViewSubclass2(frame: CGRect.zero, collectionViewLayout: layout)) } } // MARK: UIScrollView extension DelegateProxyTest { func test_UIScrollViewDelegateExtension() { performDelegateTest(UIScrollViewSubclass(frame: CGRect.zero)) } } // MARK: UISearchBar #if os(iOS) extension DelegateProxyTest { func test_UISearchBarDelegateExtension() { performDelegateTest(UISearchBarSubclass(frame: CGRect.zero)) } } #endif // MARK: UITextView extension DelegateProxyTest { func test_UITextViewDelegateExtension() { performDelegateTest(UITextViewSubclass(frame: CGRect.zero)) } } // MARK UISearchController #if os(iOS) extension DelegateProxyTest { func test_UISearchController() { performDelegateTest(UISearchControllerSubclass()) } } extension DelegateProxyTest { func test_UIPickerViewExtension() { performDelegateTest(UIPickerViewSubclass(frame: CGRect.zero)) } } #endif // MARK: UIWebView #if os(iOS) extension DelegateProxyTest { func test_UIWebViewDelegateExtension() { performDelegateTest(UIWebViewSubclass(frame: CGRect.zero)) } } #endif // MARK: UITabBarController extension DelegateProxyTest { func test_UITabBarControllerDelegateExtension() { performDelegateTest(UITabBarControllerSubclass()) } } // MARK: UITabBar extension DelegateProxyTest { func test_UITabBarDelegateExtension() { performDelegateTest(UITabBarSubclass()) } } // MARK: Mocks class ExtendTableViewDelegateProxy : RxTableViewDelegateProxy , UITableViewDelegateSubclass { weak fileprivate(set) var control: UITableViewSubclass1? required init(parentObject: AnyObject) { self.control = (parentObject as! UITableViewSubclass1) super.init(parentObject: parentObject) } } class UITableViewSubclass1 : UITableView , TestDelegateControl { override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return ExtendTableViewDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class ExtendTableViewDataSourceProxy : RxTableViewDataSourceProxy , UITableViewDelegateSubclass { weak fileprivate(set) var control: UITableViewSubclass2? required init(parentObject: AnyObject) { self.control = (parentObject as! UITableViewSubclass2) super.init(parentObject: parentObject) } } class UITableViewSubclass2 : UITableView , TestDelegateControl { override func createRxDataSourceProxy() -> RxTableViewDataSourceProxy { return ExtendTableViewDataSourceProxy(parentObject: self) } func doThatTest(_ value: Int) { if dataSource != nil { (dataSource as! TestDelegateProtocol).testEventHappened?(value) } } var testSentMessage: Observable<Int> { return rx.dataSource .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.dataSource .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxTableViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class ExtendCollectionViewDelegateProxy : RxCollectionViewDelegateProxy , UITableViewDelegateSubclass { weak fileprivate(set) var control: UICollectionViewSubclass1? required init(parentObject: AnyObject) { self.control = (parentObject as! UICollectionViewSubclass1) super.init(parentObject: parentObject) } } class UICollectionViewSubclass1 : UICollectionView , TestDelegateControl { override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return ExtendCollectionViewDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class ExtendCollectionViewDataSourceProxy : RxCollectionViewDataSourceProxy , UICollectionViewDelegateSubclass { weak fileprivate(set) var control: UICollectionViewSubclass2? required init(parentObject: AnyObject) { self.control = (parentObject as! UICollectionViewSubclass2) super.init(parentObject: parentObject) } } class UICollectionViewSubclass2 : UICollectionView , TestDelegateControl { override func createRxDataSourceProxy() -> RxCollectionViewDataSourceProxy { return ExtendCollectionViewDataSourceProxy(parentObject: self) } func doThatTest(_ value: Int) { if dataSource != nil { (dataSource as! TestDelegateProtocol).testEventHappened?(value) } } var testSentMessage: Observable<Int> { return rx.dataSource .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.dataSource .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxCollectionViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class ExtendScrollViewDelegateProxy : RxScrollViewDelegateProxy , UIScrollViewDelegateSubclass { weak fileprivate(set) var control: UIScrollViewSubclass? required init(parentObject: AnyObject) { self.control = (parentObject as! UIScrollViewSubclass) super.init(parentObject: parentObject) } } class UIScrollViewSubclass : UIScrollView , TestDelegateControl { override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return ExtendScrollViewDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } #if os(iOS) class ExtendSearchBarDelegateProxy : RxSearchBarDelegateProxy , UISearchBarDelegateSubclass { weak fileprivate(set) var control: UISearchBarSubclass? required init(parentObject: AnyObject) { self.control = (parentObject as! UISearchBarSubclass) super.init(parentObject: parentObject) } } class UISearchBarSubclass : UISearchBar , TestDelegateControl { override func createRxDelegateProxy() -> RxSearchBarDelegateProxy { return ExtendSearchBarDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxSearchBarDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } #endif class ExtendTextViewDelegateProxy : RxTextViewDelegateProxy , UITextViewDelegateSubclass { weak fileprivate(set) var control: UITextViewSubclass? required init(parentObject: AnyObject) { self.control = (parentObject as! UITextViewSubclass) super.init(parentObject: parentObject) } } class UITextViewSubclass : UITextView , TestDelegateControl { override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return ExtendTextViewDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } #if os(iOS) class UISearchControllerSubclass : UISearchController , TestDelegateControl { func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxSearchControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class UIPickerViewSubclass : UIPickerView , TestDelegateControl { func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxPickerViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class UIWebViewSubclass: UIWebView, TestDelegateControl { func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxWebViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } #endif class ExtendTabBarControllerDelegateProxy : RxTabBarControllerDelegateProxy , UITabBarControllerDelegateSubclass { weak fileprivate(set) var control: UITabBarControllerSubclass? required init(parentObject: AnyObject) { self.control = (parentObject as! UITabBarControllerSubclass) super.init(parentObject: parentObject) } } class ExtendTabBarDelegateProxy : RxTabBarDelegateProxy , UITabBarDelegateSubclass { weak fileprivate(set) var control: UITabBarSubclass? required init(parentObject: AnyObject) { self.control = (parentObject as! UITabBarSubclass) super.init(parentObject: parentObject) } } class UITabBarControllerSubclass : UITabBarController , TestDelegateControl { override func createRxDelegateProxy() -> RxTabBarControllerDelegateProxy { return ExtendTabBarControllerDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxTabBarControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } } class UITabBarSubclass: UITabBar, TestDelegateControl { override func createRxDelegateProxy() -> RxTabBarDelegateProxy { return ExtendTabBarDelegateProxy(parentObject: self) } func doThatTest(_ value: Int) { (delegate as! TestDelegateProtocol).testEventHappened?(value) } var testSentMessage: Observable<Int> { return rx.delegate .sentMessage(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } var testMethodInvoked: Observable<Int> { return rx.delegate .methodInvoked(#selector(TestDelegateProtocol.testEventHappened(_:))) .map { a in (a[0] as! NSNumber).intValue } } func setMineForwardDelegate(_ testDelegate: TestDelegateProtocol) -> Disposable { return RxTabBarDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self) } }
mit
imzyf/99-projects-of-swift
031-stopwatch/031-stopwatch/ViewController.swift
1
3284
// // ViewController.swift // 031-stopwatch // // Created by moma on 2018/3/28. // Copyright © 2018年 yifans. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - UI components @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var lapTimerLabel: UILabel! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var lapRestButton: UIButton! @IBOutlet weak var lapsTableView: UITableView! // MARK: - Variables fileprivate let mainStopwatch: Stopwatch = Stopwatch() fileprivate let lapStopwatch: Stopwatch = Stopwatch() fileprivate var isPlay: Bool = false fileprivate var laps: [String] = [] let stepTimeInterval: CGFloat = 0.035 override func viewDidLoad() { super.viewDidLoad() // 闭包设置 button 样式 let initCircleButton: (UIButton) -> Void = { button in button.layer.cornerRadius = 0.5 * button.bounds.size.width } initCircleButton(playPauseButton) initCircleButton(lapRestButton) playPauseButton.setTitle("Stop", for: .selected) lapRestButton.isEnabled = false } @IBAction func playPauseTimer(_ sender: UIButton) { if sender.isSelected { // stop mainStopwatch.timer.invalidate() } else { // start lapRestButton.isEnabled = true mainStopwatch.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.stepTimeInterval), repeats: true) { (time) in self.updateTimer(self.mainStopwatch, label: self.timerLabel) } sender.isSelected = !sender.isSelected // // Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: Selector.updateMainTimer, userInfo: nil, repeats: true) // } } func updateTimer(_ stopwatch: Stopwatch, label: UILabel) { stopwatch.counter = stopwatch.counter + stepTimeInterval let minutes = Int(stopwatch.counter / 60) let minuteText = minutes < 10 ? "0\(minutes)" : "\(minutes)" let seconds = stopwatch.counter.truncatingRemainder(dividingBy: 60) let secondeText = seconds < 10 ? String(format: "0%.2f", seconds) : String(format: "%.2f", seconds) label.text = minuteText + ":" + secondeText } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return laps.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) // if let labelNum = cell.viewWithTag(11) as? UILabel { // labelNum.text = "Lap \(laps.count - (indexPath as NSIndexPath).row)" // } // if let labelTimer = cell.viewWithTag(12) as? UILabel { // labelTimer.text = laps[laps.count - (indexPath as NSIndexPath).row - 1] // } return cell } }
mit
SuPair/firefox-ios
Client/Application/LeanplumIntegration.swift
1
15188
/* 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 AdSupport import Shared import Leanplum private let LPAppIdKey = "LeanplumAppId" private let LPProductionKeyKey = "LeanplumProductionKey" private let LPDevelopmentKeyKey = "LeanplumDevelopmentKey" private let AppRequestedUserNotificationsPrefKey = "applicationDidRequestUserNotificationPermissionPrefKey" private let FxaDevicesCountPrefKey = "FxaDevicesCount" // FxA Custom Leanplum message template for A/B testing push notifications. private struct LPMessage { static let FxAPrePush = "FxA Prepush v1" static let ArgAcceptAction = "Accept action" static let ArgCancelAction = "Cancel action" static let ArgTitleText = "Title.Text" static let ArgTitleColor = "Title.Color" static let ArgMessageText = "Message.Text" static let ArgMessageColor = "Message.Color" static let ArgAcceptButtonText = "Accept button.Text" static let ArgCancelButtonText = "Cancel button.Text" static let ArgCancelButtonTextColor = "Cancel button.Text color" // These defaults are not localized and will be overridden through Leanplum static let DefaultAskToAskTitle = "Firefox Sync Requires Push" static let DefaultAskToAskMessage = "Firefox will stay in sync faster with Push Notifications enabled." static let DefaultOkButtonText = "Enable Push" static let DefaultLaterButtonText = "Don’t Enable" } private let log = Logger.browserLogger enum LPEvent: String { case firstRun = "E_First_Run" case secondRun = "E_Second_Run" case openedApp = "E_Opened_App" case dismissedOnboarding = "E_Dismissed_Onboarding" case dismissedOnboardingShowLogin = "E_Dismissed_Onboarding_Showed_Login" case openedLogins = "Opened Login Manager" case openedBookmark = "E_Opened_Bookmark" case openedNewTab = "E_Opened_New_Tab" case openedPocketStory = "E_Opened_Pocket_Story" case interactWithURLBar = "E_Interact_With_Search_URL_Area" case savedBookmark = "E_Saved_Bookmark" case openedTelephoneLink = "Opened Telephone Link" case openedMailtoLink = "E_Opened_Mailto_Link" case saveImage = "E_Download_Media_Saved_Image" case savedLoginAndPassword = "E_Saved_Login_And_Password" case clearPrivateData = "E_Cleared_Private_Data" case downloadedFocus = "E_User_Downloaded_Focus" case downloadedPocket = "E_User_Downloaded_Pocket" case userSharedWebpage = "E_User_Tapped_Share_Button" case signsInFxa = "E_User_Signed_In_To_FxA" case useReaderView = "E_User_Used_Reader_View" case trackingProtectionSettings = "E_Tracking_Protection_Settings_Changed" case fxaSyncedNewDevice = "E_FXA_Synced_New_Device" case onboardingTestLoadedTooSlow = "E_Onboarding_Was_Swiped_Before_AB_Test_Could_Start" } struct LPAttributeKey { static let focusInstalled = "Focus Installed" static let klarInstalled = "Klar Installed" static let signedInSync = "Signed In Sync" static let mailtoIsDefault = "Mailto Is Default" static let pocketInstalled = "Pocket Installed" static let telemetryOptIn = "Telemetry Opt In" static let fxaAccountVerified = "FxA account is verified" static let fxaDeviceCount = "Number of devices in FxA account" } struct MozillaAppSchemes { static let focus = "firefox-focus" static let focusDE = "firefox-klar" static let pocket = "pocket" } private let supportedLocales = ["en_US", "de_DE", "en_GB", "en_CA", "en_AU", "zh_TW", "en_HK", "en_SG", "fr_FR", "it_IT", "id_ID", "id_ID", "pt_BR", "pl_PL", "ru_RU", "es_ES", "es_MX"] private struct LPSettings { var appId: String var developmentKey: String var productionKey: String } class LeanPlumClient { static let shared = LeanPlumClient() // Setup private weak var profile: Profile? private var prefs: Prefs? { return profile?.prefs } private var enabled: Bool = true // This defines an external Leanplum varible to enable/disable FxA prepush dialogs. // The primary result is having a feature flag controlled by Leanplum, and falling back // to prompting with native push permissions. private var useFxAPrePush: LPVar = LPVar.define("useFxAPrePush", with: false) var enablePocketVideo: LPVar = LPVar.define("pocketVideo", with: false) var enableDragDrop: LPVar = LPVar.define("tabTrayDrag", with: false) var introScreenVars = LPVar.define("IntroScreen", with: IntroCard.defaultCards().compactMap({ $0.asDictonary() })) private func isPrivateMode() -> Bool { // Need to be run on main thread since isInPrivateMode requires to be on the main thread. assert(Thread.isMainThread) return UIApplication.isInPrivateMode } func isLPEnabled() -> Bool { return enabled && Leanplum.hasStarted() } static func shouldEnable(profile: Profile) -> Bool { return AppConstants.MOZ_ENABLE_LEANPLUM && (profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true) } func setup(profile: Profile) { self.profile = profile } func recordSyncedClients(with profile: Profile?) { guard let profile = profile as? BrowserProfile else { return } profile.remoteClientsAndTabs.getClients() >>== { clients in let oldCount = self.prefs?.intForKey(FxaDevicesCountPrefKey) ?? 0 if clients.count > oldCount { self.track(event: .fxaSyncedNewDevice) } self.prefs?.setInt(Int32(clients.count), forKey: FxaDevicesCountPrefKey) Leanplum.setUserAttributes([LPAttributeKey.fxaDeviceCount: clients.count]) } } fileprivate func start() { guard let settings = getSettings(), supportedLocales.contains(Locale.current.identifier), !Leanplum.hasStarted() else { enabled = false log.error("LeanplumIntegration - Could not be started") return } if UIDevice.current.name.contains("MozMMADev") { log.info("LeanplumIntegration - Setting up for Development") Leanplum.setDeviceId(UIDevice.current.identifierForVendor?.uuidString) Leanplum.setAppId(settings.appId, withDevelopmentKey: settings.developmentKey) } else { log.info("LeanplumIntegration - Setting up for Production") Leanplum.setAppId(settings.appId, withProductionKey: settings.productionKey) } Leanplum.syncResourcesAsync(true) let attributes: [AnyHashable: Any] = [ LPAttributeKey.mailtoIsDefault: mailtoIsDefault(), LPAttributeKey.focusInstalled: focusInstalled(), LPAttributeKey.klarInstalled: klarInstalled(), LPAttributeKey.pocketInstalled: pocketInstalled(), LPAttributeKey.signedInSync: profile?.hasAccount() ?? false, LPAttributeKey.fxaAccountVerified: profile?.hasSyncableAccount() ?? false ] self.setupCustomTemplates() Leanplum.start(withUserId: nil, userAttributes: attributes, responseHandler: { _ in self.track(event: .openedApp) // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if self.prefs?.intForKey(PrefsKeys.IntroSeen) == nil { self.prefs?.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) self.track(event: .firstRun) } else if self.prefs?.boolForKey("SecondRun") == nil { self.prefs?.setBool(true, forKey: "SecondRun") self.track(event: .secondRun) } self.checkIfAppWasInstalled(key: PrefsKeys.HasFocusInstalled, isAppInstalled: self.focusInstalled(), lpEvent: .downloadedFocus) self.checkIfAppWasInstalled(key: PrefsKeys.HasPocketInstalled, isAppInstalled: self.pocketInstalled(), lpEvent: .downloadedPocket) self.recordSyncedClients(with: self.profile) }) } // Events func track(event: LPEvent, withParameters parameters: [String: String]? = nil) { guard isLPEnabled() else { return } ensureMainThread { guard !self.isPrivateMode() else { return } if let params = parameters { Leanplum.track(event.rawValue, withParameters: params) } else { Leanplum.track(event.rawValue) } } } func set(attributes: [AnyHashable: Any]) { guard isLPEnabled() else { return } ensureMainThread { if !self.isPrivateMode() { Leanplum.setUserAttributes(attributes) } } } func set(enabled: Bool) { // Setting up Test Mode stops sending things to server. if enabled { start() } self.enabled = enabled Leanplum.setTestModeEnabled(!enabled) } func isFxAPrePushEnabled() -> Bool { return AppConstants.MOZ_FXA_LEANPLUM_AB_PUSH_TEST && useFxAPrePush.boolValue() } /* This is used to determine if an app was installed after firefox was installed */ private func checkIfAppWasInstalled(key: String, isAppInstalled: Bool, lpEvent: LPEvent) { // if no key is present. create one and set it. // if the app is already installed then the flag will set true and the second block will never run if self.prefs?.boolForKey(key) == nil { self.prefs?.setBool(isAppInstalled, forKey: key) } // on a subsquent launch if the app is installed and the key is false then switch the flag to true if !(self.prefs?.boolForKey(key) ?? false), isAppInstalled { self.prefs?.setBool(isAppInstalled, forKey: key) self.track(event: lpEvent) } } private func canOpenApp(scheme: String) -> Bool { return URL(string: "\(scheme)://").flatMap { UIApplication.shared.canOpenURL($0) } ?? false } private func focusInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.focus) } private func klarInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.focusDE) } private func pocketInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.pocket) } private func mailtoIsDefault() -> Bool { return (prefs?.stringForKey(PrefsKeys.KeyMailToOption) ?? "mailto:") == "mailto:" } private func getSettings() -> LPSettings? { let bundle = Bundle.main guard let appId = bundle.object(forInfoDictionaryKey: LPAppIdKey) as? String, let productionKey = bundle.object(forInfoDictionaryKey: LPProductionKeyKey) as? String, let developmentKey = bundle.object(forInfoDictionaryKey: LPDevelopmentKeyKey) as? String else { return nil } return LPSettings(appId: appId, developmentKey: developmentKey, productionKey: productionKey) } // This must be called before `Leanplum.start` in order to correctly setup // custom message templates. private func setupCustomTemplates() { // These properties are exposed through the Leanplum web interface. // Ref: https://github.com/Leanplum/Leanplum-iOS-Samples/blob/master/iOS_customMessageTemplates/iOS_customMessageTemplates/LPMessageTemplates.m let args: [LPActionArg] = [ LPActionArg(named: LPMessage.ArgTitleText, with: LPMessage.DefaultAskToAskTitle), LPActionArg(named: LPMessage.ArgTitleColor, with: UIColor.black), LPActionArg(named: LPMessage.ArgMessageText, with: LPMessage.DefaultAskToAskMessage), LPActionArg(named: LPMessage.ArgMessageColor, with: UIColor.black), LPActionArg(named: LPMessage.ArgAcceptButtonText, with: LPMessage.DefaultOkButtonText), LPActionArg(named: LPMessage.ArgCancelAction, withAction: nil), LPActionArg(named: LPMessage.ArgCancelButtonText, with: LPMessage.DefaultLaterButtonText), LPActionArg(named: LPMessage.ArgCancelButtonTextColor, with: UIColor.Photon.Grey50) ] let responder: LeanplumActionBlock = { (context) -> Bool in // Before proceeding, double check that Leanplum FxA prepush config value has been enabled. if !self.isFxAPrePushEnabled() { return false } guard let context = context else { return false } // Don't display permission screen if they have already allowed/disabled push permissions if self.prefs?.boolForKey(AppRequestedUserNotificationsPrefKey) ?? false { FxALoginHelper.sharedInstance.readyForSyncing() return false } // Present Alert View onto the current top view controller let rootViewController = UIApplication.topViewController() let alert = UIAlertController(title: context.stringNamed(LPMessage.ArgTitleText), message: context.stringNamed(LPMessage.ArgMessageText), preferredStyle: .alert) alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgCancelButtonText), style: .cancel, handler: { (action) -> Void in // Log cancel event and call ready for syncing context.runTrackedActionNamed(LPMessage.ArgCancelAction) FxALoginHelper.sharedInstance.readyForSyncing() })) alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgAcceptButtonText), style: .default, handler: { (action) -> Void in // Log accept event and present push permission modal context.runTrackedActionNamed(LPMessage.ArgAcceptAction) FxALoginHelper.sharedInstance.requestUserNotifications(UIApplication.shared) self.prefs?.setBool(true, forKey: AppRequestedUserNotificationsPrefKey) })) rootViewController?.present(alert, animated: true, completion: nil) return true } // Register or update the custom Leanplum message Leanplum.defineAction(LPMessage.FxAPrePush, of: kLeanplumActionKindMessage, withArguments: args, withOptions: [:], withResponder: responder) } } extension UIApplication { // Extension to get the current top most view controller class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base } }
mpl-2.0
orta/RxSwift
RxSwift/RxSwift/Observables/Implementations/Switch.swift
1
4221
// // Switch.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Switch_<ElementType> : Sink<ElementType>, ObserverType { typealias Element = Observable<ElementType> typealias SwitchState = ( subscription: SingleAssignmentDisposable, innerSubscription: SerialDisposable, stopped: Bool, latest: Int, hasLatest: Bool ) let parent: Switch<ElementType> var lock = NSRecursiveLock() var switchState: SwitchState init(parent: Switch<ElementType>, observer: ObserverOf<ElementType>, cancel: Disposable) { self.parent = parent self.switchState = ( subscription: SingleAssignmentDisposable(), innerSubscription: SerialDisposable(), stopped: false, latest: 0, hasLatest: false ) super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = self.parent.sources.subscribe(self) let switchState = self.switchState switchState.subscription.setDisposable(subscription) return CompositeDisposable(switchState.subscription, switchState.innerSubscription) } func on(event: Event<Element>) { switch event { case .Next(let observable): let latest: Int = self.lock.calculateLocked { self.switchState.hasLatest = true self.switchState.latest = self.switchState.latest + 1 return self.switchState.latest } let d = SingleAssignmentDisposable() self.switchState.innerSubscription.setDisposable(d) let observer = SwitchIter(parent: self, id: latest, _self: d) let disposable = observable.value.subscribe(observer) d.setDisposable(disposable) case .Error(let error): self.lock.performLocked { self.observer.on(.Error(error)) self.dispose() } case .Completed: self.lock.performLocked { self.switchState.stopped = true self.switchState.subscription.dispose() if !self.switchState.hasLatest { self.observer.on(.Completed) self.dispose() } } } } } class SwitchIter<ElementType> : ObserverType { typealias Element = ElementType let parent: Switch_<Element> let id: Int let _self: Disposable init(parent: Switch_<Element>, id: Int, _self: Disposable) { self.parent = parent self.id = id self._self = _self } func on(event: Event<ElementType>) { return parent.lock.calculateLocked { state in let switchState = self.parent.switchState switch event { case .Next: break case .Error: fallthrough case .Completed: self._self.dispose() } if switchState.latest != self.id { return } let observer = self.parent.observer switch event { case .Next: observer.on(event) case .Error: observer.on(event) self.parent.dispose() case .Completed: parent.switchState.hasLatest = false if switchState.stopped { observer.on(event) self.parent.dispose() } } } } } class Switch<Element> : Producer<Element> { let sources: Observable<Observable<Element>> init(sources: Observable<Observable<Element>>) { self.sources = sources } override func run(observer: ObserverOf<Element>, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Switch_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift
3
1504
// // PathNode.swift // lottie-swift // // Created by Brandon Withrow on 1/16/19. // import CoreGraphics import Foundation // MARK: - ShapeNodeProperties final class ShapeNodeProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(shape: Shape) { keypathName = shape.name path = NodeProperty(provider: KeyframeInterpolator(keyframes: shape.path.keyframes)) keypathProperties = [ "Path" : path, ] properties = Array(keypathProperties.values) } // MARK: Internal var keypathName: String let path: NodeProperty<BezierPath> let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] } // MARK: - ShapeNode final class ShapeNode: AnimatorNode, PathNode { // MARK: Lifecycle init(parentNode: AnimatorNode?, shape: Shape) { pathOutput = PathOutputNode(parent: parentNode?.outputNode) properties = ShapeNodeProperties(shape: shape) self.parentNode = parentNode } // MARK: Internal let properties: ShapeNodeProperties let pathOutput: PathOutputNode let parentNode: AnimatorNode? var hasLocalUpdates = false var hasUpstreamUpdates = false var lastUpdateFrame: CGFloat? = nil // MARK: Animator Node var propertyMap: NodePropertyMap & KeypathSearchable { properties } var isEnabled = true { didSet { pathOutput.isEnabled = isEnabled } } func rebuildOutputs(frame: CGFloat) { pathOutput.setPath(properties.path.value, updateFrame: frame) } }
apache-2.0
fengzhihao123/FZHProjectInitializer
FZHProjectInitializer/FZHTabBarController/FZHCommonDeclare.swift
1
258
// // FZHCommonDeclare.swift // Demo // // Created by 冯志浩 on 2017/3/9. // Copyright © 2017年 FZH. All rights reserved. // import Foundation let SCREEN_WIDTH = UIScreen.main.bounds.size.width let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
mit
codeOfRobin/ShadowKit
TestingModalPresentation/TestingModalPresentation/ViewController.swift
1
5805
// // ViewController.swift // TestingModalPresentation // // Created by Mayur on 05/04/17. // Copyright © 2017 Mayur. All rights reserved. // import UIKit import UIKit class CardPresentationController: UIPresentationController { let tappableDismissView: UIView override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { self.tappableDismissView = UIView() super.init(presentedViewController: presentedViewController, presenting: presentingViewController) let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.dismissViewTapped)) tappableDismissView.addGestureRecognizer(tapGR) tappableDismissView.backgroundColor = .clear } //This method handles the dismissal of the current view controller, bringing the previous one forward, when the user taps outside func dismissViewTapped() { presentingViewController.dismiss(animated: true) { print("dismissed") print(self.presentingViewController) } } override func presentationTransitionWillBegin() { guard let fromView = self.presentingViewController.view else { return } let behindTransform = CGAffineTransform(scaleX: 0.9, y: 0.9) containerView?.addSubview(fromView) tappableDismissView.frame = CGRect(x: 0, y: 0, width: containerView?.frame.width ?? 0, height: CardPresentationManager.cardOffset) containerView?.addSubview(tappableDismissView) presentedViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in fromView.transform = behindTransform }, completion: { context in }) } override func dismissalTransitionWillBegin() { guard let toView = self.presentingViewController.view else { return } self.containerView?.addSubview(toView) presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in toView.transform = .identity }, completion: { (context) in UIApplication.shared.keyWindow!.addSubview(toView) }) } override func dismissalTransitionDidEnd(_ completed: Bool) { self.tappableDismissView.removeFromSuperview() } } class CardTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let pres = CardPresentationController(presentedViewController: presented, presenting: presenting) return pres } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CardPresentationManager() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CardDismissalManager() } } class CardPresentationManager: NSObject, UIViewControllerAnimatedTransitioning { static let cardOffset = CGFloat(60) static let scaleFactor = 0.9 public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } let bottomTransform = CGAffineTransform(translationX: 0, y: container.frame.height) toView.transform = bottomTransform let duration = self.transitionDuration(using: transitionContext) container.addSubview(toView) UIView.animate(withDuration: duration, animations: { toView.frame = CGRect(x: 0, y: CardPresentationManager.cardOffset, width: container.frame.width, height: container.frame.height - CardPresentationManager.cardOffset) }) { (completed) in transitionContext.completeTransition(completed) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } } class CardDismissalManager: NSObject, UIViewControllerAnimatedTransitioning { public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return } let duration = self.transitionDuration(using: transitionContext) fromView.frame = CGRect(x: 0, y: CardPresentationManager.cardOffset, width: container.frame.width, height: container.frame.height - CardPresentationManager.cardOffset) container.addSubview(fromView) UIView.animate(withDuration: duration, animations: { fromView.frame = CGRect(x: 0, y: container.frame.height, width: fromView.frame.width, height: fromView.frame.height) }) { (completed) in transitionContext.completeTransition(completed) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } } class ViewController: UIViewController { @IBAction func didTap(_ sender: UIButton) { let conversationNav = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ToPresentVC") as! ToPresentVC let cardTransitionDelegate = CardTransitioningDelegate() conversationNav.modalPresentationStyle = .custom conversationNav.transitioningDelegate = cardTransitionDelegate self.present(conversationNav, animated: true) { } } }
mit
longsirhero/DinDinShop
DinDinShopDemo/DinDinShopDemo/Utili/UIView+HUD.swift
1
1731
// // UIView+HUD.swift // DinDinShopDemo // // Created by longsirHERO on 2017/9/1. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import Foundation import UIKit import SVProgressHUD extension UIView { func showWarning(words:String) -> Void { DispatchQueue.main.async { SVProgressHUD.dismiss() SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.showInfo(withStatus: words) SVProgressHUD.setMinimumDismissTimeInterval(3.0) } } func showBusyHUD() -> Void { DispatchQueue.main.async { SVProgressHUD.dismiss() SVProgressHUD.show() SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.setMaximumDismissTimeInterval(30.0) } } func hideBusyHUD() -> Void { DispatchQueue.main.async { SVProgressHUD.dismiss() } } func showSuccess(words:String) -> Void { DispatchQueue.main.async { SVProgressHUD.dismiss() SVProgressHUD.show() SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.showSuccess(withStatus: words) SVProgressHUD.setMinimumDismissTimeInterval(3.0) } } func showError(words:String) -> Void { DispatchQueue.main.async { SVProgressHUD.dismiss() SVProgressHUD.show() SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.showError(withStatus: words) SVProgressHUD.setMinimumDismissTimeInterval(3.0) } } }
mit
CaueAlvesSilva/DropDownAlert
DropDownAlert/DropDownAlert/DropDownView/DropDownView.swift
1
3005
// // DropDownView.swift // DropDownAlert // // Created by Cauê Silva on 06/06/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import UIKit class DropDownView: UIView { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var messageLabel: UILabel! private var timer: Timer? private var visibleTime: TimeInterval = 4.0 private var animationDuration: TimeInterval = 0.8 private var animationDelay: TimeInterval = 0 private var springDamping: CGFloat = 0.9 private var springVelocity: CGFloat = 0.2 var alertHeight: CGFloat { return frame.height } override func awakeFromNib() { super.awakeFromNib() setAccessibilityIDs() addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.stopAnimation))) } private func setAccessibilityIDs() { accessibilityIdentifier = "DropDownAlert.view" messageLabel.accessibilityIdentifier = "DropDownAlert.alertImageView" iconImageView.accessibilityIdentifier = "DropDownAlert.alertMessageLabel" } func startAnimation(alertDTO: DropDownAlertLayout) { let dto = alertDTO.layoutDTO backgroundColor = dto.backgroundColor messageLabel.text = dto.message messageLabel.textColor = dto.messageColor iconImageView.image = dto.image iconImageView.tintColor = dto.messageColor self.visibleTime = dto.visibleTime startAnimation() } private func startAnimation() { print("# \(self.classForCoder): \(#function)") DispatchQueue.main.safeAsync { self.setAlertPosition(shouldDisplay: false) UIView.animate(withDuration: self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.springDamping, initialSpringVelocity: self.springVelocity, options: [], animations: { self.setAlertPosition(shouldDisplay: true) }, completion: nil) self.timer = Timer.scheduledTimer(timeInterval: self.visibleTime, target: self, selector: #selector(self.stopAnimation), userInfo: nil, repeats: false) } } func stopAnimation() { print("# \(self.classForCoder): \(#function)") timer?.invalidate() DispatchQueue.main.safeAsync { UIView.animate(withDuration: self.animationDuration, animations: { self.setAlertPosition(shouldDisplay: false) }, completion: { _ in DispatchQueue.main.safeAsync { self.removeFromSuperview() } }) } } private func setAlertPosition(shouldDisplay: Bool) { var frame = self.frame frame.origin.y = shouldDisplay ? 0 : -self.frame.size.width self.frame = frame } }
mit
scottrhoyt/Jolt
Jolt/Source/FloatingTypeExtensions/FloatingTypeFFTExtensions.swift
1
2345
// // FloatingTypeFFTExtensions.swift // Jolt // // Created by Scott Hoyt on 9/10/15. // Copyright © 2015 Scott Hoyt. All rights reserved. // import Accelerate // TODO: Write FFT Tests extension Double : VectorFFT { static public func fft(input: [Double]) -> [Double] { var real = [Double](input) var imaginary = [Double](count: input.count, repeatedValue: 0.0) var splitComplex = DSPDoubleSplitComplex(realp: &real, imagp: &imaginary) let length = vDSP_Length(Foundation.floor(Foundation.log2(Float(input.count)))) let radix = FFTRadix(kFFTRadix2) let weights = vDSP_create_fftsetupD(length, radix) vDSP_fft_zipD(weights, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) var magnitudes = [Double](count: input.count, repeatedValue: 0.0) vDSP_zvmagsD(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count)) var normalizedMagnitudes = [Double](count: input.count, repeatedValue: 0.0) // TODO: Should change? vDSP_vsmulD(Double.sqrt(magnitudes), 1, [2.0 / Double(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count)) vDSP_destroy_fftsetupD(weights) return normalizedMagnitudes } } extension Float : VectorFFT { static public func fft(input: [Float]) -> [Float] { var real = [Float](input) var imaginary = [Float](count: input.count, repeatedValue: 0.0) var splitComplex = DSPSplitComplex(realp: &real, imagp: &imaginary) let length = vDSP_Length(Foundation.floor(Foundation.log2(Float(input.count)))) let radix = FFTRadix(kFFTRadix2) let weights = vDSP_create_fftsetup(length, radix) vDSP_fft_zip(weights, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) var magnitudes = [Float](count: input.count, repeatedValue: 0.0) vDSP_zvmags(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count)) var normalizedMagnitudes = [Float](count: input.count, repeatedValue: 0.0) // TODO: Should change? vDSP_vsmul(Float.sqrt(magnitudes), 1, [2.0 / Float(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count)) vDSP_destroy_fftsetup(weights) return normalizedMagnitudes } }
mit
chatspry/rubygens
RubyGensTests/ObjectSnapshotSpec.swift
1
1033
// // ObjectSnapshotSpec.swift // RubyGensTests // // Created by Tyrone Trevorrow on 13/07/2015. // Copyright © 2015 Chatspry. All rights reserved. // import XCTest import Quick import Nimble class ObjectSnapshotSpec: QuickSpec { override func spec() { describe("snapshottable objects") { it("has specific key-value-coding keys derived from properties") { class A: NSObject, RubyCompatibleSnapshottable { @objc var X: String! @objc var Y: String! @objc var Z: String! } class B: A { @objc var A: String! } let object = A() let aProps = object.keyValueCodingKeysFromProperties expect(aProps).to(contain("X", "Y", "Z")) let b = B() let bProps = b.keyValueCodingKeysFromProperties expect(bProps).to(contain("X", "Y", "Z", "A")) } } } }
mit
nchitale/em-power
Empower/Card.swift
1
693
// // Card.swift // Empower // // Created by Nandini on 7/20/16. // Copyright © 2016 Empower. All rights reserved. // import UIKit class Card { // MARK: Properties var name: String var photo: UIImage? var backgroundText: NSAttributedString var subfield: String // MARK: Initialization init?(name: String, photo: UIImage?, backgroundText: NSAttributedString, subfield: String) { self.name = name self.photo = photo self.backgroundText = backgroundText self.subfield = subfield //Initialization should fail if there is no name if name.isEmpty { return nil } } }
mit
alafighting/NetworkForSwift
NetworkForSwift/Stream.swift
1
5749
/* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2014 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com) * * Contributors: * Kåre Morstøl, https://github.com/kareman - initial API and implementation. */ import Foundation // TODO: get encoding from environmental variable LC_CTYPE public var streamencoding = NSUTF8StringEncoding /** A stream of text. Does as much as possible lazily. */ public protocol ReadableStreamType : Streamable { /** Whatever amount of text the stream feels like providing. If the source is a file this will read everything at once. - returns: more text from the stream, or nil if we have reached the end. */ func readSome () -> String? /** Read everything at once. */ func read () -> String /** Lazily split the stream into lines. */ func lines () -> AnySequence<String> /** Enable stream to be used by "println" and "toString". */ func writeTo <Target : OutputStreamType> (inout target: Target) } /** An output stream, like standard output and standard error. */ public protocol WriteableStreamType : OutputStreamType { func write (string: String) func writeln (string: String) func writeln () /** Must be called on local streams when finished writing. */ func closeStream () } /** Create a stream from a String. */ public func stream (text: String) -> ReadableStreamType { let pipe = NSPipe() let input = pipe.fileHandleForWriting input.write(text) input.closeStream() return pipe.fileHandleForReading } /** Create a stream from a function returning a generator function, which is called every time the stream is asked for more text. stream { // initialisation... return { // called repeatedly by the resulting stream // return text, or return nil when done. } } - returns: The output stream. */ public func stream ( closure:() -> () -> String? ) -> ReadableStreamType { let getmoretext = closure() let pipe = NSPipe() let input: NSFileHandle = pipe.fileHandleForWriting input.writeabilityHandler = { filehandle in if let text = getmoretext() { filehandle.write(text) } else { // close the stream input.writeabilityHandler = nil } } return pipe.fileHandleForReading } /** Create a stream from a sequence of Strings. */ public func stream <Seq : SequenceType where Seq.Generator.Element == String> (sequence: Seq) -> ReadableStreamType { return stream { var generator = sequence.generate() return { generator.next() } } } /** Return a writable stream and a readable stream. What you write to the 1st one can be read from the 2nd one. Make sure to call closeStream() on the writable stream before you call read() on the readable one. */ public func streams () -> (WriteableStreamType, ReadableStreamType) { let pipe = NSPipe() return (pipe.fileHandleForWriting, pipe.fileHandleForReading) } /** Split a stream into parts separated by "delimiter". */ struct StringStreamGenerator : GeneratorType { private let stream: ReadableStreamType private let delimiter: String private var cache = "" init (stream: ReadableStreamType, delimiter: String = "\n") { self.stream = stream self.delimiter = delimiter } /** Pass on the stream until the next occurrence of "delimiter" */ mutating func next () -> String? { let (nextpart, returneddelimiter, remainder) = cache.partition(delimiter) let delimiterwasfound = returneddelimiter != "" cache = remainder if delimiterwasfound { return nextpart } else { if let newcache = stream.readSome() { // add the next part of the stream to what's left of the previous one, // and start again from the beginning of the function. cache = nextpart + newcache return next() } else { // the stream is empty and there are no more delimiters left. // return whatever is left, or nil if empty. return nextpart == "" ? nil : nextpart } } } } /** Split a stream lazily */ public func split (delimiter: String = "\n")(stream: ReadableStreamType) -> AnySequence<String> { return AnySequence({StringStreamGenerator (stream: stream, delimiter: delimiter)}) } /** Write something to a stream. something |> writeTo(writablestream) */ public func writeTo <T> (stream: WriteableStreamType)(input: T) { stream.write( String(input) ) } // needed to avoid `writeTo(SequenceType)` being called instead, // treating the string as a sequence of characters. /** Write a String to a writable stream. */ public func writeTo (stream: WriteableStreamType)(input: String) { stream.write(input) } /** Write a sequence to a stream. */ public func writeTo <S : SequenceType> (stream: WriteableStreamType)(seq: S) { for item in seq { item |> writeTo(stream) } } infix operator |>> { precedence 50 associativity left } /** Write something to a stream. something |>> writablestream */ public func |>> <T> (input: T, stream: WriteableStreamType) { writeTo(stream)(input: input) } // needed to avoid `func |>> <S : SequenceType>` being called instead, // treating the string as a sequence of characters. /** Write a String to a writable stream. */ public func |>> (text: String, stream: WriteableStreamType) { writeTo(stream)(input: text) } /** Write a sequence to a stream. */ public func |>> <S : SequenceType> (seq: S, stream: WriteableStreamType) { writeTo(stream)(seq: seq) }
gpl-2.0
mshhmzh/firefox-ios
Client/Frontend/Browser/ContextMenuHelper.swift
4
4576
/* 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 WebKit protocol ContextMenuHelperDelegate: class { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) } class ContextMenuHelper: NSObject, TabHelper, UIGestureRecognizerDelegate { private weak var tab: Tab? weak var delegate: ContextMenuHelperDelegate? private let gestureRecognizer = UILongPressGestureRecognizer() private weak var selectionGestureRecognizer: UIGestureRecognizer? struct Elements { let link: NSURL? let image: NSURL? } class func name() -> String { return "ContextMenuHelper" } /// Clicking an element with VoiceOver fires touchstart, but not touchend, causing the context /// menu to appear when it shouldn't (filed as rdar://22256909). As a workaround, disable the custom /// context menu for VoiceOver users. private var showCustomContextMenu: Bool { return !UIAccessibilityIsVoiceOverRunning() } required init(tab: Tab) { super.init() self.tab = tab let path = NSBundle.mainBundle().pathForResource("ContextMenu", ofType: "js")! let source = try! NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: false) tab.webView!.configuration.userContentController.addUserScript(userScript) // Add a gesture recognizer that disables the built-in context menu gesture recognizer. gestureRecognizer.delegate = self tab.webView!.addGestureRecognizer(gestureRecognizer) } func scriptMessageHandlerName() -> String? { return "contextMenuMessageHandler" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if !showCustomContextMenu { return } let data = message.body as! [String: AnyObject] // On sites where <a> elements have child text elements, the text selection delegate can be triggered // when we show a context menu. To prevent this, cancel the text selection delegate if we know the // user is long-pressing a link. if let handled = data["handled"] as? Bool where handled { // Setting `enabled = false` cancels the current gesture for this recognizer. selectionGestureRecognizer?.enabled = false selectionGestureRecognizer?.enabled = true } var linkURL: NSURL? if let urlString = data["link"] as? String { linkURL = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLAllowedCharacterSet())!) } var imageURL: NSURL? if let urlString = data["image"] as? String { imageURL = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLAllowedCharacterSet())!) } if linkURL != nil || imageURL != nil { let elements = Elements(link: linkURL, image: imageURL) delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: gestureRecognizer) } } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Hack to detect the built-in text selection gesture recognizer. if let otherDelegate = otherGestureRecognizer.delegate where String(otherDelegate).contains("_UIKeyboardBasedNonEditableTextSelectionGestureController") { selectionGestureRecognizer = otherGestureRecognizer } // Hack to detect the built-in context menu gesture recognizer. return otherGestureRecognizer is UILongPressGestureRecognizer && otherGestureRecognizer.delegate?.description.rangeOfString("WKContentView") != nil } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return showCustomContextMenu } }
mpl-2.0
mozilla-mobile/firefox-ios
Shared/NSUserDefaultsPrefs.swift
2
5096
// 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 open class NSUserDefaultsPrefs: Prefs { fileprivate let prefixWithDot: String fileprivate let userDefaults: UserDefaults open func getBranchPrefix() -> String { return self.prefixWithDot } public init(prefix: String, userDefaults: UserDefaults) { self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".") self.userDefaults = userDefaults } public init(prefix: String) { self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".") self.userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! } open func branch(_ branch: String) -> Prefs { let prefix = self.prefixWithDot + branch + "." return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults) } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. fileprivate func qualifyKey(_ key: String) -> String { return self.prefixWithDot + key } open func setInt(_ value: Int32, forKey defaultName: String) { // Why aren't you using userDefaults.setInteger? // Because userDefaults.getInteger returns a non-optional; it's impossible // to tell whether there's a value set, and you thus can't distinguish // between "not present" and zero. // Yeah, NSUserDefaults is meant to be used for storing "defaults", not data. setObject(NSNumber(value: value), forKey: defaultName) } open func setTimestamp(_ value: Timestamp, forKey defaultName: String) { setLong(value, forKey: defaultName) } open func setLong(_ value: UInt64, forKey defaultName: String) { setObject(NSNumber(value: value), forKey: defaultName) } open func setLong(_ value: Int64, forKey defaultName: String) { setObject(NSNumber(value: value), forKey: defaultName) } open func setString(_ value: String, forKey defaultName: String) { setObject(value as AnyObject?, forKey: defaultName) } open func setObject(_ value: Any?, forKey defaultName: String) { userDefaults.set(value, forKey: qualifyKey(defaultName)) } open func stringForKey(_ defaultName: String) -> String? { // stringForKey converts numbers to strings, which is almost always a bug. return userDefaults.object(forKey: qualifyKey(defaultName)) as? String } open func setBool(_ value: Bool, forKey defaultName: String) { setObject(NSNumber(value: value as Bool), forKey: defaultName) } open func boolForKey(_ defaultName: String) -> Bool? { // boolForKey just returns false if the key doesn't exist. We need to // distinguish between false and non-existent keys, so use objectForKey // and cast the result instead. let number = userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber return number?.boolValue } fileprivate func nsNumberForKey(_ defaultName: String) -> NSNumber? { return userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber } open func unsignedLongForKey(_ defaultName: String) -> UInt64? { return nsNumberForKey(defaultName)?.uint64Value } open func timestampForKey(_ defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } open func longForKey(_ defaultName: String) -> Int64? { return nsNumberForKey(defaultName)?.int64Value } open func objectForKey<T: Any>(_ defaultName: String) -> T? { return userDefaults.object(forKey: qualifyKey(defaultName)) as? T } open func intForKey(_ defaultName: String) -> Int32? { return nsNumberForKey(defaultName)?.int32Value } open func stringArrayForKey(_ defaultName: String) -> [String]? { let objects = userDefaults.stringArray(forKey: qualifyKey(defaultName)) if let strings = objects { return strings } return nil } open func arrayForKey(_ defaultName: String) -> [Any]? { return userDefaults.array(forKey: qualifyKey(defaultName)) as [Any]? } open func dictionaryForKey(_ defaultName: String) -> [String: Any]? { return userDefaults.dictionary(forKey: qualifyKey(defaultName)) as [String: Any]? } open func removeObjectForKey(_ defaultName: String) { userDefaults.removeObject(forKey: qualifyKey(defaultName)) } open func clearAll() { // TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites. // iOS Bug? Iterate and remove each manually for now. for key in userDefaults.dictionaryRepresentation().keys { if key.hasPrefix(prefixWithDot) { userDefaults.removeObject(forKey: key) } } } }
mpl-2.0
drawRect/Instagram_Stories
InstagramStories/Source/ImageStorer/IGImageRequestable.swift
1
1776
// // IGSetImage.swift // InstagramStories // // Created by Boominadha Prakash on 02/04/19. // Copyright © 2019 DrawRect. All rights reserved. // import Foundation import UIKit public typealias ImageResponse = (IGResult<UIImage, Error>) -> Void protocol IGImageRequestable { func setImage(urlString: String, placeHolderImage: UIImage?, completionBlock: ImageResponse?) } extension IGImageRequestable where Self: UIImageView { func setImage(urlString: String, placeHolderImage: UIImage? = nil, completionBlock: ImageResponse?) { self.image = (placeHolderImage != nil) ? placeHolderImage! : nil self.showActivityIndicator() if let cachedImage = IGCache.shared.object(forKey: urlString as AnyObject) as? UIImage { self.hideActivityIndicator() DispatchQueue.main.async { self.image = cachedImage } guard let completion = completionBlock else { return } return completion(.success(cachedImage)) }else { IGURLSession.default.downloadImage(using: urlString) { [weak self] (response) in guard let strongSelf = self else { return } strongSelf.hideActivityIndicator() switch response { case .success(let image): DispatchQueue.main.async { strongSelf.image = image } guard let completion = completionBlock else { return } return completion(.success(image)) case .failure(let error): guard let completion = completionBlock else { return } return completion(.failure(error)) } } } } }
mit
amonshiz/CoorinatorKit
CoordinatorKit_iOSTests/CoordinatorKit_iOSTests.swift
1
1033
// // CoordinatorKit_iOSTests.swift // CoordinatorKit_iOSTests // // Created by Andrew Monshizadeh on 12/19/15. // Copyright © 2015 Andrew Monshizadeh. All rights reserved. // import XCTest @testable import CoordinatorKit_iOS class CoordinatorKit_iOSTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
ioscreator/ioscreator
IOSStepperTutorial/IOSStepperTutorial/ViewController.swift
1
622
// // ViewController.swift // IOSStepperTutorial // // Created by Arthur Knopper on 04/02/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var stepper: UIStepper! @IBAction func stepperValueChanged(_ sender: UIStepper) { valueLabel.text = Int(sender.value).description } override func viewDidLoad() { super.viewDidLoad() stepper.wraps = true stepper.autorepeat = true stepper.maximumValue = 10 } }
mit
callam/Heimdall.swift
HeimdallTests/OAuthAccessTokenSpec.swift
5
6737
import Argo import Heimdall import Nimble import Quick import Result class OAuthAccessTokenSpec: QuickSpec { override func spec() { describe("-copy") { let accessToken = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSince1970: 0), refreshToken: "refreshToken") it("returns a copy of an access token") { let result: OAuthAccessToken = accessToken.copy() expect(result).toNot(beIdenticalTo(accessToken)) } context("when providing a new access token") { let result = accessToken.copy(accessToken: "accessToken2") it("sets the provided access token on the new access token") { expect(result.accessToken).to(equal("accessToken2")) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new token type") { let result = accessToken.copy(tokenType: "tokenType2") it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the provided token type on the new access token") { expect(result.tokenType).to(equal("tokenType2")) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new expiration date") { let result = accessToken.copy(expiresAt: NSDate(timeIntervalSince1970: 1)) it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the provided expiration date on the new access token") { expect(result.expiresAt).to(equal(NSDate(timeIntervalSince1970: 1))) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new refresh token") { let result = accessToken.copy(refreshToken: "refreshToken2") it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the provided refresh token on the new access token") { expect(result.refreshToken).to(equal("refreshToken2")) } } } describe("<Equatable> ==") { it("returns true if access tokens are equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType") expect(lhs == rhs).to(beTrue()) } it("returns false if access tokens are not equal") { let lhs = OAuthAccessToken(accessToken: "accessTokena", tokenType: "tokenType") let rhs = OAuthAccessToken(accessToken: "accessTokenb", tokenType: "tokenType") expect(lhs == rhs).to(beFalse()) } it("returns false if token types are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypea") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypeb") expect(lhs == rhs).to(beFalse()) } it("returns false if expiration times are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSinceNow: 1)) let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSinceNow: -1)) expect(lhs == rhs).to(beFalse()) } it("returns false if refresh tokens are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokena") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokenb") expect(lhs == rhs).to(beFalse()) } } describe("+decode") { context("without an expiration date") { it("creates a valid access token") { let accessToken = OAuthAccessToken.decode(.Object([ "access_token": .String("accessToken"), "token_type": .String("tokenType") ])) expect(accessToken.value).toNot(beNil()) expect(accessToken.value?.accessToken).to(equal("accessToken")) expect(accessToken.value?.tokenType).to(equal("tokenType")) expect(accessToken.value?.expiresAt).to(beNil()) expect(accessToken.value?.refreshToken).to(beNil()) } } } } }
apache-2.0
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Home/Model/搜索/BTSearchListModel.swift
1
408
// // BTSearchListModel.swift // BanTang // // Created by 张灿 on 16/6/20. // Copyright © 2016年 张灿. All rights reserved. // "搜索界面" 的 "清单" 列表 数据模型 import UIKit import MJExtension class BTSearchListModel: NSObject { /** 标题 */ var name: String = "" /** 英文标题 */ var en_name: String = "" /** 图片 */ var icon: String = "" }
apache-2.0
alex-alex/Ingress-for-Watch
Ingress/ViewController.swift
1
476
// // ViewController.swift // Ingreess // // Created by Alex Studnicka on 10/06/15. // Copyright © 2015 Alex Studnicka. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
nsagora/validation-toolkit
Examples.playground/Sources/FormError.swift
1
1817
import Foundation // MARK: - Definition public enum Form { public enum Username: Error { case missing case invalid(String) } public enum Password: Error { case missingLowercase case missingUppercase case missingDigits case missingSpecialChars case minLength(Int) } public enum Email: Error { case missing case invalid(String) } public enum Age: Error { case underage } } // MARK: - Localisation extension Form.Username: LocalizedError { public var errorDescription: String? { switch self { case .missing: return "Username is required" case .invalid(let message): return "Your username '\(message)' is invalid." } } } extension Form.Password: LocalizedError { public var errorDescription:String? { switch self { case .missingLowercase: return "At least a lower case is required." case .missingUppercase: return "At least an upper case is required." case .missingDigits: return "At least a digit is required." case .missingSpecialChars: return "At least a special character is required." case .minLength(let length): return "At least \(length) characters are required." } } } extension Form.Email: LocalizedError { public var errorDescription:String? { switch self { case .missing: return "The email address is required." case .invalid(let email): return "Your email address '\(email)' is invalid." } } } extension Form.Age: LocalizedError { public var errorDescription:String? { switch self { case .underage: return "You're underaged to use this service." } } }
mit
1738004401/Swift3.0--
SwiftCW/SwiftCW/Views/Home/SWHomeViewControllers.swift
1
3494
// // SWHomeViewControllers.swift // SwiftCW // // Created by YiXue on 17/3/16. // Copyright © 2017年 赵刘磊. All rights reserved. // import UIKit import SnapKit import AFNetworking class SWHomeViewControllers:BaseViewController { let tableView:UITableView = { let tableView = UITableView() // tableView.register(SWHomeTableViewCell.self, forCellReuseIdentifier: kCellIdentifier_SWHomeTableViewCell) return tableView }() lazy var layouts:[WBStatusLayout] = { return [WBStatusLayout]() }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadHttp(type: RefreshType.refreshTypeTop) } private func setupUI() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = UITableViewCellSeparatorStyle.none view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.top.equalTo(kNavgation_Status_Height) make.left.right.equalTo(0) make.bottom.equalTo(-kTabbar_Height) } } private func loadHttp(type:RefreshType){ switch type { case .refreshTypeTop: break case .refreshTypeBottom: break } //2.0 拼接参数 let url = URL(string: "https://api.weibo.com/") let manager = AFHTTPSessionManager.init(baseURL: url) manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String> var params = ["access_token":SWUser.curUser()?.access_token] ; params["since_id"] = "\(0)"; let path = "2/statuses/home_timeline.json"; manager.get(path, parameters: params, progress: { (_) in }, success: { (task:URLSessionDataTask, json) in let dict = json as? NSDictionary; let item:WBTimelineItem = WBTimelineItem.model(withJSON: json)! for status in (item.statuses)!{ let layout:WBStatusLayout = WBStatusLayout.init(status: status, style: WBLayoutStyle.timeline) self.layouts.append(layout) } self.tableView.reloadData() }) { (_, error) in print(error) } } } extension SWHomeViewControllers:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return layouts.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier_SWHomeTableViewCell, for: indexPath) let cellID = "cell" var cell:WBStatusCell? = tableView.dequeueReusableCell(withIdentifier: cellID) as! WBStatusCell? if (cell == nil) { cell = WBStatusCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellID) } cell?.setLayout(layouts[indexPath.row] ) return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return layouts[indexPath.row].height } }
mit
andrebocchini/SwiftChattyOSX
SwiftChattyOSX/Protocols/Reusable.swift
1
331
// // Reusable.swift // SwiftChattyOSX // // Created by Andre Bocchini on 2/12/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // protocol Reusable { static var identifier: String { get } } extension Reusable { static var identifier: String { return String(Self.self) + "Identifier" } }
mit
wj2061/ios7ptl-swift3.0
ch22-KVC/KVO/KVO/KVCTableViewController.swift
1
2931
// // KVCTableViewController.swift // KVO // // Created by wj on 15/11/29. // Copyright © 2015年 wj. All rights reserved. // import UIKit class KVCTableViewController: UITableViewController { dynamic var now:Date = Date() var timer : Timer? override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(KVCTableViewController.updateNow), userInfo: nil, repeats: true) } func updateNow(){ now = Date() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! KVCTableViewCell cell.property = "now" cell.object = self return cell } deinit{ timer?.invalidate() timer = nil } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
mmrmmlrr/ModelsTreeKit
JetPack/Disposable.swift
1
563
// // Disposable.swift // ModelsTreeKit // // Created by aleksey on 05.06.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import Foundation public protocol Disposable: class { func dispose() @discardableResult func deliverOnMainThread() -> Disposable @discardableResult func autodispose() -> Disposable @discardableResult func putInto(_ pool: AutodisposePool) -> Disposable @discardableResult func takeUntil(_ signal: Pipe<Void>) -> Disposable @discardableResult func ownedBy(_ object: DeinitObservable) -> Disposable }
mit
jay18001/brickkit-ios
Example/Source/Examples/Interactive/HideBrickViewController.swift
1
3746
// // HideBrickViewController.swift // BrickKit // // Created by Ruben Cagnie on 6/16/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import BrickKit class HideBrickViewController: BrickApp.BaseBrickController { override class var brickTitle: String { return "Hide Bricks" } override class var subTitle: String { return "Example of hiding bricks" } struct Identifiers { static let HideBrickButton = "HideBrickButton" static let HideSectionButton = "HideSectionButton" static let SimpleBrick = "SimpleBrick" static let SimpleSection = "SimpleSection" } var hideBrickButton: ButtonBrick! var hideSectionButton: ButtonBrick! var brickHidden = false var sectionHidden = false override func viewDidLoad() { super.viewDidLoad() self.registerBrickClass(ButtonBrick.self) self.registerBrickClass(LabelBrick.self) self.layout.hideBehaviorDataSource = self hideBrickButton = ButtonBrick(HideBrickViewController.Identifiers.HideBrickButton, backgroundColor: .brickGray1, title: titleForHideBrickButton) { [weak self] _ in self?.hideBrick() } hideSectionButton = ButtonBrick(HideBrickViewController.Identifiers.HideSectionButton, backgroundColor: .brickGray1, title: titleForHideSectionButton) { [weak self] _ in self?.hideSection() } self.collectionView?.backgroundColor = .brickBackground let section = BrickSection(bricks: [ LabelBrick(HideBrickViewController.Identifiers.SimpleBrick, backgroundColor: .brickGray3, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), hideBrickButton, BrickSection(HideBrickViewController.Identifiers.SimpleSection, backgroundColor: .brickGray3, bricks: [ LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), ]), hideSectionButton ], inset: 10, edgeInsets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)) self.setSection(section) } var titleForHideBrickButton: String { return "\(brickHidden ? "Show" : "Hide") Brick".uppercased() } var titleForHideSectionButton: String { return "\(sectionHidden ? "Show" : "Hide") Section".uppercased() } func hideBrick() { brickHidden = !brickHidden hideBrickButton.title = titleForHideBrickButton brickCollectionView.invalidateVisibility() reloadBricksWithIdentifiers([HideBrickViewController.Identifiers.HideBrickButton]) } func hideSection() { sectionHidden = !sectionHidden hideSectionButton.title = titleForHideSectionButton brickCollectionView.invalidateVisibility() reloadBricksWithIdentifiers([HideBrickViewController.Identifiers.HideSectionButton]) } } extension HideBrickViewController: HideBehaviorDataSource { func hideBehaviorDataSource(shouldHideItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool { switch identifier { case HideBrickViewController.Identifiers.SimpleBrick: return brickHidden case HideBrickViewController.Identifiers.SimpleSection: return sectionHidden default: return false } } }
apache-2.0
wokalski/Hourglass
Hourglass/State.swift
1
2020
import Foundation import EventKit typealias TaskIndex = [TaskID : Task] struct EventLogTarget { let calendar: EKCalendar let eventStore: EKEventStore } struct State { let currentSession: Session? let tasks: TaskIndex let selected: IndexPath? let logTarget: EventLogTarget? static let initialState = State(currentSession: nil, tasks: [:], selected: nil, logTarget: nil) } extension State { func set(visibleCells: [TaskID: IndexPath]) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(currentSession: Session?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(tasks: [Int : Task]) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(selected: IndexPath?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(logTarget: EventLogTarget?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } } extension State { var selectedTask: Task? { get { guard let indexPath = selected else { return nil } return taskAtIndexPath(indexPath) } } func taskAtIndexPath(_ indexPath: IndexPath) -> Task? { if indexPath.section == 0 { return Array(tasks.values)[indexPath.item] } return nil } }
mit
practicalswift/swift
stdlib/public/core/ContiguousArrayBuffer.swift
3
23693
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. /// /// NOTE: older runtimes called this _EmptyArrayStorage. The two must /// coexist, so it was renamed. The old name must not be used in the new /// runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class __EmptyArrayStorage : __ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _internalInvariantFailure("creating instance of __EmptyArrayStorage") } #if _runtime(_ObjC) override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { return 0 } override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { return _BridgingBuffer(0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage : __EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout @usableFromInline internal final class _ContiguousArrayStorage< Element > : __ContiguousArrayStorageBase { @inlinable deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { _internalInvariant( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { _internalInvariant( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _BridgingBuffer(count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @usableFromInline @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: __ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _internalInvariant(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _internalInvariant(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _internalInvariant(newValue >= 0) _internalInvariant( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _internalInvariant(bounds.lowerBound >= 0) _internalInvariant(bounds.upperBound >= bounds.lowerBound) _internalInvariant(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { // This customization point is not implemented for internal types. // Accidentally calling it would be a catastrophic performance bug. fatalError("unsupported") } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @inlinable internal __consuming func _asCocoaArray() -> AnyObject { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return __SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _internalInvariant(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @usableFromInline internal var _storage: __ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// 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 /// `index(after:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> } extension Sequence { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) let p = UnsafeMutableBufferPointer(start: result.firstElementAddress, count: count) var (itr, end) = source._copyContents(initializing: p) _debugPrecondition(itr.next() == nil, "invalid Collection: more than 'count' elements in collection") // We also have to check the evil shrink case in release builds, because // it can result in uninitialized array elements and therefore undefined // behavior. _precondition(end == p.endIndex, "invalid Collection: less than 'count' elements in collection") return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writting to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _internalInvariant(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _internalInvariant(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
debugsquad/metalic
metalic/Model/Edit/MEditItemCrop.swift
1
301
import UIKit class MEditItemCrop:MEditItem { init() { super.init(icon:#imageLiteral(resourceName: "assetEditCrop").withRenderingMode(UIImageRenderingMode.alwaysTemplate)) } override func selected(controller:CHomeEdit) { controller.viewEdit.cropMode() } }
mit
steelwheels/KiwiScript
KiwiShell/Source/KHShellConverter.swift
1
3030
/** * @file KHShellConverter.swift * @brief Define KHShellConverter class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiLibrary import CoconutShell import CoconutData import Foundation public func KHCompileShellStatement(statements stmts: Array<KHStatement>) -> Array<KHStatement> { var newstmts: Array<KHStatement> = [] var hasnewstmts: Bool = false for stmt in stmts { var curstmt: KHStatement = stmt let builtinconv = KHBuiltinCommandConverter() if let newstmt = builtinconv.accept(statement: curstmt) { hasnewstmts = true curstmt = newstmt } newstmts.append(curstmt) } return hasnewstmts ? newstmts : stmts } private class KHBuiltinCommandConverter: KHShellStatementConverter { open override func visit(shellCommandStatement stmt: KHShellCommandStatement) -> KHSingleStatement? { if let newcmd = convertToNativeBuiltinCommand(statement: stmt) { return newcmd } else if let (url, args) = convertToBuiltinScriptCommand(command: stmt.shellCommand) { let newstmt = KHBuiltinCommandStatement(scriptURL: url, arguments: args) newstmt.importProperties(source: stmt) return newstmt } else { return nil } } private func convertToNativeBuiltinCommand(statement stmt: KHShellCommandStatement) -> KHSingleStatement? { let (cmdnamep, restp) = CNStringUtil.cutFirstWord(string: stmt.shellCommand) if let cmdname = cmdnamep { switch cmdname { case "cd": var path: String? = nil if let rest = restp { (path, _) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHCdCommandStatement(path: path) newstmt.importProperties(source: stmt) return newstmt case "history": let newstmt = KHHistoryCommandStatement() newstmt.importProperties(source: stmt) return newstmt case "run": var path: String? = nil var arg: String? = nil if let rest = restp { (path, arg) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHRunCommandStatement(scriptPath: path, argument: arg) newstmt.importProperties(source: stmt) return newstmt case "install": var path: String? = nil var arg: String? = nil if let rest = restp { (path, arg) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHInstallCommandStatement(scriptPath: path, argument: arg) newstmt.importProperties(source: stmt) return newstmt case "clean": var file: String? = nil if let rest = restp { (file, _) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHCleanCommandStatement(scriptFile: file) newstmt.importProperties(source: stmt) return newstmt default: break } } return nil } private func convertToBuiltinScriptCommand(command cmd: String) -> (URL, Array<String>)? { var words = CNStringUtil.divideBySpaces(string: cmd) if words.count > 0 { if let url = KLBuiltinScripts.shared.search(scriptName: words[0]) { words.removeFirst() return (url, words) } } return nil } }
lgpl-2.1
mightydeveloper/swift
test/1_stdlib/RangeTraps.swift
9
2182
//===--- RangeTraps.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out_Debug // RUN: %target-build-swift %s -o %t/a.out_Release -O // // RUN: %target-run %t/a.out_Debug // RUN: %target-run %t/a.out_Release // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var RangeTraps = TestSuite("RangeTraps") RangeTraps.test("HalfOpen") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { var range = 1..<1 expectType(Range<Int>.self, &range) expectCrashLater() 1..<0 } RangeTraps.test("Closed") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { var range = 1...1 expectType(Range<Int>.self, &range) expectCrashLater() 1...0 } RangeTraps.test("OutOfRange") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { 0..<Int.max // This is a Range // This works for Intervals, but... expectTrue(ClosedInterval(0...Int.max).contains(Int.max)) // ...no support yet for Ranges containing the maximum representable value expectCrashLater() #if arch(i386) || arch(arm) // FIXME <rdar://17670791> Range<Int> bounds checking not enforced in optimized 32-bit 1...0 // crash some other way #else 0...Int.max #endif } runAllTests()
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers/26720-void.swift
9
293
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where h.h.d:d{struct c{struct g<T{{{}} protocol a class b:a
apache-2.0
huonw/swift
test/IDE/importProtocols.swift
70
638
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -module-to-print=ImportedProtocols.SubModule -source-filename %s > %t.printed.txt // RUN: %FileCheck %s < %t.printed.txt // REQUIRES: objc_interop // CHECK: protocol ImportedProtocolBase : NSObjectProtocol { // CHECK: } // CHECK: typealias ImportedProtocolBase_t = ImportedProtocolBase // CHECK: protocol IPSub : ImportedProtocolBase { // CHECK: } // CHECK: typealias IPSub_t = IPSub // CHECK: typealias Dummy = IPSub // CHECK: func takesIPSub(_ in: IPSub_t!) import ImportedProtocols func noop(_ p: ImportedProtocolSub) {}
apache-2.0
noppoMan/aws-sdk-swift
Sources/Soto/Services/CognitoIdentityProvider/CognitoIdentityProvider_Error.swift
1
11841
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CognitoIdentityProvider public struct CognitoIdentityProviderErrorType: AWSErrorType { enum Code: String { case aliasExistsException = "AliasExistsException" case codeDeliveryFailureException = "CodeDeliveryFailureException" case codeMismatchException = "CodeMismatchException" case concurrentModificationException = "ConcurrentModificationException" case duplicateProviderException = "DuplicateProviderException" case enableSoftwareTokenMFAException = "EnableSoftwareTokenMFAException" case expiredCodeException = "ExpiredCodeException" case groupExistsException = "GroupExistsException" case internalErrorException = "InternalErrorException" case invalidEmailRoleAccessPolicyException = "InvalidEmailRoleAccessPolicyException" case invalidLambdaResponseException = "InvalidLambdaResponseException" case invalidOAuthFlowException = "InvalidOAuthFlowException" case invalidParameterException = "InvalidParameterException" case invalidPasswordException = "InvalidPasswordException" case invalidSmsRoleAccessPolicyException = "InvalidSmsRoleAccessPolicyException" case invalidSmsRoleTrustRelationshipException = "InvalidSmsRoleTrustRelationshipException" case invalidUserPoolConfigurationException = "InvalidUserPoolConfigurationException" case limitExceededException = "LimitExceededException" case mFAMethodNotFoundException = "MFAMethodNotFoundException" case notAuthorizedException = "NotAuthorizedException" case passwordResetRequiredException = "PasswordResetRequiredException" case preconditionNotMetException = "PreconditionNotMetException" case resourceNotFoundException = "ResourceNotFoundException" case scopeDoesNotExistException = "ScopeDoesNotExistException" case softwareTokenMFANotFoundException = "SoftwareTokenMFANotFoundException" case tooManyFailedAttemptsException = "TooManyFailedAttemptsException" case tooManyRequestsException = "TooManyRequestsException" case unexpectedLambdaException = "UnexpectedLambdaException" case unsupportedIdentityProviderException = "UnsupportedIdentityProviderException" case unsupportedUserStateException = "UnsupportedUserStateException" case userImportInProgressException = "UserImportInProgressException" case userLambdaValidationException = "UserLambdaValidationException" case userNotConfirmedException = "UserNotConfirmedException" case userNotFoundException = "UserNotFoundException" case userPoolAddOnNotEnabledException = "UserPoolAddOnNotEnabledException" case userPoolTaggingException = "UserPoolTaggingException" case usernameExistsException = "UsernameExistsException" } private let error: Code public let context: AWSErrorContext? /// initialize CognitoIdentityProvider public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// This exception is thrown when a user tries to confirm the account with an email or phone number that has already been supplied as an alias from a different account. This exception tells user that an account with this email or phone already exists. public static var aliasExistsException: Self { .init(.aliasExistsException) } /// This exception is thrown when a verification code fails to deliver successfully. public static var codeDeliveryFailureException: Self { .init(.codeDeliveryFailureException) } /// This exception is thrown if the provided code does not match what the server was expecting. public static var codeMismatchException: Self { .init(.codeMismatchException) } /// This exception is thrown if two or more modifications are happening concurrently. public static var concurrentModificationException: Self { .init(.concurrentModificationException) } /// This exception is thrown when the provider is already supported by the user pool. public static var duplicateProviderException: Self { .init(.duplicateProviderException) } /// This exception is thrown when there is a code mismatch and the service fails to configure the software token TOTP multi-factor authentication (MFA). public static var enableSoftwareTokenMFAException: Self { .init(.enableSoftwareTokenMFAException) } /// This exception is thrown if a code has expired. public static var expiredCodeException: Self { .init(.expiredCodeException) } /// This exception is thrown when Amazon Cognito encounters a group that already exists in the user pool. public static var groupExistsException: Self { .init(.groupExistsException) } /// This exception is thrown when Amazon Cognito encounters an internal error. public static var internalErrorException: Self { .init(.internalErrorException) } /// This exception is thrown when Amazon Cognito is not allowed to use your email identity. HTTP status code: 400. public static var invalidEmailRoleAccessPolicyException: Self { .init(.invalidEmailRoleAccessPolicyException) } /// This exception is thrown when the Amazon Cognito service encounters an invalid AWS Lambda response. public static var invalidLambdaResponseException: Self { .init(.invalidLambdaResponseException) } /// This exception is thrown when the specified OAuth flow is invalid. public static var invalidOAuthFlowException: Self { .init(.invalidOAuthFlowException) } /// This exception is thrown when the Amazon Cognito service encounters an invalid parameter. public static var invalidParameterException: Self { .init(.invalidParameterException) } /// This exception is thrown when the Amazon Cognito service encounters an invalid password. public static var invalidPasswordException: Self { .init(.invalidPasswordException) } /// This exception is returned when the role provided for SMS configuration does not have permission to publish using Amazon SNS. public static var invalidSmsRoleAccessPolicyException: Self { .init(.invalidSmsRoleAccessPolicyException) } /// This exception is thrown when the trust relationship is invalid for the role provided for SMS configuration. This can happen if you do not trust cognito-idp.amazonaws.com or the external ID provided in the role does not match what is provided in the SMS configuration for the user pool. public static var invalidSmsRoleTrustRelationshipException: Self { .init(.invalidSmsRoleTrustRelationshipException) } /// This exception is thrown when the user pool configuration is invalid. public static var invalidUserPoolConfigurationException: Self { .init(.invalidUserPoolConfigurationException) } /// This exception is thrown when a user exceeds the limit for a requested AWS resource. public static var limitExceededException: Self { .init(.limitExceededException) } /// This exception is thrown when Amazon Cognito cannot find a multi-factor authentication (MFA) method. public static var mFAMethodNotFoundException: Self { .init(.mFAMethodNotFoundException) } /// This exception is thrown when a user is not authorized. public static var notAuthorizedException: Self { .init(.notAuthorizedException) } /// This exception is thrown when a password reset is required. public static var passwordResetRequiredException: Self { .init(.passwordResetRequiredException) } /// This exception is thrown when a precondition is not met. public static var preconditionNotMetException: Self { .init(.preconditionNotMetException) } /// This exception is thrown when the Amazon Cognito service cannot find the requested resource. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// This exception is thrown when the specified scope does not exist. public static var scopeDoesNotExistException: Self { .init(.scopeDoesNotExistException) } /// This exception is thrown when the software token TOTP multi-factor authentication (MFA) is not enabled for the user pool. public static var softwareTokenMFANotFoundException: Self { .init(.softwareTokenMFANotFoundException) } /// This exception is thrown when the user has made too many failed attempts for a given action (e.g., sign in). public static var tooManyFailedAttemptsException: Self { .init(.tooManyFailedAttemptsException) } /// This exception is thrown when the user has made too many requests for a given operation. public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) } /// This exception is thrown when the Amazon Cognito service encounters an unexpected exception with the AWS Lambda service. public static var unexpectedLambdaException: Self { .init(.unexpectedLambdaException) } /// This exception is thrown when the specified identifier is not supported. public static var unsupportedIdentityProviderException: Self { .init(.unsupportedIdentityProviderException) } /// The request failed because the user is in an unsupported state. public static var unsupportedUserStateException: Self { .init(.unsupportedUserStateException) } /// This exception is thrown when you are trying to modify a user pool while a user import job is in progress for that pool. public static var userImportInProgressException: Self { .init(.userImportInProgressException) } /// This exception is thrown when the Amazon Cognito service encounters a user validation exception with the AWS Lambda service. public static var userLambdaValidationException: Self { .init(.userLambdaValidationException) } /// This exception is thrown when a user is not confirmed successfully. public static var userNotConfirmedException: Self { .init(.userNotConfirmedException) } /// This exception is thrown when a user is not found. public static var userNotFoundException: Self { .init(.userNotFoundException) } /// This exception is thrown when user pool add-ons are not enabled. public static var userPoolAddOnNotEnabledException: Self { .init(.userPoolAddOnNotEnabledException) } /// This exception is thrown when a user pool tag cannot be set or updated. public static var userPoolTaggingException: Self { .init(.userPoolTaggingException) } /// This exception is thrown when Amazon Cognito encounters a user name that already exists in the user pool. public static var usernameExistsException: Self { .init(.usernameExistsException) } } extension CognitoIdentityProviderErrorType: Equatable { public static func == (lhs: CognitoIdentityProviderErrorType, rhs: CognitoIdentityProviderErrorType) -> Bool { lhs.error == rhs.error } } extension CognitoIdentityProviderErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
sumitokamoi/Runnable
Example/Runnable/AppDelegate.swift
1
2170
// // AppDelegate.swift // Runnable // // Created by sumisonic on 03/23/2017. // Copyright (c) 2017 sumisonic. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
typelift/Focus
Tests/FocusTests/SetterSpec.swift
1
2288
// // SetterSpec.swift // Focus // // Created by Ryan Peck on 3/18/16. // Copyright © 2016-2016 TypeLift. All rights reserved. // import XCTest import SwiftCheck import Focus #if SWIFT_PACKAGE import Operadics #endif class SetterSpec : XCTestCase { func testSetterLaws() { property("preserves-identity") <- forAll { (fs : IsoOf<Int, UInt>) in let lens = Lens(get: fs.getTo, set: { _, v in fs.getFrom(v) }) let setter = Setter(over: { f in { s in lens.modify(s, f) } }) return forAll { (l : Int) in return setter.over({ $0 })(l) == l } } property("preserves-composition") <- forAll { (fs : IsoOf<Int, UInt>) in let lens = Lens(get: fs.getTo, set: { _, v in fs.getFrom(v) }) let setter = Setter(over: { f in { s in lens.modify(s, f) } }) let f : (UInt) -> UInt = { $0 + 1 } let g : (UInt) -> UInt = { $0 * 2 } return forAll { (l : Int) in return (setter.over(f) • setter.over(g))(l) == setter.over(f • g)(l) } } } #if !os(macOS) && !os(iOS) && !os(tvOS) static var allTests = testCase([ ("testSetterLaws", testSetterLaws), ]) #endif } class SimpleSetterSpec : XCTestCase { func testSetterLaws() { property("preserves-identity") <- forAll { (fs : IsoOf<Int, UInt>) in let lens = Lens(get: fs.getTo, set: { _, v in fs.getFrom(v) }) let setter = SimpleSetter(over: { f in { s in lens.modify(s, f) } }) return forAll { (l : Int) in return setter.over({ $0 })(l) == l } } property("preserves-composition") <- forAll { (fs : IsoOf<Int, UInt>) in let lens = Lens(get: fs.getTo, set: { _, v in fs.getFrom(v) }) let setter = SimpleSetter(over: { f in { s in lens.modify(s, f) } }) let f : (UInt) -> UInt = { $0 + 1 } let g : (UInt) -> UInt = { $0 * 2 } return forAll { (l : Int) in return (setter.over(f) • setter.over(g))(l) == setter.over(f • g)(l) } } } #if !os(macOS) && !os(iOS) && !os(tvOS) static var allTests = testCase([ ("testSetterLaws", testSetterLaws), ]) #endif }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/25789-swift-lexer-leximpl.swift
65
456
// 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 g{ struct b func g func g b class B{struct A{var e:g
apache-2.0
7ulipa/ReactiveDataSource
ReactiveDataSource/ReactiveTableViewDataSource.swift
1
202
// // ReactiveTableViewDataSource.swift // Pods // // Created by Tulipa on 12/11/2016. // // import Foundation class ReactiveTableViewDataSource: ReactiveDataSource, UItableViewDataSource { }
mit
jyxia/nostalgic-pluto-ios
nostalgic-pluto-ios/AppDelegate.swift
1
6163
// // AppDelegate.swift // nostalgic-pluto-ios // // Created by Jinyue Xia on 7/18/15. // Copyright (c) 2015 Jinyue Xia. 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 "org.ios.jx.nostalgic_pluto_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("nostalgic_pluto_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("nostalgic_pluto_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. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(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
FolioReader/FolioReaderKit
Source/FolioReaderAddHighlightNote.swift
1
9481
// // FolioReaderAddHighlightNote.swift // FolioReaderKit // // Created by ShuichiNagao on 2018/05/06. // import UIKit import RealmSwift class FolioReaderAddHighlightNote: UIViewController { var textView: UITextView! var highlightLabel: UILabel! var scrollView: UIScrollView! var containerView = UIView() var highlight: Highlight! var highlightSaved = false var isEditHighlight = false var resizedTextView = false private var folioReader: FolioReader private var readerConfig: FolioReaderConfig init(withHighlight highlight: Highlight, folioReader: FolioReader, readerConfig: FolioReaderConfig) { self.folioReader = folioReader self.highlight = highlight self.readerConfig = readerConfig super.init(nibName: nil, bundle: Bundle.frameworkBundle()) } required init?(coder aDecoder: NSCoder) { fatalError("storyboards are incompatible with truth and beauty") } // MARK: - life cycle methods override func viewDidLoad() { super.viewDidLoad() setCloseButton(withConfiguration: readerConfig) prepareScrollView() configureTextView() configureLabel() configureNavBar() configureKeyboardObserver() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() setNeedsStatusBarAppearanceUpdate() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.frame = view.bounds containerView.frame = view.bounds scrollView.contentSize = view.bounds.size } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if !highlightSaved && !isEditHighlight { guard let currentPage = folioReader.readerCenter?.currentPage else { return } currentPage.webView?.js("removeThisHighlight()") } } // MARK: - private methods private func prepareScrollView(){ scrollView = UIScrollView() scrollView.delegate = self as UIScrollViewDelegate scrollView.contentSize = CGSize.init(width: view.frame.width, height: view.frame.height ) scrollView.bounces = false containerView = UIView() containerView.backgroundColor = .white scrollView.addSubview(containerView) view.addSubview(scrollView) let leftConstraint = NSLayoutConstraint(item: scrollView!, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0) let rightConstraint = NSLayoutConstraint(item: scrollView!, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: 0) let topConstraint = NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0) let botConstraint = NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) view.addConstraints([leftConstraint, rightConstraint, topConstraint, botConstraint]) } private func configureTextView(){ textView = UITextView() textView.delegate = self textView.translatesAutoresizingMaskIntoConstraints = false textView.textColor = .black textView.backgroundColor = .clear textView.font = UIFont.boldSystemFont(ofSize: 15) containerView.addSubview(textView) if isEditHighlight { textView.text = highlight.noteForHighlight } let leftConstraint = NSLayoutConstraint(item: textView!, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1.0, constant: 20) let rightConstraint = NSLayoutConstraint(item: textView!, attribute: .right, relatedBy: .equal, toItem: containerView, attribute: .right, multiplier: 1.0, constant: -20) let topConstraint = NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 100) let heiConstraint = NSLayoutConstraint(item: textView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: view.frame.height - 100) containerView.addConstraints([leftConstraint, rightConstraint, topConstraint, heiConstraint]) } private func configureLabel() { highlightLabel = UILabel() highlightLabel.translatesAutoresizingMaskIntoConstraints = false highlightLabel.numberOfLines = 3 highlightLabel.font = UIFont.systemFont(ofSize: 15) highlightLabel.text = highlight.content.stripHtml().truncate(250, trailing: "...").stripLineBreaks() containerView.addSubview(self.highlightLabel!) let leftConstraint = NSLayoutConstraint(item: highlightLabel!, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1.0, constant: 20) let rightConstraint = NSLayoutConstraint(item: highlightLabel!, attribute: .right, relatedBy: .equal, toItem: containerView, attribute: .right, multiplier: 1.0, constant: -20) let topConstraint = NSLayoutConstraint(item: highlightLabel, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 20) let heiConstraint = NSLayoutConstraint(item: highlightLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 70) containerView.addConstraints([leftConstraint, rightConstraint, topConstraint, heiConstraint]) } private func configureNavBar() { let navBackground = folioReader.isNight(self.readerConfig.nightModeNavBackground, self.readerConfig.daysModeNavBackground) let tintColor = readerConfig.tintColor let navText = folioReader.isNight(UIColor.white, UIColor.black) let font = UIFont(name: "Avenir-Light", size: 17)! setTranslucentNavigation(false, color: navBackground, tintColor: tintColor, titleColor: navText, andFont: font) let titleAttrs = [NSAttributedString.Key.foregroundColor: readerConfig.tintColor] let saveButton = UIBarButtonItem(title: readerConfig.localizedSave, style: .plain, target: self, action: #selector(saveNote(_:))) saveButton.setTitleTextAttributes(titleAttrs, for: UIControl.State()) navigationItem.rightBarButtonItem = saveButton } private func configureKeyboardObserver() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardWillShow(notification: NSNotification){ //give room at the bottom of the scroll view, so it doesn't cover up anything the user needs to tap var userInfo = notification.userInfo! var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) var contentInset:UIEdgeInsets = self.scrollView.contentInset contentInset.bottom = keyboardFrame.size.height self.scrollView.contentInset = contentInset } @objc private func keyboardWillHide(notification:NSNotification){ let contentInset:UIEdgeInsets = UIEdgeInsets.zero self.scrollView.contentInset = contentInset } @objc private func saveNote(_ sender: UIBarButtonItem) { if !textView.text.isEmpty { if isEditHighlight { let realm = try! Realm(configuration: readerConfig.realmConfiguration) realm.beginWrite() highlight.noteForHighlight = textView.text highlightSaved = true try! realm.commitWrite() } else { highlight.noteForHighlight = textView.text highlight.persist(withConfiguration: readerConfig) highlightSaved = true } } dismiss() } } // MARK: - UITextViewDelegate extension FolioReaderAddHighlightNote: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { let fixedWidth = textView.frame.size.width textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) var newFrame = textView.frame newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height + 15) textView.frame = newFrame; } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { textView.frame.size.height = textView.frame.height + 30 if resizedTextView { scrollView.scrollRectToVisible(textView.frame, animated: true) } else{ resizedTextView = true } return true } }
bsd-3-clause
PairOfNewbie/BeautifulDay
BeautifulDay/Controller/Album/AlbumDetailController.swift
1
8869
// // AlbumDetailController.swift // BeautifulDay // // Created by DaiFengyi on 16/5/4. // Copyright © 2016年 PairOfNewbie. All rights reserved. // import UIKit private let albumZanCellIdentifier = "AlbumZanCell" private let albumCommentCellIdentifier = "AlbumCommentCell" class AlbumDetailController: UITableViewController { @IBOutlet weak var webHeader: UIWebView! var albumId = 0 { didSet { fetchAlbumDetailInfo(albumId, failure: { (error) in print(error.description) }, success: { [unowned self](albumDetail) in self.albumDetail = albumDetail // webHeader let request = NSURLRequest(URL: NSURL(string: (albumDetail.albuminfo?.pageUrl)!)!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10) self.webHeader.loadRequest(request) self.webHeader.scrollView.scrollEnabled = false self.tableView.reloadData() }) } } var albumDetail: AlbumDetail? override func viewDidLoad() { super.viewDidLoad() // 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() self.automaticallyAdjustsScrollViewInsets = true tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension tableView.registerNib(UINib(nibName: albumZanCellIdentifier, bundle: nil), forCellReuseIdentifier: albumZanCellIdentifier) tableView.registerNib(UINib(nibName: albumCommentCellIdentifier, bundle: nil), forCellReuseIdentifier: albumCommentCellIdentifier) } override func viewWillAppear(animated: Bool) { self.navigationController?.hidesBarsOnSwipe = true super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.setNavigationBarHidden(false, animated: true) super.viewWillDisappear(animated) } // MARK: - Action @objc func zan(sender: UIButton) { guard currentUser.isLogin else { return } sender.selected = !sender.selected let keyframeAni = CAKeyframeAnimation(keyPath: "transform.scale") keyframeAni.duration = 0.5; keyframeAni.values = [0.1, 1.5, 1.0]; keyframeAni.keyTimes = [0, 0.8, 1]; keyframeAni.calculationMode = kCAAnimationLinear; sender.layer.addAnimation(keyframeAni, forKey: "zan") zanAction(sender.selected) } private func zanAction(status: Bool) { postZan(albumId, zanStatus: status, failure: { (error) in print("zan failure") SAIUtil.showMsg("点赞失败") }, success:{ (z) in print("zan success") }) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: if let list = albumDetail?.commentList { return list.count }else { return 0 } default: return 0 } } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == 0 { return nil } let inputBar = NSBundle.mainBundle().loadNibNamed("InputBar", owner: self, options: nil).last as? InputBar inputBar?.clickAction = { if currentUser.isLogin { self.performSegueWithIdentifier("showComment", sender: nil) } } return inputBar } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 0 { return 0 } return 44 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCellWithIdentifier(albumZanCellIdentifier, forIndexPath: indexPath) if let button = cell.accessoryView as? UIButton { button.addTarget(self, action: #selector(AlbumDetailController.zan(_:)), forControlEvents: .TouchUpInside) } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier(albumCommentCellIdentifier, forIndexPath: indexPath) return cell default: return UITableViewCell() } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: let c = cell as! AlbumZanCell var zlist = String() if let zanlist = albumDetail?.zanList { for z in zanlist { if let userName = z.userName { if zlist.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 { zlist = userName }else { zlist = zlist + (",\(userName)") } } } } if zlist.isEmpty { zlist = "还没人点赞,赶紧点赞吧!" } c.zanList.text = zlist break; case 1: let c = cell as! AlbumCommentCell if let comment = albumDetail?.commentList![indexPath.row] { // todo // c.name.text = comment.userId c.content.text = comment.content } default: break; } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if currentUser.isLogin { self.performSegueWithIdentifier("showComment", sender: nil) } } /* // 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?) { let vc = segue.destinationViewController as! AlbumCommentController vc.albumDetail = albumDetail // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } } extension AlbumDetailController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { // webHeader.frame.size = webHeader.scrollView.contentSize webHeader.frame.size = webHeader.sizeThatFits(CGSizeZero) tableView.reloadData() } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { } }
mit
HabitRPG/habitrpg-ios
HabitRPG/Views/LoginEntryView.swift
1
3878
// // LoginEntryView.swift // Habitica // // Created by Phillip on 27.07.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import Foundation @IBDesignable class LoginEntryView: UIView, UITextFieldDelegate { @IBInspectable var placeholderText: String? { didSet { if let text = placeholderText { let color = UIColor.white.withAlphaComponent(0.5) entryView.attributedPlaceholder = NSAttributedString(string: text, attributes: [NSAttributedString.Key.foregroundColor: color]) } else { entryView.placeholder = "" } } } weak public var delegate: UITextFieldDelegate? @IBInspectable var icon: UIImage? { didSet { iconView.image = icon } } @IBInspectable var keyboard: Int { get { return entryView.keyboardType.rawValue } set(keyboardIndex) { if let type = UIKeyboardType.init(rawValue: keyboardIndex) { entryView.keyboardType = type } } } @IBInspectable var isSecureTextEntry: Bool = false { didSet { entryView.isSecureTextEntry = isSecureTextEntry } } @IBOutlet weak var entryView: UITextField! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var bottomBorder: UIView! var gestureRecognizer: UIGestureRecognizer? var hasError: Bool = false { didSet { setBarColor() } } private var wasEdited = false override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { if let view = loadViewFromNib() { view.frame = bounds view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] addSubview(view) gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedView)) if let gestureRecognizer = self.gestureRecognizer { addGestureRecognizer(gestureRecognizer) } isUserInteractionEnabled = true } } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView return view } func textFieldDidBeginEditing(_ textField: UITextField) { wasEdited = true UIView.animate(withDuration: 0.3) {[weak self] in self?.bottomBorder.alpha = 1.0 } if let gestureRecognizer = self.gestureRecognizer { removeGestureRecognizer(gestureRecognizer) } } func textFieldDidEndEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.3) {[weak self] in self?.bottomBorder.alpha = 0.15 } if let gestureRecognizer = gestureRecognizer { addGestureRecognizer(gestureRecognizer) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let function = delegate?.textFieldShouldReturn { return function(textField) } return false } @objc func tappedView() { entryView.becomeFirstResponder() } private func setBarColor() { if !wasEdited { return } if hasError { bottomBorder.backgroundColor = UIColor.red50 } else { bottomBorder.backgroundColor = .white } } }
gpl-3.0
domenicosolazzo/practice-swift
HealthKit/Observing changes in HealthKit/Observing changes in HealthKitTests/Observing_changes_in_HealthKitTests.swift
1
959
// // Observing_changes_in_HealthKitTests.swift // Observing changes in HealthKitTests // // Created by Domenico on 08/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit import XCTest class Observing_changes_in_HealthKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
abarisain/skugga
Apple/iOS/Skugga/Configuration.swift
1
1291
// // Configuration.swift // skugga // // Created by Arnaud Barisain-Monrose on 08/02/2015. // // import Foundation import UpdAPI private struct LocalConsts { static let EndpointKey = "user.endpoint" static let SecretKey = "user.secret" static let GroupId = "group.fr.nlss.skugga" } struct Configuration { static var endpoint: String { get { return UserDefaults(suiteName: LocalConsts.GroupId)?.string(forKey: LocalConsts.EndpointKey) ?? "" } set { UserDefaults(suiteName: LocalConsts.GroupId)?.set(newValue, forKey: LocalConsts.EndpointKey) } } static var secret: String? { get { return UserDefaults(suiteName: LocalConsts.GroupId)?.string(forKey: LocalConsts.SecretKey) } set { UserDefaults(suiteName: LocalConsts.GroupId)?.set(newValue, forKey: LocalConsts.SecretKey) } } static var updApiConfiguration: UpdAPIConfiguration { get { return UpdAPIConfiguration(endpoint: self.endpoint, secret: self.secret) } } static func synchronize() { UserDefaults(suiteName: LocalConsts.GroupId)?.synchronize() } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Coincore/CryptoCurrency+Account.swift
1
742
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import MoneyKit extension CryptoCurrency { private typealias LocalizedString = LocalizationConstants.Account public var defaultInterestWalletName: String { LocalizedString.myInterestWallet } public var defaultTradingWalletName: String { LocalizedString.myTradingAccount } public var defaultWalletName: String { LocalizedString.myWallet } public var defaultExchangeWalletName: String { LocalizedString.myExchangeAccount } } extension FiatCurrency { private typealias LocalizedString = LocalizationConstants.Account public var defaultWalletName: String { name } }
lgpl-3.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/WalletActionCell/WalletActionTableViewCell.swift
1
1790
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import UIKit final class WalletActionTableViewCell: UITableViewCell { // MARK: - Properties var presenter: WalletActionCellPresenter! { didSet { badgeImageView.viewModel = presenter.badgeImageViewModel titleLabel.content = presenter.titleLabelContent descriptionLabel.content = presenter.descriptionLabelContent } } // MARK: - Private Properties private let badgeImageView = BadgeImageView() private let stackView = UIStackView() private let titleLabel = UILabel() private let descriptionLabel = UILabel() // MARK: - Setup override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { contentView.addSubview(badgeImageView) contentView.addSubview(stackView) stackView.axis = .vertical stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(descriptionLabel) badgeImageView.layoutToSuperview(.leading, offset: Spacing.outer) badgeImageView.layout(size: .init(edge: Sizing.badge)) badgeImageView.layout(edges: .centerY, to: stackView) stackView.layout(to: .top, of: contentView, offset: Spacing.inner) stackView.layout(edges: .trailing, to: contentView, offset: -Spacing.inner) stackView.layout(edge: .leading, to: .trailing, of: badgeImageView, offset: Spacing.inner) stackView.layout(edges: .centerY, to: contentView) } }
lgpl-3.0
aojet/Aojet
Sources/Aojet/threading/WeakReferenceCompat.swift
1
449
// // WeakReferenceCompat.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // protocol WeakReferenceCompat { associatedtype T: AnyObject func get() -> T? } class AnyWeakReferenceCompat<T: AnyObject>: WeakReferenceCompat { private let _get: () -> (T?) init<S:WeakReferenceCompat>(_ base: S) where S.T == T { _get = base.get } func get() -> T? { return _get() } }
mit
wilfreddekok/Antidote
Antidote/StaticBackgroundView.swift
1
602
// 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 /** View with static background color. Is used to prevent views inside UITableViewCell from blinking on tap. */ class StaticBackgroundView: UIView { override var backgroundColor: UIColor? { get { return super.backgroundColor } set {} } func setStaticBackgroundColor(color: UIColor?) { super.backgroundColor = color } }
mpl-2.0
sundeepgupta/foodup
FoodUp/AppDelegate.swift
1
709
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.setupTrackVC() return true } private func setupTrackVC() { let dataController = DataController(defaults: NSUserDefaults.standardUserDefaults()) if let navigationController = self.window?.rootViewController as? UINavigationController { if let trackVC = navigationController.viewControllers.first as? TrackVC { trackVC.setDataController(dataController) } } } }
unlicense
pvbaleeiro/movie-aholic
movieaholic/movieaholic/recursos/view/ExploreHeaderView.swift
1
14967
// // ExploreHeaderView.swift // movieaholic // // Created by Victor Baleeiro on 24/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit //------------------------------------------------------------------------------------------------------------- // MARK: Delegate //------------------------------------------------------------------------------------------------------------- protocol ExploreHeaderViewDelegate { func didSelect(viewController: UIViewController, completion: (() -> Void)?) func didCollapseHeader(completion: (() -> Void)?) func didExpandHeader(completion: (() -> Void)?) } class ExploreHeaderView: UIView { //------------------------------------------------------------------------------------------------------------- // MARK: Propriedades //------------------------------------------------------------------------------------------------------------- override var bounds: CGRect { didSet { backgroundGradientLayer.frame = bounds } } var delegate: UIViewController? { didSet { } } lazy var backgroundGradientLayer: CAGradientLayer = { let layer = CAGradientLayer() layer.startPoint = CGPoint(x: 0, y: 0.5) layer.endPoint = CGPoint(x: 1, y: 0.5) layer.colors = self.backgroundGradient return layer }() var whiteOverlayView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.white view.alpha = 0 return view }() var backgroundGradient: [CGColor] = [UIColor.primaryColor().cgColor, UIColor.primaryColorDark().cgColor] var pageTabDelegate: ExploreHeaderViewDelegate? var pageTabControllers = [UIViewController]() { didSet { setupPagers() } } let pageTabHeight: CGFloat = 50 let headerInputHeight: CGFloat = 50 var minHeaderHeight: CGFloat { return 20 // status bar + pageTabHeight } var midHeaderHeight: CGFloat { return 20 + 10 // status bar + spacing + headerInputHeight // input 1 + pageTabHeight } var maxHeaderHeight: CGFloat { return 20 + 10 // status bar + spacing + 50 // collapse button + 50 + 10 // input 1 + spacing + 50 + 10 // input 2 + spacing + 50 // input 3 + 50 // page tabs } let collapseButtonHeight: CGFloat = 40 let collapseButtonMaxTopSpacing: CGFloat = 20 + 10 let collapseButtonMinTopSpacing: CGFloat = 0 var collapseButtonTopConstraint: NSLayoutConstraint? lazy var collapseButton: UIButton = { let button = UIButton() button.setImage(UIImage(named: "collapse"), for: .normal) button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) button.translatesAutoresizingMaskIntoConstraints = false button.contentHorizontalAlignment = .center button.addTarget(self, action: #selector(ExploreHeaderView.handleCollapse), for: .touchUpInside) return button }() var destinationFilterTopConstraint: NSLayoutConstraint? lazy var summaryFilter: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.addTarget(self, action: #selector(ExploreHeaderView.handleExpand), for: .touchUpInside) let img = UIImage(named: "Search") btn.setImage(img, for: .normal) btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("Search • Places • News", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() lazy var searchBarFilter: UISearchBar = { let searchBar = UISearchBar() searchBar.translatesAutoresizingMaskIntoConstraints = false searchBar.backgroundColor = UIColor.primaryColor() searchBar.showsCancelButton = true return searchBar }() lazy var btnNews: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.addTarget(self, action: #selector(ExploreHeaderView.funcNotImplemented), for: .touchUpInside) btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("News", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() lazy var btnPrincipal: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("Principal", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() var pagerView: PageTabNavigationView = { let view = PageTabNavigationView() view.translatesAutoresizingMaskIntoConstraints = false return view }() init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.primaryColorDark() setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { addSubview(collapseButton) collapseButton.heightAnchor.constraint(equalToConstant: collapseButtonHeight).isActive = true collapseButtonTopConstraint = collapseButton.topAnchor.constraint(equalTo: topAnchor, constant: collapseButtonMaxTopSpacing) collapseButtonTopConstraint?.isActive = true collapseButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true collapseButton.widthAnchor.constraint(equalToConstant: collapseButtonHeight).isActive = true addSubview(searchBarFilter) searchBarFilter.heightAnchor.constraint(equalToConstant: 50).isActive = true destinationFilterTopConstraint = searchBarFilter.topAnchor.constraint(equalTo: topAnchor, constant: collapseButtonHeight + collapseButtonMaxTopSpacing + 10) destinationFilterTopConstraint?.isActive = true searchBarFilter.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true searchBarFilter.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(summaryFilter) summaryFilter.heightAnchor.constraint(equalToConstant: 50).isActive = true summaryFilter.topAnchor.constraint(equalTo: searchBarFilter.topAnchor).isActive = true summaryFilter.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true summaryFilter.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true summaryFilter.alpha = 0 addSubview(btnNews) btnNews.heightAnchor.constraint(equalToConstant: 50).isActive = true btnNews.topAnchor.constraint(equalTo: searchBarFilter.bottomAnchor, constant: 10).isActive = true btnNews.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true btnNews.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(btnPrincipal) btnPrincipal.heightAnchor.constraint(equalToConstant: 50).isActive = true btnPrincipal.topAnchor.constraint(equalTo: btnNews.bottomAnchor, constant: 10).isActive = true btnPrincipal.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true btnPrincipal.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(whiteOverlayView) whiteOverlayView.topAnchor.constraint(equalTo: topAnchor).isActive = true whiteOverlayView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true whiteOverlayView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true whiteOverlayView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true } func setupPagers() { // TODO: remove all subviews addSubview(pagerView) pagerView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true pagerView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true pagerView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true pagerView.heightAnchor.constraint(equalToConstant: pageTabHeight).isActive = true for vc in pageTabControllers { pagerView.appendPageTabItem(withTitle: vc.title ?? "") pagerView.navigationDelegate = self if (searchBarFilter.delegate == nil) { searchBarFilter.delegate = vc as? UISearchBarDelegate } } } override func layoutSubviews() { } public func updateHeader(newHeight: CGFloat, offset: CGFloat) { let headerBottom = newHeight - pageTabHeight let midMaxPercentage = (newHeight - midHeaderHeight) / (maxHeaderHeight - midHeaderHeight) btnNews.alpha = midMaxPercentage var datePickerPercentage3 = (headerBottom - btnPrincipal.frame.origin.y) / btnPrincipal.frame.height datePickerPercentage3 = max(0, min(1, datePickerPercentage3)) // capped between 0 and 1 btnPrincipal.alpha = datePickerPercentage3 collapseButton.alpha = datePickerPercentage3 var collapseButtonTopSpacingPercentage = (headerBottom - searchBarFilter.frame.origin.y) / (btnPrincipal.frame.origin.y + btnPrincipal.frame.height - searchBarFilter.frame.origin.y) collapseButtonTopSpacingPercentage = max(0, min(1, collapseButtonTopSpacingPercentage)) collapseButtonTopConstraint?.constant = collapseButtonTopSpacingPercentage * collapseButtonMaxTopSpacing summaryFilter.setTitle("\("Search") • \(btnNews.titleLabel!.text!) • \(btnPrincipal.titleLabel!.text!)", for: .normal) if newHeight > midHeaderHeight { searchBarFilter.alpha = collapseButtonTopSpacingPercentage destinationFilterTopConstraint?.constant = max(UIApplication.shared.statusBarFrame.height + 10,collapseButtonTopSpacingPercentage * (collapseButtonHeight + collapseButtonMaxTopSpacing + 10)) summaryFilter.alpha = 1 - collapseButtonTopSpacingPercentage whiteOverlayView.alpha = 0 pagerView.backgroundColor = UIColor.primaryColorDark() pagerView.titleColor = UIColor.white pagerView.selectedTitleColor = UIColor.white } else if newHeight == midHeaderHeight { destinationFilterTopConstraint?.constant = UIApplication.shared.statusBarFrame.height + 10 searchBarFilter.alpha = 0 summaryFilter.alpha = 1 whiteOverlayView.alpha = 0 pagerView.backgroundColor = UIColor.primaryColorDark() pagerView.titleColor = UIColor.white pagerView.selectedTitleColor = UIColor.white } else { destinationFilterTopConstraint?.constant = destinationFilterTopConstraint!.constant - offset let minMidPercentage = (newHeight - minHeaderHeight) / (midHeaderHeight - minHeaderHeight) searchBarFilter.alpha = 0 summaryFilter.alpha = minMidPercentage whiteOverlayView.alpha = 1 - minMidPercentage pagerView.backgroundColor = UIColor.fade(fromColor: UIColor.primaryColorDark(), toColor: UIColor.white, withPercentage: 1 - minMidPercentage) pagerView.titleColor = UIColor.fade(fromColor: UIColor.white, toColor: UIColor.darkGray, withPercentage: 1 - minMidPercentage) pagerView.selectedTitleColor = UIColor.fade(fromColor: UIColor.white, toColor: UIColor.primaryColor(), withPercentage: 1 - minMidPercentage) } } @objc func handleCollapse() { pageTabDelegate?.didCollapseHeader(completion: nil) } @objc func handleExpand() { pageTabDelegate?.didExpandHeader(completion: nil) } @objc func funcNotImplemented() { let alertView = UIAlertController(title: "Aviso", message: "Essa funcionalidade ainda não foi implementada", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in NSLog("OK clicado") }) alertView.addAction(action) //Exibe alerta let controller = delegate controller?.present(alertView, animated: true, completion: nil) } } //------------------------------------------------------------------------------------------------------------- // MARK: PageTabNavigationViewDelegate //------------------------------------------------------------------------------------------------------------- extension ExploreHeaderView: PageTabNavigationViewDelegate { func didSelect(tabItem: PageTabItem, atIndex index: Int, completion: (() -> Void)?) { if index >= 0, index < pageTabControllers.count { pageTabDelegate?.didSelect(viewController: pageTabControllers[index]) { if let handler = completion { handler() } } } } func animatePageTabSelection(toIndex index: Int) { pagerView.animatePageTabSelection(toIndex: index) } }
mit
JarlRyan/IOSNote
Swift/City/City/ViewController.swift
1
2863
// // ViewController.swift // City // // Created by bingoogol on 14-6-15. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { var _province:NSArray! var _city:NSMutableDictionary! override func viewDidLoad() { super.viewDidLoad() // 初始化选择器控件 let picker = UIPickerView() // 1.设置选择器数据源 picker.dataSource = self // 2.设置选择器代理 picker.delegate = self picker.showsSelectionIndicator = true self.view.addSubview(picker) // 3.指定选择器的内容 loadPickerData() } func loadPickerData() { // 1.省份 _province = ["北京","河北","湖南"] // 2.城市 // 2.1初始化城市字典 _city = NSMutableDictionary() // 2.2实例化城市中的数据 let city1 = ["东城","西城"] _city["北京"] = city1 let city2 = ["石家庄","唐山","保定"] _city["河北"] = city2 let city3 = ["长沙","郴州","衡阳"] _city["湖南"] = city3 } // 选择器数据源方法 // 设置数据列数 func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 2 } // 设置数据行数 func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return _province.count } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray return citys.count } } // 设置选择器行的内容 func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { if component == 0 { return _province[row] as String } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray return citys[row] as String } } // 用户选择行的时候刷新数据 func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { if component == 0 { pickerView.reloadComponent(1) } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray let cityName = citys[row] as String println("\(provinceName):\(cityName)") } } }
apache-2.0
bravelocation/daysleft
DaysLeft WatchKit Widget/DaysLeftWatchWidget.swift
1
1069
// // DaysLeft_WatchKit_Widget.swift // DaysLeft WatchKit Widget // // Created by John Pollard on 22/09/2022. // Copyright © 2022 Brave Location Software. All rights reserved. // import WidgetKit import SwiftUI /// Watch extension widget @main struct DaysLeftWatchWidget: Widget { /// Widget kind let kind: String = "DaysLeftWatchWidget" /// Configuration body var body: some WidgetConfiguration { StaticConfiguration( kind: kind, provider: WidgetTimelineProvider()) { entry in WatchWidgetSwitcherView(model: entry) } .supportedFamilies(self.supportedFamilies()) .configurationDisplayName(NSLocalizedString("Abbreviated App Title", comment: "")) .description(NSLocalizedString("App Title", comment: "")) } /// Supported fwidget families /// - Returns: Array of supported families private func supportedFamilies() -> [WidgetFamily] { return [.accessoryCircular, .accessoryRectangular, .accessoryInline, .accessoryCorner] } }
mit