blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
1e026b9567e1123fcd21d3024abafdb7ded17253
Swift
Dorian10/InMindApp
/InMindApp/Model/CoreDataHelper.swift
UTF-8
1,673
2.828125
3
[]
no_license
// // CoreDataHelper.swift // InMindApp // // Created by Dorian Solant on 13/05/2020. // Copyright © 2020 Dorian Solant. All rights reserved. // import UIKit import CoreData typealias ListeCompletion = (_ listes : [VideoCourseList]?) -> Void class CoreDataHelper { // Récupérer base CoreData private let appDel = UIApplication.shared.delegate as! AppDelegate // Récupérer le contexte var context : NSManagedObjectContext { return appDel.persistentContainer.viewContext } // Sauvegarder dans CoreData func save () { appDel.saveContext() } /* Logique ENTITY VideoCourse */ func saveVideo (_ string : String?) { guard let texte = string, texte != "" else { return } let nouvelleVideo = VideoCourseList(context: context) nouvelleVideo.name = texte nouvelleVideo.sectionName = "Maths" nouvelleVideo.dateAdded = Date() nouvelleVideo.chapterName = "Fonctions" save() print("Sauvegardé") } func getVideoCourses(completion : ListeCompletion?) { let fetchRequest : NSFetchRequest<VideoCourseList> = VideoCourseList.fetchRequest() let sortDescriptor = NSSortDescriptor(key: "dateAdded", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] do { let listes = try context.fetch(fetchRequest) for l in listes { print(l.name) } completion?(listes) } catch { completion?(nil) print(error.localizedDescription) } } }
true
1245ae89162510faa1e8167f45d2fe0edf36f971
Swift
eojine/GalleryApp
/GalleryApp/Models/Photo.swift
UTF-8
872
3.359375
3
[]
no_license
// // Photo.swift // GalleryApp // // Created by Eojin Yang on 2021/01/08. // import Foundation struct Photo: Codable { let id: String? let width: Int? let height: Int? let urls: Urls? let user: User? struct Urls: Codable { let regular: String? } struct User: Codable { let name: String? } } extension Photo { /// 디바이스 width 받아서 photo height 결정하는 함수 func photoHeightForDevice(_ deviceWidth: Float) -> Float? { guard let width = self.width, let height = self.height else { return nil} let floatWidth = Float(width), floatHeight = Float(height) let resizedWidth = floatWidth * (deviceWidth / floatWidth) let resizedHeight = resizedWidth * floatHeight / floatWidth return resizedHeight } }
true
dd7f56566a3b6f435139532bee931a5e3891bd8e
Swift
TonikMusic/TonikAnalyticsIOS
/TonikAnalytics/Views/platformView.swift
UTF-8
1,665
2.609375
3
[]
no_license
// // platformView.swift // TonikAnalytics // // Created by Wesley Espinoza on 11/4/19. // Copyright © 2019 HazeWritesCode. All rights reserved. // import Foundation import UIKit class PlatformView: UIView{ let platformImageView: UIImageView = UIImageView(image: UIImage(named: "spotifyIcon")) let platformNameLabel: Label = Label.newLabel(title: "Spotify", textColor: .white, textSize: 8) override init(frame: CGRect) { super.init(frame: frame) setupViews() self.add(subview: platformImageView) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.centerXAnchor), v.topAnchor.constraint(equalTo: platformImageView.bottomAnchor, constant: 8), v.heightAnchor.constraint(equalToConstant: 25), v.widthAnchor.constraint(equalToConstant: 25) ]} self.add(subview: platformNameLabel) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.centerXAnchor), v.topAnchor.constraint(equalTo: platformImageView.bottomAnchor, constant: 4) ]} } func setupViews(){ platformImageView.backgroundColor = .clear platformImageView.translatesAutoresizingMaskIntoConstraints = false platformNameLabel.translatesAutoresizingMaskIntoConstraints = false } public func changeImage(_ image: UIImage){ self.platformImageView.image = image } public func changeTitle(_ text: String){ self.platformNameLabel.text = text } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
675093b38cd3a42bd2f864deb5f9708023d8ec0e
Swift
maxim5/code-inspector
/data/swift/7965f18447224429f2f3322211a62068_MTZBackgroundViewController.swift
UTF-8
4,987
2.578125
3
[ "Apache-2.0" ]
permissive
// // MTZBackgroundViewController.swift // Matt Zanchelli // // Created by Matt Zanchelli on 6/7/14. // Copyright (c) 2014 Matt Zanchelli. All rights reserved. // import UIKit @objc(MTZBackgroundViewController) class BackgroundViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView : UITableView // var content : TimelineEvent[] var content : NSArray = [] init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.contentInset = UIEdgeInsets(top: 44+31, left: 0, bottom: 0, right: 0) let e0 = TimelineEvent(date: "Early Life", title: "Interested in Computers & Computer Graphics.", descriptionString: "As a kid, I was fascinated with computers and what was possible with them. I made artwork in various programs to give to my parents. I much preferred drawing with computer programs over traditional crayons and markers.", image: UIImage(named: "Computer Graphics.jpg")) let e1 = TimelineEvent(date: "Dec. 2004", title: "Owned my first iPad.", descriptionString: "As I unboxed the silver iPod mini, my eyes lit up. I suddenly knew what I would be doing for the rest of my life: building incredible products and customer experiences like this one. Every day of my life is working towards that goal.", image: UIImage(named: "iPod.jpg")) let e2 = TimelineEvent(date: "Aug. 2006", title: "Bought my first Mac.", descriptionString: "After a couple years of collecting iPods, I knew it was time to also get a Mac. I used them occasionally at school and found them to be much more enjoyable to use than any other computer I had ever used before.", image: UIImage(named:"MacBook.jpg")) let e3 = TimelineEvent(date: "Aug. 2007", title: "Started High School.", descriptionString: "By this time, I was developing my interest in design. I spent a lot of time on design forums, like MacThemes, where I was inspired by and learned from fantastic Mac designers. I started designing icons and user interfaces for fun.", image: UIImage(named: "Started HS.jpg")) let e4 = TimelineEvent(date: "Oct. 2007", title: "Began Freelancing.", descriptionString: "I had enough experience with designing and building websites that I could do freelance design and web work. I loved my time designing logos, business cards, and websites for friends and locals in my community.", image: UIImage(named: "10th Grade.jpg")) let e5 = TimelineEvent(date: "Apr. 2008", title: "Started DJ BMZ", descriptionString: "I became very interested in music and started collecting equipment to playback and manipulate music. My neighbour and I started DJing parties and other events. Eventually that turned into a profitable business that’s still running to this day.", image: UIImage(named: "DJ BMZ.jpg")) let e6 = TimelineEvent(date: "Aug. 2011", title: "Started College.", descriptionString: "I figured out that the design I’m most interested in was in software, so I decided to go to school for Computer Science. I met by best friend, Peter, who taught me how to take what I learned in class and build native apps for Mac and iOS.", image: UIImage(named: "College.jpg")) content = [e0, e1, e2, e3, e4, e5, e6] } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.flashScrollIndicators() } func flashScrollIndicators() { tableView.flashScrollIndicators() } func scrollToTop() { tableView.setContentOffset(CGPoint(x: 0, y: -self.tableView.contentInset.top), animated: true); } // MARK: UITableViewDataSource func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? { let cell = tableView!.dequeueReusableCellWithIdentifier("Event", forIndexPath: indexPath!) as UITableViewCell // if ( !cell ) { // cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Event"]; // cell.selectionStyle = UITableViewCellSelectionStyleNone; // } if let path = indexPath { let timelineStripeView = cell.contentView?.viewWithTag(222) if !timelineStripeView { let view = UIView(frame: CGRect(x: 128, y: 0, width: 1, height: cell.frame.size.height)) view.tag = 222 view.backgroundColor = UIColor(white: 0.85, alpha: 1) cell.contentView?.addSubview(view) } var timelineEventView = cell.contentView?.viewWithTag(111) as TimelineEventView? if !timelineEventView { let view = TimelineEventView(frame: cell.bounds) view.tag = 111 cell.contentView?.addSubview(view) timelineEventView = view } // WARNING: If content was a TimelineEvent[], no need to "as" timelineEventView?.setUpWithTimelineEvent(content[path.row] as TimelineEvent) } return cell } func numberOfSectionsInTableView(tableView: UITableView) -> NSInteger { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection: NSInteger) -> NSInteger { return content.count } }
true
e5cdb397d5bc41534258cf3c11890307013c90d4
Swift
VRGsoftUA/mygoal-viper-ios
/MyGoal/Core/Validators/SMValidationGroup.swift
UTF-8
1,605
2.640625
3
[]
no_license
// // SMValidationGroup.swift // Contractors // // Created by OLEKSANDR SEMENIUK on 12/23/16. // Copyright © 2016 OnePlanetOps. All rights reserved. // import Foundation import UIKit class SMValidationGroup: AnyObject { var validators: Array<SMValidator> = Array<SMValidator>() open func add(validator aValidator: SMValidator) -> Void { validators.append(aValidator) } open func add(validators aValidators: Array<SMValidator>) -> Void { validators.append(contentsOf: aValidators) } open func removeAllValidators() -> Void { validators.removeAll() } open func validate() -> Array<SMValidationProtocol> { var result: Array<SMValidationProtocol> = Array<SMValidationProtocol>() for validator: SMValidator in validators { if !validator.validate() { result.append(validator.validatableObject!) } } return result } open func applyShakeForWrongFieldsIfCan() -> Void { for obj: SMValidationProtocol in self.validate() { if obj is UIView { (obj as! UIView).transform = CGAffineTransform(translationX: 15, y: 0) UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.curveEaseInOut, animations: { (obj as! UIView).transform = CGAffineTransform.identity }, completion: nil) } } } }
true
1512793457bd1a43a19a782da9b9bcbcec3e7b57
Swift
fredbuluku/coinbase-ios-sdk
/Source/Extentions/Result+promiseCallback.swift
UTF-8
1,066
2.9375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Result+PromiseCallback.swift // Coinbase // // Copyright © 2018 Coinbase, Inc. All rights reserved. // // MARK: - Helper extension to connect handler. internal extension Result { /// Converts `onSuccess` and `onFailure` completion closures into completion handler expecting `Result<Value>`. /// /// - Parameters: /// - onSuccess: Closure which should be called in case of success. /// - value: Value from succeeded result. /// - onFailure: Closure which should be called in case of failure. /// - error: Error from failed result. /// /// - Returns: /// Closure expecting `Result<Value>`. /// static func completeResult(_ onSuccess: @escaping (_ value: Value) -> Void, _ onFailure: @escaping (_ error: Error) -> Void ) -> ((Result<Value>) -> Void) { return { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } }
true
e3ebdf04e9f0950070641ca42a0f42410d097d7e
Swift
mukhammadjonAskarov/SSDTask
/Task1_SSD/Supportfiles/Errors.swift
UTF-8
483
2.96875
3
[]
no_license
// // Errors.swift // Task1_SSD // // Created by Mukhammadjon Askarov on 09/01/21. // import Foundation enum Errors: String, Error { case invalidLinkAddress = "This Link created an invalid request. Please, try again." case unableToComplete = "Unable to complete Your request. Please, check your internet connection" case invalidResponse = "Invalid response from the server. Please, Try again." case invalidData = "The data received from the server was invalid " }
true
2ef65a1f2ac05d367273a18b11ae80bb39092cf7
Swift
parthparikh23/ios-nd-alien-adventure-swift-3
/Alien Adventure/BannedItems.swift
UTF-8
1,799
3.046875
3
[ "MIT" ]
permissive
// // BannedItems.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // import Foundation extension Hero { func bannedItems(dataFile: String) -> [Int] { var items: [Int] = [] if let datafileURL = Bundle.main.url(forResource: dataFile, withExtension: "plist") { let data = NSArray(contentsOf: datafileURL) for item in data! { var name: String? var carbonAge: Int? if let item = item as? NSDictionary { if let itemName = item["Name"] as? String { name = itemName } if let historicalData = item["HistoricalData"] as? [String: AnyObject] { if let itemCarbonAge = historicalData["CarbonAge"] as? Int { carbonAge = itemCarbonAge } } if name!.lowercased().contains("laser") && carbonAge! < 30 { print("\(name) with age \(carbonAge) is banned") items.append(item["ItemID"] as! Int) } else { print("\(name) with age \(carbonAge) kept") } } } print(items) } return items } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 6"
true
fda26216addca29450231e3b659cb84e7b7d51a0
Swift
Yita55/Swift-Design-Pattern
/Factory Method Pattern/Factory Method Pattern/main.swift
UTF-8
468
2.984375
3
[]
no_license
// // main.swift // Factory Method Pattern // // Created by don chen on 2017/3/4. // Copyright © 2017年 Don Chen. All rights reserved. // import Foundation let orderList = [1,3,5,7,9,12,15,18] let factory = ProductFactory.shared var products = [Product]() for order in orderList { let product = factory.createProduct(biscuitCount: order) products.append(product) } for product in products { print(product.name + " - Price: " + "\(product.price)") }
true
1320e1724727ce437ecf0a4ddc9d5089e6edf427
Swift
VitorFerraz/NetworkModuleFramework
/NetworkModule/Engine/Network/NetworkProtocol.swift
UTF-8
360
2.5625
3
[]
no_license
// // NetworkProtocol.swift // NetworkModule // // Created by Vitor Ferraz Varela on 10/03/20. // Copyright © 2020 Vitor Ferraz Varela. All rights reserved. // import Foundation typealias ResultCompletion<T> = (Result<T, Error>) -> Void protocol NetworkProtocol { associatedtype S: Service func request<T: Decodable>(service: S, result: @escaping ResultCompletion<T>) }
true
bfaaf2a8ea45822099156b4aedc06c433ca80406
Swift
MariamElmorshedy/Regestiration-
/First task/ViewController.swift
UTF-8
793
2.625
3
[]
no_license
// // ViewController.swift // First task // // Created by Mariam Elmorshedy on 3/16/20. // Copyright © 2020 Mariam Elmorshedy. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textview: UITextView! override func viewDidLoad() { super.viewDidLoad() updatetextview() } func updatetextview() { let path = "" let text = textview.text ?? "" let attributedString = NSMutableAttributedString.makeHyperlink(for: path, in: text, as: "terms & conditions") textview.attributedText = attributedString textview.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, .underlineStyle:10, .underlineColor: UIColor.red ] } }
true
4344398ba905aee383a249440d5879d41dcd90c5
Swift
funzin/swift-composable-architecture-example
/Target/Core/Core/Source/Request/Coordinator/RootCoordinatorRequest.swift
UTF-8
359
2.609375
3
[]
no_license
import UIKit public struct RootCoordinatorRequest: CoordinatorRequest { public let input: Input public init(input: Input) { self.input = input } } extension RootCoordinatorRequest { public struct Input { public let window: UIWindow public init(window: UIWindow) { self.window = window } } }
true
f1b4580e5efaf95886fef5598fbcde3b5f3ae961
Swift
sEmoto0808/swf-KeychainAccess-demo
/swf-Keychain-demo/swf-Keychain-demo/ViewController.swift
UTF-8
832
2.65625
3
[]
no_license
// // ViewController.swift // swf-Keychain-demo // // Created by S.Emoto on 2018/06/13. // Copyright © 2018年 S.Emoto. All rights reserved. // import UIKit class ViewController: UIViewController { let keychainManager = KeychainManager(withService: "testService", group: "sEmoto.jp.swf-Keychain-demo") override func viewDidLoad() { super.viewDidLoad() let resultSave = keychainManager.save(byKey: "testKey01", value: "testValue03") let resultRemove = keychainManager.delete(byKey: "testKey01") if resultSave && resultRemove { let data1 = keychainManager.getString(byKey: "testKey01") print(data1) let data2 = keychainManager.getString(byKey: "testKey02") print(data2) } } }
true
d04716ff6d0fdc0053bd60baf5075b09730be712
Swift
GodFighter/WRPDFModel
/WRPDFModel/Classes/Model/ContentParser/pdf/extensions/WRPDFString.swift
UTF-8
670
2.53125
3
[ "MIT" ]
permissive
// // String.swift // PDFParser // // Created by Benjamin Garrigues on 24/07/2018. // Copyright © 2018 SimpleApp. All rights reserved. // import Foundation extension String { static func decodePDFInt8CString(_ cString: UnsafePointer<Int8>?, repairingInvalidCodeUnits: Bool = false) -> String? { guard let cString = cString else { return nil } let str = cString.withMemoryRebound(to: UInt8.self, capacity: 1) { (bytes: UnsafePointer<UInt8>) in return String.decodeCString(bytes, as: UTF8.self, repairingInvalidCodeUnits:repairingInvalidCodeUnits) } return str?.result } }
true
77f6afe3d43d0694563b5bd35ca5a26ae9ecd2c1
Swift
jabraham17/Enigma
/Enigma/KeyedVC.swift
UTF-8
21,754
2.53125
3
[]
no_license
// // Keyed.swift // Enigma // // Created by Jacob R. Abraham on 2/28/17. // Copyright © 2017 Jacob R. Abraham. All rights reserved. // import UIKit //TODO: If key is out of range, send warnign to user //view controller for keyed encryptions @IBDesignable class KeyedVC: UIViewController, EncryptionNameHeaderDelegate, EncryptionSelectionDelegate, UITextViewCustomDelegate, UITextFieldCustomDelegate, UIPopoverPresentationControllerDelegate { //the header view from storyboard @IBOutlet var headerView: EncryptionNameHeader! //text fields @IBOutlet var unencryptedField: UITextViewCustom! @IBOutlet var encryptedField: UITextViewCustom! //key field @IBOutlet var keyField: UITextFieldCustom! //positions for encryption text views var topPosition: CGPoint = CGPoint() var bottomPosition: CGPoint = CGPoint() //encrytion class var encryptor: KeyedEncryption = KeyedEncryption(encryption: .None) //key var key: String { //on get, put return the value of encytor key get { return encryptor.key } //on set, put the value into encryptor key, then update the encryption views set { encryptor.key = newValue //update the text updateText() } } //updates the text after a change, ie encrytpion change or key change func updateText() { //if current field is unencrypted, encrypt the text with the new key if currentField == .Unencrypted { encryptText(unencryptedField.text.text) } //if current field is encrypted, decrypt the text with the new key else if currentField == .Encrypted { decryptText(encryptedField.text.text) } } //holds which field is currently on top/allowed to be edited var currentField: Global.TypesOfField = .None //update the view to reflect currentField func updateView() { //if current field is unencrypted, put it at the top, then enable it if currentField == .Unencrypted { unencryptedField.frame.origin = topPosition unencryptedField.editable = true encryptedField.frame.origin = bottomPosition encryptedField.editable = false } //if currentField is encrypted, put it at the top, then enable it else if currentField == .Encrypted { encryptedField.frame.origin = topPosition encryptedField.editable = true unencryptedField.frame.origin = bottomPosition unencryptedField.editable = false } } //change currentField on switch click @IBAction func switchAction(_ sender: UIButtonBorder) { //if unencrypt, change to encrypt if currentField == .Unencrypted { currentField = .Encrypted } //if encrypt, change to unencrypt else if currentField == .Encrypted { currentField = .Unencrypted } updateView() } //current encryption var currentEncyption: Global.EncryptionTypes.Encryptions = .None { //if encryption was set, update the header label: this is done in setEncryption didSet { //update encryption setEncryption() } } //current encryption type, only changes when moving to new view var currentEncyptionType: Global.EncryptionTypes.Types = .Keyed //when the screen loads override func viewDidLoad() { super.viewDidLoad() //add listener for when to save data NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: NSNotification.Name(rawValue: "saveAllData"), object: nil) //add delegate to header headerView.delegate = self //disable the back button self.navigationItem.setHidesBackButton(true, animated: false) //set the delegates for the text views and text field unencryptedField.passingDelegate = self encryptedField.passingDelegate = self keyField.passingDelegate = self //update the encryption setEncryption() } //when the view will diaspear override func viewWillDisappear(_ animated: Bool) { //post notifivtion to save data NotificationCenter.default.post(name: NSNotification.Name(rawValue: "saveAllData"), object: nil) //remove all notification listeners NotificationCenter.default.removeObserver(self) } //after the view has appeared override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //get the inital positions of the encryot fields set them to the top and bottom positions topPosition = unencryptedField.frame.origin bottomPosition = encryptedField.frame.origin //update the view to reflect what it should look like updateView() //when the view appears set key to keyField text key = keyField.field.text! } //on deinit of class deinit { //remove all notification listeners NotificationCenter.default.removeObserver(self) } //save all data func saveData() { //save current position UserData.sharedInstance.setLastUsedEncryptionType(currentEncyptionType) UserData.sharedInstance.setLastUsedEncryption(currentEncyption) UserData.sharedInstance.setLastUsedField(currentField) } //override from EncryptionNameHeaderDelegate, used to determine when the NavigationBar header was tapped //when tapped, open EncryptionSelection func headerWasTapped() { //close the keyboard //if the current field is unencrypted if currentField == .Unencrypted { //close unecrntpted fields keyboard unencryptedField.text.resignFirstResponder() } //if the current field is encrypted else if currentField == .Encrypted { //close ecrntpted fields keyboard encryptedField.text.resignFirstResponder() } //resign the keyboard on the key field keyField.field.resignFirstResponder() //get the view controller let selectionVC = EncryptionSelection() //set the delegate selectionVC.delegate = self //set the source vc selectionVC.sourceViewController = self //set the current encryption of the selection view controller selectionVC.currentEncyption = currentEncyption //set the presentation style to popover selectionVC.modalPresentationStyle = .popover //setup as a popover view controller let popover = selectionVC.popoverPresentationController! //set the delegate as this class popover.delegate = self //anchor the popover to the title view popover.sourceView = self.navigationItem.titleView popover.sourceRect = (self.navigationItem.titleView?.bounds)! //present the popover present(selectionVC, animated: true, completion:nil) } //if the enter button was tapped, determine wether to encryt or decrupt, then do so func enterButton(textView: UITextView, textOfView: String) { //dismiss keyboard textView.resignFirstResponder() //update the key, incase user did not press enter when entering key //this will also update the text views so there is no need to do it again key = keyField.field.text! } //if the share button was tapped, share the text func shareButton(senderButton: UIButton, textToShare: String) { //creat the activity controller to share the text let activityVC = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil) //excluded certian types activityVC.excludedActivityTypes = [.airDrop, .assignToContact, .addToReadingList, .openInIBooks, .postToFlickr, .postToTencentWeibo, .postToVimeo, .postToWeibo, .saveToCameraRoll] //present as a popover activityVC.popoverPresentationController?.sourceView = senderButton self.present(activityVC, animated: true, completion: nil) } //if the enter button was tapped, set the new key func enterButton(textField: UITextField, textOfField: String) { //dismiss keyboard textField.resignFirstResponder() //set new key key = textOfField } //if the share button was tapped, share the key func shareButton(senderButton: UIButton, keyToShare: String) { //creat the activity controller to share the key let activityVC = UIActivityViewController(activityItems: [keyToShare], applicationActivities: nil) //excluded certian types activityVC.excludedActivityTypes = [.airDrop, .assignToContact, .addToReadingList, .openInIBooks, .postToFlickr, .postToTencentWeibo, .postToVimeo, .postToWeibo, .saveToCameraRoll] //present as a popover activityVC.popoverPresentationController?.sourceView = senderButton self.present(activityVC, animated: true, completion: nil) } //override from EncryptionSelectionDelegate, used to determine which encryption was selected //if current encryption, do nothing, otherwise change to anther encryption func encryptionSelected(encryptionType: Global.EncryptionTypes.Types, encryption: Global.EncryptionTypes.Encryptions) { //if the encryption selected is not the same as the current encryption if currentEncyption != encryption { //if its of the same type of encryption, change current encryption to the new one if currentEncyptionType == encryptionType { currentEncyption = encryption } //otherwise, change to another encryption type else { //set the new encryption and encryotin type currentEncyption = encryption currentEncyptionType = encryptionType //save all the data saveData() //unwind the segue, this pops current view off the stack _ = self.navigationController?.popViewController(animated: false) } } } //set the current encryption type func setEncryption() { //post notifivtion to save data NotificationCenter.default.post(name: NSNotification.Name(rawValue: "saveAllData"), object: nil) //update the header headerView.name.text = self.currentEncyption.description switch currentEncyption { //if Caesar, make CaesarCipher encryption case .Caesar: encryptor = CaesarCipher(key: key) //set the special keyboards for caesar cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .numberPad //unhide the toolbar on the keyboard keyField?.keyboardToolBarHidden = false unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break //if XOR, make XORCipher encryption case .XOR: encryptor = XORCipher(key: key) //set the special keyboards for xor cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .numberPad //unhide the toolbar on the keyboard keyField?.keyboardToolBarHidden = false unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break //if Trans, make TranspositionCipher encryption case .Keyword: encryptor = KeywordCipher(key: key) //set the special keyboards for trans cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .asciiCapable //hide the toolbar on the keyboard keyField?.keyboardToolBarHidden = true unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break //if RailFence, make RailFenceCipher encryption case .RailFence: encryptor = RailFenceCipher(key: key) //set the special keyboards for rail fence cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .numberPad //hide the toolbar on the keyboard keyField?.keyboardToolBarHidden = true unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break //if Columnar, make ColumnarCipher encryption case .Columnar: encryptor = ColumnarCipher(key: key) //set the special keyboards for columnar cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .asciiCapable //hide the toolbar on the keyboard keyField?.keyboardToolBarHidden = true unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break //if Vigenere, make VigenereCipher encryption case .Vigenere: encryptor = VigenereCipher(key: key) //set the special keyboards for vigenere cipher //MUST BE OPTIONAL: otherwise fields may not be initilized yet so code will crash keyField?.field.keyboardType = .asciiCapable //hide the toolbar on the keyboard keyField?.keyboardToolBarHidden = true unencryptedField?.text.keyboardType = .asciiCapable encryptedField?.text.keyboardType = .asciiCapable break default: //shouldnt ever get here break } updateText() } //when info button clicked, show information popup with current encryption view showing @IBAction func infoButton(_ sender: UIBarButtonItem) { Global.information(viewShowing: .Current, containerView: self, animated: true) } //delegate function from UIPopoverControllerDelegate //present in popover style func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } //encrypt the text func encryptText(_ text: String) { do { //encrypt the text and output it let encryptedText = try encryptor.encrypt(text) encryptedField.text.text = encryptedText } //if there is an invaild character, tell the user catch Global.EncryptionErrors.InvalidCharacter(_, let message) { Global.popup(withTitle: "Invalid Character", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the unecryptex text field self.unencryptedField.text.becomeFirstResponder() }), UIAlertAction(title: "Clear Text", style: .destructive, handler: { (alert) in //if the user wants to clear the text, do so self.unencryptedField.text.text = "" self.encryptedField.text.text = "" })], presentOn: self) } //if the text is invaild, tell the user catch Global.EncryptionErrors.InvalidText(let message) { Global.popup(withTitle: "Invalid Text", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the unecryptex text field self.unencryptedField.text.becomeFirstResponder() }), UIAlertAction(title: "Clear Text", style: .destructive, handler: { (alert) in //if the user wants to clear the text, do so self.unencryptedField.text.text = "" self.encryptedField.text.text = "" })], presentOn: self) } //if the key is invalid catch Global.EncryptionErrors.InvalidKey(_, let message) { Global.popup(withTitle: "Invalid Key", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the key text field self.keyField.field.becomeFirstResponder() }), UIAlertAction(title: "Clear Key", style: .destructive, handler: { (alert) in //if the user wants to clear the key, do so self.keyField.field.text = "" })], presentOn: self) } //if the key is catch Global.EncryptionErrors.KeyOutOfRange(_, let message) { Global.popup(withTitle: "Key out of Range", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the key text field self.keyField.field.becomeFirstResponder() }), UIAlertAction(title: "Clear Key", style: .destructive, handler: { (alert) in //if the user wants to clear the key, do so self.keyField.field.text = "" })], presentOn: self) } catch { //shoudlnt get here } } //decrypt the text func decryptText(_ text: String) { do { //decrypt the text and output it let unencryptedText = try encryptor.decrypt(text) unencryptedField.text.text = unencryptedText } //if there is an invaild character, tell the user catch Global.EncryptionErrors.InvalidCharacter(_, let message) { Global.popup(withTitle: "Invalid Character", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the ecryptex text field self.encryptedField.text.becomeFirstResponder() }), UIAlertAction(title: "Clear Text", style: .destructive, handler: { (alert) in //if the user wants to clear the text, do so self.encryptedField.text.text = "" self.unencryptedField.text.text = "" })], presentOn: self) } //if the text is invaild, tell the user catch Global.EncryptionErrors.InvalidText(let message) { Global.popup(withTitle: "Invalid Text", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the ecryptex text field self.encryptedField.text.becomeFirstResponder() }), UIAlertAction(title: "Clear Text", style: .destructive, handler: { (alert) in //if the user wants to clear the text, do so self.encryptedField.text.text = "" self.unencryptedField.text.text = "" })], presentOn: self) } //if the key is invalid catch Global.EncryptionErrors.InvalidKey(_, let message) { Global.popup(withTitle: "Invalid Key", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the key text field self.keyField.field.becomeFirstResponder() }), UIAlertAction(title: "Clear Key", style: .destructive, handler: { (alert) in //if the user wants to clear the key, do so self.keyField.field.text = "" })], presentOn: self) } //if the key is catch Global.EncryptionErrors.KeyOutOfRange(_, let message) { Global.popup(withTitle: "Key out of Range", message: message, buttons: [ UIAlertAction(title: "Ok", style: .default, handler: {(alert) in //if the user wants to do nothing, open up the keyboard on the key text field self.keyField.field.becomeFirstResponder() }), UIAlertAction(title: "Clear Key", style: .destructive, handler: { (alert) in //if the user wants to clear the key, do so self.keyField.field.text = "" })], presentOn: self) } catch { //shoudlnt get here } } }
true
e693fa4e895ea09f0cabdd04eee1c4cdf85fdf46
Swift
tnantoka/swiftbook-examples
/Chapter12/ProgrammaticallyActivity/ProgrammaticallyActivity/ViewController.swift
UTF-8
1,282
2.6875
3
[ "MIT", "Apache-2.0" ]
permissive
// // ViewController.swift // ProgrammaticallyActivity // // Created by Tobioka on 2017/10/29. // Copyright © 2017年 tnantoka. All rights reserved. // import UIKit class ViewController: UIViewController { /// [marker1] let activity = UIActivityIndicatorView(activityIndicatorStyle: .gray) /// [marker1] /// [marker2] override func viewDidLoad() { super.viewDidLoad() activity.hidesWhenStopped = false activity.frame.origin = CGPoint(x: 10.0, y: 20.0) view.addSubview(activity) let button = UIButton(type: .system) button.frame = CGRect(x: 10.0, y: activity.frame.maxY + 8.0, width: 150.0, height: 30.0) button.setTitle("スタート・ストップ", for: .normal) button.addTarget(self, action: #selector(onTap), for: .touchUpInside) view.addSubview(button) } /// [marker2] override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// [marker3] @objc func onTap(sender: Any) { if activity.isAnimating { activity.stopAnimating() } else { activity.startAnimating() } } /// [marker3] }
true
9d39bda383d2e24af89eb6ec078e3f5d0f8f3d8e
Swift
janbjelicic/Collections
/Collections/Domain/NetworkManager.swift
UTF-8
1,190
3.1875
3
[]
no_license
// // NetworkManager.swift // Collections // // Created by Jan Bjelicic on 19/03/2021. // import Foundation protocol NetworkManagerProtocol { func request(urlRequest: NetworkRequest, completion: @escaping (Result<Any, Error>) -> ()) } class NetworkManager: NetworkManagerProtocol { private let session = URLSession.shared func request(urlRequest: NetworkRequest, completion: @escaping (Result<Any, Error>) -> ()) { guard let request = urlRequest.getRequest() else { return } let task = session.dataTask(with: request) { data, urlResponse, error in if let error = error { completion(.failure(error)) } guard let data = data else { completion(.failure(NetworkError.invalidResponse)) return } do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) completion(.success(json)) } catch (let error) { completion(.failure(NetworkError.parsingError(error.localizedDescription))) } } task.resume() } }
true
cd2b54a6b78e941abae4ee26c9c463c6e73b5962
Swift
gilserrap/PromptRating
/PromptRating/PromptRating/Model/PromptRule.swift
UTF-8
4,105
2.78125
3
[]
no_license
import Foundation public typealias Condition = (Int, PromptEvent) open class PromptRule: NSObject, NSCoding { fileprivate let mainEvent: PromptEvent fileprivate var conditions = [PromptCondition]() fileprivate var ruleTransitions = [RuleTransition]() public init(forEvent event: PromptEvent) { mainEvent = event } public init(mainEvent: PromptEvent, conditions: [PromptCondition], ruleTransitions: [RuleTransition]) { self.mainEvent = mainEvent self.conditions = conditions self.ruleTransitions = ruleTransitions } open func showForTheFirstTimeAfter(_ conditions: Condition...) -> PromptRule { self.conditions = mapConditionsToPromptConditions(conditions) return self } open func whenPromptRatingIs(_ result: PromptResult, showAfter conditions: Condition...) -> PromptRule { ruleTransitions.append(RuleTransition(result: result, conditions: mapConditionsToPromptConditions(conditions))) return self } internal func changeConditionsFor(_ promptResult: PromptResult) -> Bool { guard let transition = ruleTransitions.filter({ $0.result == promptResult }).first else { return false } conditions = transition.conditions return true } internal func addEvents(_ events: [PromptEvent]) { for condition in conditions { condition.eventCount = events.reduce(condition.eventCount) { (eventCount, event) -> Int in if condition.event == event { return eventCount + 1 } return eventCount } } } internal func eventIsRelevant(_ event: PromptEvent) -> Bool { return conditions.filter { $0.event == event }.count > 0 || event == mainEvent } internal func resetEvents() { for condition in conditions { condition.eventCount = 0 } } internal func isSatisfied() -> Bool { for condition in conditions { if !condition.isSatisfied() { return false } } return true } internal func isTriggeredByEvent(_ event: PromptEvent) -> Bool { return event == mainEvent } fileprivate func mapConditionsToPromptConditions(_ conditions: [Condition]) -> [PromptCondition] { return conditions.map { condition -> PromptCondition in return PromptCondition( event: condition.1, threshold: condition.0, eventCount: 0 ) } } //MARK: NSObject open override func isEqual(_ object: Any?) -> Bool { if let otherObject = object as? PromptRule { return otherObject.ruleTransitions == self.ruleTransitions && otherObject.mainEvent.value() == self.mainEvent.value() } return false } open override var description: String { return self.mainEvent.value() } //MARK: NSCoding struct PropertyKey { static let mainEvent = "mainEvent" static let conditions = "conditions" static let transitions = "transitions" } open func encode(with aCoder: NSCoder) { aCoder.encode(mainEvent.value(), forKey: PropertyKey.mainEvent) aCoder.encode(conditions, forKey: PropertyKey.conditions) aCoder.encode(ruleTransitions, forKey: PropertyKey.transitions) } public required convenience init?(coder aDecoder: NSCoder) { let mainEvent = PromptRatingEvent(name: aDecoder.decodeObject(forKey: PropertyKey.mainEvent) as! String) let conditions = aDecoder.decodeObject(forKey: PropertyKey.conditions) as! [PromptCondition] let ruleTransitions = aDecoder.decodeObject(forKey: PropertyKey.transitions) as! [RuleTransition] self.init(mainEvent: mainEvent, conditions: conditions, ruleTransitions: ruleTransitions) } }
true
fd7a857cafd59b9cebe6e985f7a828170ede7b4f
Swift
meghanreynolds/UIUC-Student-Planner
/UIUC Student Planner/UIUC Student Planner/SupportingView/TagView.swift
UTF-8
2,397
2.953125
3
[]
no_license
// // TagPickerView.swift // UIUC Student Planner // // Created by Jeffery Wang on 10/25/20. // import SwiftUI import CoreData struct TagPicker: View{ @State var createNewTag = false @State var newTagName: String = "" @Binding var selectedTags: Array<Tag> @Environment(\.managedObjectContext) private var viewContext //The fetch request getting all the assignments and sorting them by their timestamps @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Tag.name, ascending: true)], animation: .default) private var tags: FetchedResults<Tag> var body: some View{ Spacer() HStack{ Button("+"){ self.createNewTag.toggle() }.font(Font.system(size: 25)) Spacer() }.padding([.leading, .trailing], 20) if self.createNewTag{ HStack{ TextField("new tag name", text: self.$newTagName) Button("cancel") { self.newTagName = "" self.createNewTag.toggle() } Button("save"){ let t = Tag(context: self.viewContext) t.name = self.newTagName do{ try self.viewContext.save() }catch{ } self.selectedTags.append(t) self.newTagName = "" self.createNewTag.toggle() }.disabled(self.newTagName == "") }.padding([.leading, .trailing], 20) } List{ ForEach.init(self.tags) { tag in HStack{ Text(tag.name!) Spacer() if self.selectedTags.contains(tag){ Image.init(systemName: "checkmark").foregroundColor(.blue) }else{ EmptyView() } }.contentShape(Rectangle()).onTapGesture { if self.selectedTags.contains(tag){ self.selectedTags.remove(at: self.selectedTags.firstIndex(of: tag)!) }else{ self.selectedTags.append(tag) } } } }.navigationTitle("Tags") } }
true
ab615b2ef42ec7d96791e495db73425df0b34a51
Swift
Bionik6/Prometheus
/PrometheusTests/PrometheusTests.swift
UTF-8
3,286
2.578125
3
[]
no_license
// // PrometheusTests.swift // PrometheusTests // // Created by Ibrahima Ciss on 2/15/19. // Copyright © 2019 Ibrahima Ciss. All rights reserved. // import XCTest @testable import Prometheus class PrometheusTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } func testInitializeWithValue() { let promise = Promise(value: 5) XCTAssertNotNil(promise.value) if let value = promise.value { XCTAssertEqual(value, 5) } } func testFullfillPromiseSetsValue() { let stringValue = "Hello World" let promise = Promise<String>() XCTAssertNil(promise.value) promise.fullfill(stringValue) XCTAssertNotNil(promise.value) if let value = promise.value { XCTAssertEqual(value, stringValue) } } func testFullfillCallsThenBlock() { let stringValue = "Hello World" let promise = Promise<String>() let exp = expectation(description: "did not call then block") _ = promise.then { value in exp.fulfill() XCTAssertEqual(value, stringValue) } promise.fullfill(stringValue) wait(for: [exp], timeout: 1.0) } func testFailCallsCatchBlock() { let promise = Promise<String>() let exp = expectation(description: "did not call catch block") let testError = NSError(domain: "test", code: 1, userInfo: nil) promise.then { value in XCTFail() }.catch { error in exp.fulfill() let e = error as NSError XCTAssertEqual(e.domain, "test") XCTAssertEqual(e.code, 1) } promise.fail(testError) wait(for: [exp], timeout: 1.0) } func testFailSetsError() { let promise = Promise<String>(value: nil) let testError = NSError(domain: "test", code: 1, userInfo: nil) promise.fail(testError) XCTAssertNotNil(promise.error) if let error = promise.error as NSError? { XCTAssertEqual(error, testError) } } func testMapTransformsFutureValue() { let promise = Promise<Int>() let exp = expectation(description: "did not call then block") promise.map { x in return String(x) }.then { value in exp.fulfill() XCTAssertEqual(value, "5") }.catch { _ in XCTFail() } promise.fullfill(5) wait(for: [exp], timeout: 1.0) } func testMapCarriesOverErrors() { let promise = Promise<Int>() let testError = NSError(domain: "test", code: 1, userInfo: nil) let exp = expectation(description: "did not call catch block") promise.map { x in return String(x) }.then { _ in XCTFail() }.catch { error in exp.fulfill() let e = error as NSError XCTAssertEqual(e.domain, "test") XCTAssertEqual(e.code, 1) } promise.fail(testError) wait(for: [exp], timeout: 1.0) } }
true
a04f566f93f24dc68b0ce8c3c5b7649801430bbc
Swift
AndreFirmoo/TestIOS
/Bank/Bank/Models/Mappers/UserMapper.swift
UTF-8
469
2.671875
3
[]
no_license
// // UserMapper.swift // Bank // // Created by Andre Jardim Firmo on 26/06/20. // Copyright © 2020 Andre Jardim Firmo. All rights reserved. // import Foundation struct UserMapper: Codable { let userAccount: UserInfo let error: ErrorResponse } struct UserInfo: Codable { let userId: Double? let name: String? let bankAccount: String? let agency: String? let balance: Double? } struct ErrorResponse: Codable { let code: Int? let message: String? }
true
40511b159d78047979823362e9399f06c52d0179
Swift
jmhdevelop/SimpleQR
/Example/SimpleQR/ViewController.swift
UTF-8
828
2.53125
3
[ "MIT" ]
permissive
// // ViewController.swift // SimpleQR // // Created by jmhdevelop on 04/19/2019. // Copyright (c) 2019 jmhdevelop. All rights reserved. // import UIKit import SimpleQR class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var imageView: UIImageView! @IBAction func buttonGenerate(_ sender: Any) { if let text = textField.text, !text.isEmpty { imageView.image = SimpleQR.shared.imageQR(text) } } override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
true
5245da5b11ff57279a34db41d053bb1e2d2819c2
Swift
Harman-Orsay/iOS-Enterprise-App-1
/AnAppKit/AnAppKit/Model/Model/UserSession.swift
UTF-8
716
2.90625
3
[]
no_license
// // UserSession.swift // AnAppKit // // Created by Rohan Ramsay on 12/01/21. // import Foundation public typealias AuthToken = String struct RemoteUserSession: Codable { let token: AuthToken let createdOn: Date init(token: AuthToken, createdOn: Date) { self.token = token self.createdOn = createdOn } } public struct UserSession: Codable { public let profile: UserProfile let remoteSession: RemoteUserSession var validity: TimeInterval {10000000} init(profile: UserProfile, remoteSession: RemoteUserSession) { self.profile = profile self.remoteSession = remoteSession } public var logInDate: Date { remoteSession.createdOn } }
true
cc97b59c4bbb6bab99090ac7c1804da900bc93f0
Swift
joqqy/psd.swift
/Source/flash/utils/Endian.swift
UTF-8
2,187
3.5
4
[]
no_license
// // Endian.swift // ByteArray // // Created by featherJ on 15/12/22. // Copyright © 2015年 Test. All rights reserved. // /** Endian 类中包含一些值,它们表示用于表示多字节数字的字节顺序。字节顺序为 bigEndian(最高有效字节位于最前)或 littleEndian(最低有效字节位于最前)。<br><br> The Endian class contains values that denote the byte order used to represent multibyte numbers. The byte order is either bigEndian (most significant byte first) or littleEndian (least significant byte first). - author: featherJ */ public class Endian { /** 表示多字节数字的最高有效字节位于字节序列的最前面。<p> 十六进制数字 0x12345678 包含 4 个字节(每个字节包含 2 个十六进制数字)。最高有效字节为 0x12。最低有效字节为 0x78。(对于等效的十进制数字 305419896,最高有效数字是 3,最低有效数字是 6)。<br><br> Indicates the most significant byte of the multibyte number appears first in the sequence of bytes.<p> The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6). */ public static let BIG_ENDIAN: String = "bigEndian"; /** 表示多字节数字的最低有效字节位于字节序列的最前面。<p> 十六进制数字 0x12345678 包含 4 个字节(每个字节包含 2 个十六进制数字)。最高有效字节为 0x12。最低有效字节为 0x78。(对于等效的十进制数字 305419896,最高有效数字是 3,最低有效数字是 6)。<br><br> Indicates the least significant byte of the multibyte number appears first in the sequence of bytes.<p> The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6). */ public static let LITTLE_ENDIAN: String = "littleEndian"; }
true
57fee9e6bf26196101482b6c6b8fa7d7a028870e
Swift
EsmerlinMoya/swift-viewLifeCycle-lab-swift-intro-000
/FunWithViews/ViewController.swift
UTF-8
3,415
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
// // ViewController.swift // FunWithViews // // Created by Jim Campagno on 9/17/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var viewOne: UIView! @IBOutlet weak var viewTwo: UIView! @IBOutlet weak var viewThree: UIView! @IBOutlet weak var viewFour: UIView! @IBOutlet weak var viewFive: UIView! @IBOutlet weak var viewSix: UIView! @IBOutlet weak var viewSeven: UIView! @IBOutlet weak var displayScore: UILabel! @IBOutlet weak var clearBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func dieButtonTapped(_ sender: AnyObject) { func updateScoreLabel (roll: Int) { let diceScore = String(roll) if roll > 0{ displayScore.text = diceScore displayScore.isHidden = false } else { displayScore.text = "No Value Yet!" displayScore.isHidden = true } } func rearrangeCubes(roll: Int) { if roll == 1{ viewSeven.isHidden = false } else if roll == 2{ viewThree.isHidden = false viewFour.isHidden = false } else if roll == 3{ viewThree.isHidden = false viewSeven.isHidden = false viewFour.isHidden = false } else if roll == 4{ viewOne.isHidden = false viewThree.isHidden = false viewFour.isHidden = false viewSix.isHidden = false } else if roll == 5{ viewOne.isHidden = false viewThree.isHidden = false viewSeven.isHidden = false viewFour.isHidden = false viewSix.isHidden = false } else if roll == 6{ viewOne.isHidden = false viewTwo.isHidden = false viewThree.isHidden = false viewFour.isHidden = false viewFive.isHidden = false viewSix.isHidden = false } else{ displayScore.text = "Unknown Error" } } func program(){ //updateScoreLabel(roll: randomDiceRoll()) // rearrangeCubes(roll: randomDiceRoll()) } program() } // Returns back a random Int (1, 2, 3, 4, 5, or 6) }
true
a8a766591eafe1f701acef68a9b08958128cfe08
Swift
Wilfred/difftastic
/sample_files/swift_before.swift
UTF-8
36
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
func f(_ x: Int) -> Int { x * 2 }
true
8d77a7d120cd7dc50383837f9e6a3bf65ed6c603
Swift
linchenko/SoFi-Coding-Challenge
/SoFi Coding Challenge/Model/Helpers.swift
UTF-8
1,697
3.15625
3
[]
no_license
// // Helpers.swift // SoFi Coding Challenge // // Created by Levi Linchenko on 20/11/2018. // Copyright © 2018 Levi Linchenko. All rights reserved. // import UIKit // Image Cache to prevent unessasary reloading of images let imageCache = NSCache<NSString, AnyObject>() // Custom Image View to assure images are being displayed in the currect cells class CustomImageView: UIImageView { var urlString: String? func loadImage(with url: URL){ urlString = url.absoluteString let spinner = UIActivityIndicatorView(style: .gray) spinner.startAnimating() spinner.frame = self.frame self.addSubview(spinner) image = nil //If image has already been loaded, pull from cache instead of loading twice if let image = imageCache.object(forKey: NSString(string: url.absoluteString)) as? UIImage { self.image = image spinner.removeFromSuperview() return } URLSession.shared.dataTask(with: url) { (data, _, error) in DispatchQueue.main.async { guard let data = data, let imageToCache = UIImage(data: data) else {return} if self.urlString == url.absoluteString { self.image = imageToCache spinner.removeFromSuperview() } imageCache.setObject(imageToCache, forKey: NSString(string: url.absoluteString)) if let error = error { print ("💩💩 error in file \(#file), function \(#function), \(error),\(error.localizedDescription)💩💩") } } }.resume() } }
true
0fee6d1c8c41dd3fb5bce663b0603d63082ffb05
Swift
XColdStar/DownloadForSwift
/DownloadForSwift/CSDownloader.swift
UTF-8
1,409
3.015625
3
[]
no_license
// // CSDownloader.swift // DownloadForSwift // // Created by hanxing on 2019/11/1. // Copyright © 2019 hanxing. All rights reserved. // import UIKit class CSDownloader: NSObject { static let instance = CSDownloader() lazy var taskQueue = { return Dictionary<String, Any>() }() func download(url: String, progressCallback: @escaping ProgressCallback,finishCallback: @escaping FinishCallback) { var task = taskQueue[url] as? CSDownloadTask if task == nil { task = CSDownloadTask() taskQueue[url] = task } //MARK: >> finishCallback作为尾随闭包可以简写 << _ = task!.download(url: url, progressCallback: progressCallback) {[weak self] (isSuccess, filePath, errorInfo) in if isSuccess { self?.taskQueue .removeValue(forKey: url) } finishCallback(isSuccess,filePath,errorInfo) } } //MARK: >> 暂停 << func pause(url: String) { if let task = taskQueue[url] as? CSDownloadTask { task.pause() } else { print("暂停下载失败") } } //MARK: >> 恢复下载 << func resume(url: String) { if let task = taskQueue[url] as? CSDownloadTask { task.resume() } else { print("恢复下载失败") } } }
true
be887da0dfebaecb1dde70f4ed71416e0658a2e0
Swift
Jride/FoundationExtended
/FoundationExtendedTests/(T) Extensions/(T) Foundation/Date+ExtensionsTests.swift
UTF-8
2,561
3.25
3
[]
no_license
// // Date+ExtensionsTests.swift // FoundationExtendedTests // // Created by Steve Barnegren on 25/06/2018. // Copyright © 2018 ITV. All rights reserved. // import XCTest class DateExtensionsTests: XCTestCase { // MARK: - Creation func testInitWithDayMonthYear() { let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy" let datesAndStrings: [(Date, String)] = [ (Date.init(day: 1, month: 1, year: 2000), "01/01/2000"), (Date.init(day: 14, month: 2, year: 1987), "14/02/1987"), (Date.init(day: 18, month: 11, year: 2019), "18/11/2019") ] for (date, string) in datesAndStrings { XCTAssertEqual(formatter.string(from: date), string) } } func testInitWithDayMonthYearHourMinute() { let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy HH:mm" let datesAndStrings: [(Date, String)] = [ (Date.init(day: 1, month: 1, year: 2000, hour: 1, minute: 15), "01/01/2000 01:15"), (Date.init(day: 14, month: 2, year: 1987, hour: 15, minute: 30), "14/02/1987 15:30"), (Date.init(day: 18, month: 11, year: 2019, hour: 19, minute: 56), "18/11/2019 19:56") ] for (date, string) in datesAndStrings { XCTAssertEqual(formatter.string(from: date), string) } } // MARK: - MillisecondsSince1970 func testInitWithMillisecondsSince1970() { let secondsDate = Date(timeIntervalSince1970: 500) let millisecondsDate = Date(millisecondsSince1970: 500000) XCTAssertEqual(millisecondsDate, secondsDate) } // MARK: - Retriving day / month / year func testDayComputedProperty() { let date = Date(day: 5, month: 1, year: 2000) XCTAssertEqual(date.day, 5) } func testMonthComputedProperty() { let date = Date(day: 1, month: 5, year: 2000) XCTAssertEqual(date.month, 5) } func testYearComputedProperty() { let date = Date(day: 1, month: 1, year: 2000) XCTAssertEqual(date.year, 2000) } // MARK: - Adding days func testAddingDays() { let date = Date(day: 1, month: 1, year: 2000) guard let newDate = date.adding(days: 3) else { XCTFail("Failed to create date") return } XCTAssertEqual(newDate.day, 4) } }
true
a27f44ef2ccd61eb3a082b5dc2b8627728df7df9
Swift
publicfarley/FunctionalCalculator
/FunctionalCalculator/StringToModelTypeConversion.swift
UTF-8
393
2.90625
3
[]
no_license
// // StringConversion.swift // FunctionalCalculator // // Created by Farley Caesar on 2016-04-16. // Copyright © 2016 AppObject. All rights reserved. // import Foundation func stringToInt(_ x: String) -> Int? { return Int(x) } func stringToNonZeroInt(_ x: String) -> NonZeroInt? { guard let number = stringToInt(x) else { return nil } return NonZeroInt(number: number) }
true
58d3023a324b7406b019edd09061aadac7094284
Swift
bljubisic/SportsOrganizer
/SportsOrganizer/ViewModel/TokenViewModelProtocol.swift
UTF-8
651
2.5625
3
[]
no_license
// // TokenViewModelProtocol.swift // SportsOrganizer // // Created by Bratislav Ljubisic on 9/23/17. // Copyright © 2017 Bratislav Ljubisic. All rights reserved. // import Foundation import RxSwift protocol TokenViewModelOutputs { var messageObservable: Observable<CommMessage> { get } var phone🔢: String { get } } protocol TokenViewModelInputs { func createTokenMessage() -> TokenMessage func sendToken(Message message: TokenMessage) -> Bool } protocol TokenViewModelProtocol { var token: String { set get } var model: SOModelProtocol { get } var outputs: TokenViewModelOutputs { get } var inputs: TokenViewModelInputs { get } }
true
a62a8e9d9395619581776967ecf89cfb0608d7ff
Swift
teanet/VNBase
/VNBase/Classes/View/Table/Cell/BaseCell.swift
UTF-8
3,649
2.703125
3
[ "MIT" ]
permissive
import UIKit public typealias RegisterableClass = Registerable.Type public typealias SizeableClass = Sizeable.Type public protocol Registerable: AnyObject { static func identifier() -> String static func nib() -> UINib? } public protocol IHaveHeight: AnyObject { static func internalHeight(with viewModel: BaseCellVM, width: CGFloat) -> CGFloat static func internalEstimatedHeight(with viewModel: BaseCellVM) -> CGFloat } public protocol Sizeable { static func size() -> CGSize } public extension UITableView { func register(cell: RegisterableClass) { guard let cellClass = cell as? UITableViewCell.Type else { assertionFailure("Can't register cell class \(String(describing: cell))") return } let identifier = cell.identifier() if let nib = cell.nib() { self.register(nib, forCellReuseIdentifier: identifier) } else { self.register(cellClass, forCellReuseIdentifier: identifier) } } func register(header: RegisterableClass) { guard let cellClass = header as? UITableViewHeaderFooterView.Type else { assertionFailure("Can't register cell class \(String(describing: header))") return } let identifier = header.identifier() self.register(cellClass, forHeaderFooterViewReuseIdentifier: identifier) } func register(cells: RegisterableClass...) { self.register(cells: cells) } func register(cells: [RegisterableClass]) { for cell in cells { self.register(cell: cell) } } func register(headers: RegisterableClass...) { self.register(headers: headers) } func register(headers: [RegisterableClass]) { for header in headers { self.register(header: header) } } } open class BaseCell<TViewModel: BaseCellVM>: UITableViewCell, Registerable, IHaveHeight, IHaveViewModel, ViewModelChangedDelegate { open override class var requiresConstraintBasedLayout: Bool { true } open var viewModelObject: BaseVM? { didSet { if oldValue?.didChangeDelegate === self { oldValue?.didChangeDelegate = nil } self.viewModelObject?.didChangeDelegate = self self.viewModelChanged() } } public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var constraintsCreated = false public static func internalHeight(with viewModel: BaseCellVM, width: CGFloat) -> CGFloat { guard let vm = viewModel as? TViewModel else { return UITableView.automaticDimension } return self.height(with: vm, width: width) } public static func internalEstimatedHeight(with viewModel: BaseCellVM) -> CGFloat { guard let vm = viewModel as? TViewModel else { return 100 } return self.estimatedHeight(with: vm) } open class func height(with viewModel: TViewModel, width: CGFloat) -> CGFloat { return UITableView.automaticDimension } open class func estimatedHeight(with viewModel: TViewModel) -> CGFloat { return 50 } public static func identifier() -> String { return TViewModel.reuseIdentifier } open class func nib() -> UINib? { return nil } open override func prepareForReuse() { super.prepareForReuse() self.viewModel = nil } open var viewModel: TViewModel? { get { return self.viewModelObject as? TViewModel } set { self.viewModelObject = newValue } } open func viewModelChanged() { } open override func updateConstraints() { if !self.constraintsCreated { self.createConstraints() self.constraintsCreated = true } super.updateConstraints() } open func createConstraints() { } }
true
1185e6aa8dc239735dd9e8d11fc72ec781e1da0e
Swift
appswithlove/updraft-sdk-ios
/Updraft/Network/FeedbackEnabled/FeedbackEnabledResource.swift
UTF-8
515
2.609375
3
[ "MIT" ]
permissive
// // FeedbackEnabledResource.swift // Updraft // // Created by Raphael Neuenschwander on 18.10.18. // Copyright © 2018 Apps with love AG. All rights reserved. // import Foundation enum FeedbackEnabledResource { case isEnabled(params: [String: Any]?) } extension FeedbackEnabledResource: ApiResource { var path: String { return "/feedback-mobile-enabled/" } var method: NetworkMethod { return .post } var parameters: [String: Any]? { switch self { case .isEnabled(let params): return params } } }
true
11c42462d3bc227ac62def2e8313fc90467eab0d
Swift
MinaMinchy/fizz_buzz_Swift
/FizzBuzzTests/testSayNumber.swift
UTF-8
659
2.59375
3
[]
no_license
// // testSayNumber.swift // FizzBuzzTests // // Created by Amina on 16/04/2019. // Copyright © 2019 Amina. All rights reserved. // import XCTest @testable import FizzBuzz class testSayNumber: XCTestCase { let brain = Brain() override func 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. } func testSayNumber() { let result = brain.check(number: 1) XCTAssertEqual(result, "1") } }
true
719672032aab063dee3c653eb4d4f825d8b4cc67
Swift
jimnastic/Itch
/Itch/data.swift
UTF-8
759
2.71875
3
[]
no_license
// // data.swift // Itch // // Created by James May on 22/11/16. // Copyright © 2016 James May. All rights reserved. // import Foundation struct gameState{ // keep track of the game static var isEndGame = false //gameover } struct gameSettings{ // set gameplay constants static var bubbleRadius = 50 // size of bubbles static var playingBlind = false //if playingBlind then bubbles are invisible static var initialBubbles = 6 // sets the number of bubbles to add during setup static var maxBubbles = 12 // sets the seconds before new bubble spawned static var timerInterval = 10 // sets the seconds before new bubble spawned static var respawning = true // new bubbles created on timer } var bubbleWrap: UIBubbleWrap?
true
78e41610d1e75fd9d99e95f01f1d1f80289e1c16
Swift
chrislasers/pholio01
/pholio01/ViewControllers/UserProfile/Location.swift
UTF-8
751
2.671875
3
[]
no_license
// // Location.swift // pholio01 // // Created by Chris Ransom on 10/16/21. // Copyright © 2021 Chris Ransom. All rights reserved. // import UIKit class Location { var location : UIImage init( location :UIImage ) { self.location = location } static func FetchCourse () -> [Location] { return [ Location(location: UIImage(named: "location1a" )!) , Location(location: UIImage(named: "location2a" )!) , Location(location: UIImage(named: "location3a" )!) , Location(location: UIImage(named: "location4a" )!) , Location(location: UIImage(named: "location5a" )!) , ] } }
true
2df7529df89d0fd63d2e06b875e3dba1703204db
Swift
AyaFathy01/CustomTableViewCells
/CustomTableViewCells/CustomTableViewCells/ViewController.swift
UTF-8
1,939
3.078125
3
[]
no_license
// // ViewController.swift // CustomTableViewCells // // Created by Wael Moharram on 6/15/20. // Copyright © 2020 aya fathy. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var table: UITableView! override func viewDidLoad() { super.viewDidLoad() table.register(FieldTableViewCell.nib(), forCellReuseIdentifier: "FieldTableViewCell") table.register(MyTableViewCell.nib(), forCellReuseIdentifier: "MyTableViewCell") table.delegate = self table.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 9 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row > 5 { let fieldCell = table.dequeueReusableCell(withIdentifier: "FieldTableViewCell", for: indexPath) as! FieldTableViewCell return fieldCell } if indexPath.row > 2 { let customCell = table.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell customCell.configure(title: "hello Aya", image: "image_1") return customCell } let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "hello" let mySwitch = UISwitch() mySwitch.addTarget(self, action: #selector(didChangeSwitch(_:)), for: .valueChanged) mySwitch.isOn = true cell.accessoryView = mySwitch return cell } @objc func didChangeSwitch(_ sender: UISwitch){ if sender .isOn { print("turned on") }else { print("turned off") } } }
true
6d5cee3f3bc84b7dd105e00765458a7cb87379de
Swift
vpark777/LearnSwift
/Networking/URLSession/NetworkingExample/Controller/ViewController.swift
UTF-8
6,100
3.234375
3
[]
no_license
// // ViewController.swift // NetworkingExample // // Created by Hannie Kim on 5/23/21. // import UIKit class ViewController: UIViewController { // MARK: - Properties let stackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.alignment = .center stackView.distribution = .fillProportionally return stackView }() let usernameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.systemFont(ofSize: 32, weight: .bold) label.text = "User" return label }() let fetchUsersButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = .blue button.tintColor = .white button.layer.cornerRadius = 20 button.setTitle("Fetch a Random User", for: .normal) button.addTarget(self, action: #selector(fetchUserButtonPressed), for: .touchUpInside) return button }() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setUpUI() } // MARK: - UI Setup private func setUpUI() { view.backgroundColor = .white view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), ]) stackView.addArrangedSubview(usernameLabel) stackView.addArrangedSubview(fetchUsersButton) NSLayoutConstraint.activate([ fetchUsersButton.heightAnchor.constraint(equalToConstant: 50), fetchUsersButton.widthAnchor.constraint(equalToConstant: 200) ]) } @objc func fetchUserButtonPressed() { guard let usersURL = URL(string: "https://jsonplaceholder.typicode.com/users") else { print("Invalid URL") return } // Prepare URL Request object var request = URLRequest(url: usersURL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let json: [String: Any] = [ "name": "Han Kim", "username": "hanlovespourovers", "email": "han@test.com", "phone": "555-5555" ] let jsonData = try? JSONSerialization.data(withJSONObject: json) request.httpBody = jsonData // Perform HTTP Request let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // Check for Error if let error = error { print("Error took place \(error)") return } // Convert HTTP Response Data to a String if let data = data, let dataString = String(data: data, encoding: .utf8) { print("Response data string:\n \(dataString)") } } task.resume() // Fetch a random user fetchUser { users, error in if let error = error { print("Error: \(error.localizedDescription)") } DispatchQueue.main.async { [weak self] in self?.usernameLabel.text = users?.randomElement()?.username } } } private func fetchUser(completion: @escaping ([User]?, Error?) -> Void) { // The URL where we'll be making our network request to guard let usersURL = URL(string: "https://jsonplaceholder.typicode.com/users") else { print("Invalid URL") return } // URLRequest uses a non-optional URL to construct the URLRequest var urlRequest = URLRequest(url: usersURL) urlRequest.httpMethod = "GET" // Start a networking task using the URLRequest we made // Most common to use the `shared` session that iOS lets us use, rather than making our own session. // If `shared` session doesn't fit your needs, look into creating a custom session let fetchUsersTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in response // Everything in this closure waits to get called until the dataTask is complete, whether or not the request was successful. // This is still technically on the background thread, since URLSession automatically runs in the background. // For any UI changes done in this closure, it must be done on the `main` thread // All 3 of the closure parameters are optionals. // If the response returns an error, no data is returned. // If the response returns data, then no error is returned. guard let data = data, error == nil else { completion(nil, error) return } do { // We use data to decode let users = try JSONDecoder().decode([User].self, from: data) completion(users, error) } catch { print("Failed to convert \(error.localizedDescription)") completion(nil, error) } } fetchUsersTask.resume() // Don't forget this. Without resume(), your dataTask won't do anything. // But with it the request starts immediately, and control gets handed over to the system – it will automatically run in the background, and won’t be destroyed even after our method ends. } private func postUser(completion: @escaping ([User]?, Error?) -> Void) { } } struct User: Codable { let name: String let username: String let email: String }
true
28f79f0478309c6e2c12eaaf79090dbd2a7c5241
Swift
universeye/tictactoe-swiftui
/tictactoe/tictactoeV2/Alerts.swift
UTF-8
786
2.921875
3
[]
no_license
// // Alerts.swift // tictactoe // // Created by Terry Kuo on 2021/5/28. // import SwiftUI struct AlertItem: Identifiable { let id = UUID() var title: Text var message: Text var buttonTitle: Text } struct AlertContext { static let humanWin = AlertItem(title: Text("You Win!"), message: Text("u beat ai"), buttonTitle: Text("Rematch")) static let computerWin = AlertItem(title: Text("You Lose!"), message: Text("AI beat u"), buttonTitle: Text("Rematch")) static let draw = AlertItem(title: Text("Draw!"), message: Text("what a battle!"), buttonTitle: Text("Rematch")) }
true
2c1a1555c149f09f090a40307cb38da67f0a3786
Swift
Coder-256/PingPoint
/PingHelper/ReadLines.swift
UTF-8
1,305
2.90625
3
[ "MIT" ]
permissive
// // ReadLines.swift // PingHelper // // Created by Jacob Greenfield on 3/8/21. // import Combine import Foundation /// Reads lines from the file handle into the given subject. This holds a weak reference to the subject, so you can /// cancel the reader by simply deallocating the subject. func readLines<S: Subject>(handle: FileHandle, subject: S) where S.Output == String?, S.Failure == Never { var buffer = Data() handle.readabilityHandler = { [weak subject] h in guard let subject = subject else { h.readabilityHandler = nil; return } let newData = h.availableData if newData.count == 0 { // We reached EOF h.readabilityHandler = nil if !buffer.isEmpty { subject.send(String(data: buffer, encoding: .utf8)) } buffer.removeAll() // just in case subject.send(completion: .finished) return } var i = 0 for j in 0..<newData.count { if newData[j] == 0x0A { // '\n' buffer.append(newData[i..<j]) subject.send(String(data: buffer, encoding: .utf8)) buffer.removeAll(keepingCapacity: true) i = j+1 } } buffer.append(newData[i..<newData.count]) } }
true
e70c39b44fd4f7ee9cba9ec2ab0c997adb131590
Swift
seamusdaniello/Silva
/Silva/Shared/SideMenuOptionView.swift
UTF-8
1,338
3.109375
3
[]
no_license
// // SideMenuOptionView.swift // Silva // // Data from the data.swift class is loaded in here for // the available options in the navigation tab. // // Created by Seamus Daniello on 4/19/21. // import SwiftUI // Used to model the side menu that will be displayed // in the navigation menu. struct SideMenuOptionView: View { @State var isActive: Bool = false let viewModel: SideMenuViewModel var body: some View { HStack(spacing: 16) { Image(systemName: viewModel.imageName) .frame(width: 24, height: 24) Text(viewModel.title) .font(.system(size: 15, weight: .semibold)) .animation(.easeOut(duration: 0.2)) .gesture(DragGesture(minimumDistance: 0) .onChanged({ _ in self.isActive = true }) .onEnded({ _ in self.isActive = false })) Spacer() } .foregroundColor(.white) .padding() } } // a preview structure for SideMenuOptionView struct SideMenuOptionView_Previews: PreviewProvider { static var previews: some View { SideMenuOptionView(viewModel: .flares) } }
true
aedf2589dd44d37f961f72c6bab04e2bf021edd9
Swift
peterIrving/UpcomingMovies
/UpcomingMovies/ui/MovieDetailView.swift
UTF-8
2,189
3.078125
3
[]
no_license
// // MovieDetailView.swift // UpcomingMovies // // Created by Peter Irving on 7/27/21. // import SwiftUI struct MovieDetailView: View { let id: Int let title:String @EnvironmentObject var detailObservable: MovieDetailObservableObject var body: some View { VStack{ MovieDetailBody(state: detailObservable.state) }.onAppear { detailObservable.loadList(id: id) }.navigationBarTitle(Text(title),displayMode: .inline ) } } struct MovieDetailBody: View { let state: MovieDetailStateEnum var body: some View { switch state { case .Failed(let message): return AnyView(Text(message)) case .Loaded(let viewModel): return AnyView( ScrollView{ VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 4){ Text(viewModel.title).font(.title) Text("In Theaters: " + viewModel.releaseDateString) } VStack(alignment: .leading, spacing: 6){ Text("Overview").font(.title2) Divider() Text(viewModel.overview).font(.body) } VStack(alignment: .leading, spacing: 6){ Text("Genre\(viewModel.genreTitles.count == 1 ? "" : "s")").font(.title2) Divider() Text(viewModel.genreTitles).font(.body) } VStack(alignment: .leading, spacing: 6){ Text("Age Recommendation").font(.title2) Divider() Text(viewModel.ageReccomendationString).font(.body) } }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).padding(16) } ) default: return AnyView(ProgressView()) } } }
true
c3676b273d2f46c97aa330e4245f35cc10b2a46d
Swift
sttbtt/CodingChallenge1
/CodingChallenge1/View Model/CellManager.swift
UTF-8
4,117
2.65625
3
[]
no_license
// // CellManager.swift // CodingChallenge1 // // Created by Scott Bennett on 6/3/21. // import Foundation import Combine import SwiftUI class CellManager: ObservableObject { @Published var cells: [[Cell]] = [[]] @Published var liveCultures: Int = 0 @Published var liveRatio: Double = 0 @Published var hours: Int = 0 @Published var isChanged: Bool = false @Published var isAnimating: Bool = false @Published var cellText: String = "" @State var largeTest: Bool = true var tempArray: [[Cell]] = [[]] var switchTest: Bool = true init() { loadCells() arrayToText() } func loadCells() { cells = largeTest ? CellData.init().largeArray : CellData.init().smallArray tempArray = cells } func activate() { hours = 1 liveRatio = 0 liveCultures = 0 isChanged = true for i in 0..<tempArray.count { for j in 0..<tempArray[0].count { if tempArray[i][j] == Cell.L { tempArray[i][j] = Cell.A } } } cells = tempArray arrayToText() } func growCells() { for _ in 0... { if !isChanged { break } isChanged = false performTest() } arrayToText() answers() } func performTest() { if switchTest { crowdingTest() } else { adjacentTest() } switchTest.toggle() if isChanged { hours += 1 } } func crowdingTest() { for i in 0..<cells.count { for j in 0..<cells[0].count { if cells[i][j] == Cell.D { continue } if checkCount(i: i, j: j) >= 4 && tempArray[i][j] != Cell.L { tempArray[i][j] = Cell.L isChanged = true } } } cells = tempArray } func adjacentTest() { for i in 0..<cells.count { for j in 0..<cells[0].count { if cells[i][j] == Cell.D { continue } if checkCount(i: i, j: j) == 0 && tempArray[i][j] != Cell.A { tempArray[i][j] = Cell.A isChanged = true } } } cells = tempArray } func arrayToText() { var tempText: String = "" for i in 0..<cells.count { for j in 0..<cells[0].count { tempText = tempText + cells[i][j].rawValue } tempText = tempText + "\n" } cellText = tempText } func checkCount(i: Int, j: Int) -> Int { var testArray: [Cell] = [] testArray.append(i == 0 || j == 0 ? Cell.D : cells[i - 1][j - 1]) testArray.append(j == 0 ? Cell.D : cells[i][j - 1]) testArray.append(i == (cells.count - 1) || j == 0 ? Cell.D : cells[i + 1][j - 1]) testArray.append(i == 0 ? Cell.D : cells[i - 1][j]) testArray.append(i == (cells.count - 1) ? Cell.D : cells[i + 1] [j]) testArray.append(i == 0 || j == (cells[0].count - 1) ? Cell.D : cells[i - 1][j + 1]) testArray.append(j == (cells[0].count - 1) ? Cell.D : cells[i][j + 1]) testArray.append(i == (cells.count - 1) || j == (cells[0].count - 1) ? Cell.D : cells[i + 1][j + 1]) return testArray.filter{ $0 == Cell.A }.count } func answers() { var livableArray: [Cell] = [] for i in 0..<cells.count { for j in 0..<cells[0].count { if cells[i][j] == Cell.L || cells[i][j] == Cell.A { livableArray.append(cells[i][j]) } } } liveCultures = livableArray.filter{ $0 == Cell.L }.count liveRatio = (Double(liveCultures) / Double(livableArray.count)) * 100 } }
true
975ac6981a33d5a6a06cd94b92beaac750b58423
Swift
hellochenms/m4-scroll-observer
/m4-scroll-observer/double-direction-progress/M42DirectionProgressScrollConverter.swift
UTF-8
1,177
2.625
3
[ "MIT" ]
permissive
// // M4Scroll2DirectionProgressConverter.swift // m4-scroll-observer // // Created by Chen,Meisong on 2019/7/12. // Copyright © 2019 xyz.chenms. All rights reserved. // import UIKit class M42DirectionProgressScrollConverter: NSObject { public var progress0OffsetX: CGFloat = 0 public var scrollUpProgress1OffsetX: CGFloat = 0 public var scrollDownProgress1OffsetX: CGFloat = 0 public func scrollUpProgress(_ scrollView: UIScrollView) -> CGFloat? { guard scrollView.contentOffset.y > progress0OffsetX else { return nil } var progress = (scrollView.contentOffset.y - progress0OffsetX) / (scrollUpProgress1OffsetX - progress0OffsetX) progress = min(max(0, progress), 1) return progress } public func scrollDownProgress(_ scrollView: UIScrollView) -> CGFloat? { guard scrollView.contentOffset.y <= progress0OffsetX else { return nil } var progress = (scrollView.contentOffset.y - progress0OffsetX) / (scrollDownProgress1OffsetX - progress0OffsetX) progress = min(max(0, progress), 1) return progress } }
true
d3b784d6c69c69ec5ab19461807c2422041308bd
Swift
richiehollins/CarouselDemo
/CarouselDemo/IntroViewController.swift
UTF-8
6,927
2.609375
3
[]
no_license
// // IntroViewController.swift // CarouselDemo // // Created by Hollins, Richie on 4/7/16. // Copyright © 2016 Hollins, Richie. All rights reserved. // import UIKit class IntroViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var introImage: UIImageView! @IBOutlet weak var tile1: UIImageView! @IBOutlet weak var tile2: UIImageView! @IBOutlet weak var tile3: UIImageView! @IBOutlet weak var tile4: UIImageView! @IBOutlet weak var tile5: UIImageView! @IBOutlet weak var tile6: UIImageView! override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self scrollView.contentSize = introImage.image!.size // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidScroll(scrollView: UIScrollView) { // called as the user scrolls // big tile 1 let tile1Offset = Float(scrollView.contentOffset.y) let tile1x = convertValue(CGFloat(tile1Offset), r1Min: 0, r1Max: 568, r2Min: -50, r2Max: 0) let tile1y = convertValue(CGFloat(tile1Offset), r1Min: 0, r1Max: 568, r2Min: -320, r2Max: 0) let tile1Rotation = convertValue(CGFloat(tile1Offset), r1Min: 0, r1Max: 568, r2Min: -10, r2Max: 0) tile1.transform = CGAffineTransformMakeTranslation(CGFloat(tile1x),CGFloat(tile1y)) tile1.transform = CGAffineTransformRotate(tile1.transform, CGFloat(Double(tile1Rotation) * M_PI / 180)) // tile 2 let tile2Offset = Float(scrollView.contentOffset.y) let tile2x = convertValue(CGFloat(tile2Offset), r1Min: 0, r1Max: 568, r2Min: -40, r2Max: 0) let tile2y = convertValue(CGFloat(tile2Offset), r1Min: 0, r1Max: 568, r2Min: -330, r2Max: 0) let tile2Scale = convertValue(CGFloat(tile2Offset), r1Min: 0, r1Max: 568, r2Min: 2, r2Max: 1) let tile2Rotation = convertValue(CGFloat(tile2Offset), r1Min: 0, r1Max: 568, r2Min: 4, r2Max: 0) tile2.transform = CGAffineTransformMakeTranslation(CGFloat(tile2x),CGFloat(tile2y)) tile2.transform = CGAffineTransformRotate(tile2.transform, CGFloat(Double(tile2Rotation) * M_PI / 180)) tile2.transform = CGAffineTransformScale(tile2.transform, CGFloat(tile2Scale), CGFloat(tile2Scale)) // tile 3 let tile3Offset = Float(scrollView.contentOffset.y) let tile3x = convertValue(CGFloat(tile3Offset), r1Min: 0, r1Max: 568, r2Min: 10, r2Max: 0) let tile3y = convertValue(CGFloat(tile3Offset), r1Min: 0, r1Max: 568, r2Min: -340, r2Max: 0) let tile3Scale = convertValue(CGFloat(tile3Offset), r1Min: 0, r1Max: 568, r2Min: 1.8, r2Max: 1) let tile3Rotation = convertValue(CGFloat(tile3Offset), r1Min: 0, r1Max: 568, r2Min: 8, r2Max: 0) tile3.transform = CGAffineTransformMakeTranslation(CGFloat(tile3x),CGFloat(tile3y)) tile3.transform = CGAffineTransformRotate(tile3.transform, CGFloat(Double(tile3Rotation) * M_PI / 180)) tile3.transform = CGAffineTransformScale(tile3.transform, CGFloat(tile3Scale), CGFloat(tile3Scale)) // tile 4 let tile4Offset = Float(scrollView.contentOffset.y) let tile4x = convertValue(CGFloat(tile4Offset), r1Min: 0, r1Max: 568, r2Min: -50, r2Max: 0) let tile4y = convertValue(CGFloat(tile4Offset), r1Min: 0, r1Max: 568, r2Min: -480, r2Max: 0) let tile4Scale = convertValue(CGFloat(tile4Offset), r1Min: 0, r1Max: 568, r2Min: 2, r2Max: 1) let tile4Rotation = convertValue(CGFloat(tile4Offset), r1Min: 0, r1Max: 568, r2Min: -6, r2Max: 0) tile4.transform = CGAffineTransformMakeTranslation(CGFloat(tile4x),CGFloat(tile4y)) tile4.transform = CGAffineTransformRotate(tile4.transform, CGFloat(Double(tile4Rotation) * M_PI / 180)) tile4.transform = CGAffineTransformScale(tile4.transform, CGFloat(tile4Scale), CGFloat(tile4Scale)) // tile 5 let tile5Offset = Float(scrollView.contentOffset.y) let tile5x = convertValue(CGFloat(tile5Offset), r1Min: 0, r1Max: 568, r2Min: 0, r2Max: 0) let tile5y = convertValue(CGFloat(tile5Offset), r1Min: 0, r1Max: 568, r2Min: -440, r2Max: 0) let tile5Scale = convertValue(CGFloat(tile5Offset), r1Min: 0, r1Max: 568, r2Min: 1.6, r2Max: 1) let tile5Rotation = convertValue(CGFloat(tile5Offset), r1Min: 0, r1Max: 568, r2Min: -12, r2Max: 0) tile5.transform = CGAffineTransformMakeTranslation(CGFloat(tile5x),CGFloat(tile5y)) tile5.transform = CGAffineTransformRotate(tile5.transform, CGFloat(Double(tile5Rotation) * M_PI / 180)) tile5.transform = CGAffineTransformScale(tile5.transform, CGFloat(tile5Scale), CGFloat(tile5Scale)) // tile 6 let tile6Offset = Float(scrollView.contentOffset.y) let tile6x = convertValue(CGFloat(tile6Offset), r1Min: 0, r1Max: 568, r2Min: 10, r2Max: 0) let tile6y = convertValue(CGFloat(tile6Offset), r1Min: 0, r1Max: 568, r2Min: -490, r2Max: 0) let tile6Scale = convertValue(CGFloat(tile6Offset), r1Min: 0, r1Max: 568, r2Min: 2, r2Max: 1) let tile6Rotation = convertValue(CGFloat(tile6Offset), r1Min: 0, r1Max: 568, r2Min: 7, r2Max: 0) tile6.transform = CGAffineTransformMakeTranslation(CGFloat(tile6x),CGFloat(tile6y)) tile6.transform = CGAffineTransformRotate(tile6.transform, CGFloat(Double(tile6Rotation) * M_PI / 180)) tile6.transform = CGAffineTransformScale(tile6.transform, CGFloat(tile6Scale), CGFloat(tile6Scale)) } func scrollViewWillBeginDragging(scrollView: UIScrollView) { } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { // This method is called right as the user lifts their finger } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // This method is called when the scrollview finally stops scrolling. } /* resets scroll view to top before page appears. override func viewWillAppear(animated: Bool) { self.scrollView.contentOffset = CGPointZero }*/ /* // 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. } */ }
true
beca82a369b134c8b8e7e54fdca624c4e5e6aa73
Swift
roothybrid7/DesignableKit
/Sources/DesignableKit/UILayerConfifurable.swift
UTF-8
1,180
2.8125
3
[ "MIT" ]
permissive
// // UILayerConfifurable.swift // DesignableKit // // Created by SATOSHI OHKI on 2017/01/11. // // #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #endif @available(iOS 8.0, tvOS 9.0, watchOS 2.0, *) /// Defines a blueprint of properties for CALayer configuration. public protocol UILayerConfigurable { var layerDrawsAsynchronously: Bool { get set } /** The cornerRadius of CALayer by an extension. For example, `layerCornerRaidus` will be implemented to: extension UIView: LayerConfigurable { var layerCornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } } */ var layerCornerRadius: CGFloat { get set } var layerBorderWidth: CGFloat { get set } var layerBorderUIColor: UIColor? { get set } var layerBackgroundUIColor: UIColor? { get set } var layerShouldRasterize: Bool { get set } var layerShadowUIColor: UIColor? { get set } var layerShadowOpacity: Float { get set } var layerShadowOffset: CGSize { get set } var layerShadowRadius: CGFloat { get set } }
true
b7d03b7b230b6896540c7812eb7eb83835c0a046
Swift
ple-d/iTinder
/ITinder/Presentation Layer/ResetPassword/ResetPasswordController.swift
UTF-8
1,294
3.09375
3
[]
no_license
import UIKit protocol ResetPasswordViewProtocol: AnyObject { func showWarning(title: String, text: String) func hideWarning() } class ResetPasswordController: UIViewController, ResetPasswordViewProtocol { var presenter: ResetPasswordPresenterProtocol? override func loadView() { view = ResetPasswordView() } override func viewDidLoad() { super.viewDidLoad() let view = view as? ResetPasswordView view?.resetButton.addTarget(self, action: #selector(resetButtonTouched), for: .touchUpInside) } // Метод вызывается при нажатии на кнопку "Войти" @objc private func resetButtonTouched() { let view = view as? ResetPasswordView guard let email = view?.emailTextField.text else { return } presenter?.reset(email: email) } // Метод для показа предупреждения func showWarning(title: String, text: String) { let view = view as? ResetPasswordView view?.warningView.show(title: title, text: text) } // Метод для скрытия предупреждения func hideWarning() { let view = view as? ResetPasswordView view?.warningView.hide() {} } }
true
404f9fbd4e73adcfa81b6d6a4b6e29ef04a2abe3
Swift
sungyoungPark/baekjoon_solution
/sol13.swift
UTF-8
748
3.6875
4
[]
no_license
import Foundation let n = Int(readLine()!)! var arr = [[Int]](repeating: [], count: n) for i in 1...n{ let str = readLine()?.split(separator: " ") let a = Int(String(str![0]))! let b = Int(String(str![1]))! arr[i-1] = [a,b] } arr = arr.sorted(by: { (a1, b1) -> Bool in if(a1[0]>b1[0]){ return false } else if (a1[0]==b1[0]){ if(a1[1] < b1[1]){ return true } else{ return false } } else{ return true } } ) //print(arr) var temp = [0,Int.max] var count = 1 for a in arr{ if(a[0] >= temp[0] && a[1] < temp[1]){ temp = a } else if temp[1] <= a[0]{ temp = a count += 1 } } print(count)
true
153332a63b5c3ac11132112caedb0603e86653df
Swift
as1k/ios-dev
/Contacts/Contacts/Models/ContactModel.swift
UTF-8
853
3
3
[]
no_license
// // ContactModel.swift // Contacts // // Created by Асыланбек Нурмухамбет on 2/12/21. // Copyright © 2021 kbtu.edu.as1k.kz. All rights reserved. // import Foundation import UIKit struct ContactModel{ private var contacts = [ Contact.init("Vasya Pupkin", "+77089871231", UIImage.init(named: "female")!), Contact.init("Vladimir Putin", "95999999999", UIImage.init(named: "male")!), Contact.init("Palenshe Pugenshiev", "123123123", UIImage.init(named: "female")!) ] private var genders = ["male", "female"] func getGenders() -> Array<String> { return genders } func getContacts() -> Array<Contact>{ return contacts } mutating func addNewContact(_ contact: Contact){ contacts.append(contact) } mutating func deleteContact(_ index: Int){ contacts.remove(at: index) } }
true
fc12b8047e79a27dd27385e111144ae997f8a564
Swift
ThePowerOfSwift/NacaoEspirita
/NacaoEspirita/modules/login-module/login-main-module/interactor/LoginInteractor.swift
UTF-8
1,357
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // LoginInteractor.swift // NacaoEspirita // // Created by Felippe Matos Francoski on 10/15/19. // Copyright © 2019 Felippe Matos Francoski. All rights reserved. // import Foundation import Firebase import FBSDKLoginKit class LoginInteractor: LoginPresenterToInteractorProtocol { var presenter: LoginInteractorToPresenterProtocol? func makeFacebookLogin(view: UIViewController) { let fbLoginManager = LoginManager() fbLoginManager.logIn(permissions: ["public_profile", "email"], from: view) { (result, error) in if let error = error { print("Failed to login: \(error.localizedDescription)") return } guard let accessToken = AccessToken.current else { print("Failed to get access token") return } let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString) // Perform login by calling Firebase APIs Auth.auth().signIn(with: credential, completion: { (user, error) in if let error = error { self.presenter?.sendError(message: error.localizedDescription) return } self.presenter?.successFacebookLogin() }) } } }
true
2072a90a7a7da8c9712728ffd6df69b593de6848
Swift
shota1000000/Kenko
/kenko/CollectionViewController.swift
UTF-8
2,777
2.546875
3
[]
no_license
// // CollectionViewController.swift // kenko // // Created by 葛西 翔太 on 2021/01/30. // Copyright © 2021 葛西 翔太. All rights reserved. // import UIKit import SDWebImage class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { let image_max = 47 var commentArray = [String]() var imageURLArray = [String]() var recipeTypeArray = [String]() var recordedDateArray = [String]() var comment = "" var image = "" var recipeType = "" var recordedDate = "" override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 200, height: 200) layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView.collectionViewLayout = layout } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return image_max } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.sd_internalSetImage(with: URL(string: imageURLArray[indexPath.row]), placeholderImage: UIImage(named: "noimage"), options: .continueInBackground, context: nil, setImageBlock: nil, progress: nil, completed: nil) let imageView = cell.contentView.viewWithTag(1) as! UIImageView imageView.sd_setImage(with: URL(string: imageURLArray[indexPath.row]), placeholderImage: UIImage(named: "noimage"), options: .continueInBackground, context: nil, progress: nil, completed: nil) return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { comment = commentArray[indexPath.row] image = imageURLArray[indexPath.row] recipeType = recipeTypeArray[indexPath.row] recordedDate = recordedDateArray[indexPath.row] performSegue(withIdentifier: "moveToPresentation", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "moveToPresentation"{ let presentationVC = segue.destination as! PresentationViewController presentationVC.comment = self.comment presentationVC.image = self.image presentationVC.recipeType = self.recipeType presentationVC.recordedDate = self.recordedDate } } }
true
bc76a68bba802c84dc56e4f440b78332864587d3
Swift
lakshaychhabra/BenefitIOSApplication
/Benefit/Benefit/Controller/Workout Screens/WorkoutsSectionViewController.swift
UTF-8
3,813
2.515625
3
[ "Apache-2.0" ]
permissive
// // WorkoutsSectionViewController.swift // Benefit // // Created by Delta One on 24/01/18. // Copyright © 2018 IOSD. All rights reserved. // import UIKit class WorkoutsSectionViewController: UIViewController { var isMyWorkoutsLocked = false let imageList = ["fw1.png", "fw2.png", "fw3.png", "fw4.png"] let workoutList = ["PremiumFeatureCell", "SecondaryCell", "CardViewCell"] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() //setNav() for workout in workoutList { registerCellNib(named: workout, with: tableView) } tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 80 tableView.backgroundColor = UIColor.clear let logo = UIImage(named: "benefit_logo") let imageView = UIImageView(image:logo) imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false self.navigationItem.titleView = imageView } } extension WorkoutsSectionViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { if isMyWorkoutsLocked { performSegue(withIdentifier: "goToMyWorkoutsLocked", sender: self) } else { performSegue(withIdentifier: "goToMyWorkouts", sender: self) } } else if indexPath.section == 2 { performSegue(withIdentifier: "goToHIIT", sender: self) } } } extension UIViewController { func registerCellNib(named name: String, with tableView: UITableView) { let cellNib = UINib(nibName: name, bundle: nil) tableView.register(cellNib, forCellReuseIdentifier: name) } } extension WorkoutsSectionViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 15 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = UIColor(hex: "EEEEEE") return headerView } func numberOfSections(in tableView: UITableView) -> Int { return workoutList.count - 1 + imageList.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "PremiumFeatureCell", for: indexPath) as! PremiumFeatureCell cell.leftLogoImageView.image = UIImage(named: "ic_my_workout_24dp.png") cell.lockImageView.image = UIImage(named: "ic_locked_24dp.png") cell.titleLabel.text = "MY WORKOUTS" return cell } else if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "SecondaryCell", for: indexPath) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "CardViewCell", for: indexPath) as! CardViewCell cell.cardViewImage.image = UIImage(named: imageList[indexPath.section - 2]) return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } }
true
36a493ab7e22d38293c1e7ec1e5412025425698a
Swift
camgrigo/Cardsneak
/Shared/Player/AIPlayer.swift
UTF-8
2,345
3.140625
3
[]
no_license
// // AIPlayer.swift // Cardsneak // // Created by Cameron Grigoriadis on 2/24/21. // import Foundation class AIPlayer: Player { let name: String let id: Int var cards = CardStack() init(name: String, id: Int) { self.name = name self.id = id } private let caution = (0...8).randomElement()! func getPlay(rank: PlayingCard.Rank, handler: @escaping ([PlayingCard]) -> Void) { var discardStack = CardStack() let matches = cards.popAll { $0.rank == rank } discardStack .append( contentsOf: matches.isEmpty ? getSneakCards(max: .random(in: 1...2)) : matches ) // If not cautious, add an extra card if !cards.isEmpty && caution < 5 && discardStack.count <= 2 { discardStack.append(cards.popRandomElement()!) } let deadline: DispatchTime = .now() + [2, 3, 4].randomElement()! DispatchQueue.main.asyncAfter(deadline: deadline) { precondition(Set(discardStack).isDisjoint(with: self.cards)) handler(discardStack) } } private func getSneakCards(max: Int) -> [PlayingCard] { (0..<max) .map { _ in self.cards.popRandomElement() } .compactMap { $0 } } func shouldChallenge(player: (playerId: Int, cardCount: Int), rank: PlayingCard.Rank, handler: @escaping (Bool) -> Void) { // Opinion of player (Player did/did not challenge him before) // Threatened by player (Card count) // High card count // Good/Bad expectations for next turn (I have all the aces/I don't have any aces) let confidenceLevel = (cardCountConfidenceScore() + 5 // nextTurnProjection(nextRank: <#T##PlayingCard.Rank#>) ) / 2 DispatchQueue.main.asyncAfter(deadline: .now() + [0.5, 0.75, 1].randomElement()!) { handler(confidenceLevel >= self.caution) } } private func cardCountConfidenceScore() -> Int { Int((max(0, 20 - cards.count) / 20) * 10) } private func nextTurnProjection(nextRank: PlayingCard.Rank) -> Int { Int((cards.filter { $0.rank == nextRank }.count / 4) * 10) } }
true
976d147fb61587909da89a6d5aa200f8ac251acc
Swift
chiafishh/Activities
/Activities/DetailViewController.swift
UTF-8
5,041
2.65625
3
[]
no_license
// // DetailViewController.swift // Activities // // Created by User02 on 2019/1/14. // Copyright © 2019 Chiafishh. All rights reserved. // import UIKit import AVFoundation class DetailViewController: UIViewController { var act1: Act1? var showInfo0: ShowInfo0? var web = "0" var speakdetail:String = "0" var speaking = 0 //按說話按鈕 按一下變0 再按一下變1 @IBOutlet var actImg2: UIImageView! @IBOutlet var actImg3: UIImageView! @IBOutlet var titleLabel2: UILabel! @IBOutlet var detail: UITextView! @IBOutlet var scrollV: UIScrollView! @IBOutlet var showInfoTime: UILabel! @IBOutlet var showInfoLocationTextField: UITextView! @IBOutlet var priceLabel: UILabel! @IBOutlet var BuyTicketButton: UIButton! @IBOutlet var speak: UIButton! var speechUtterance = AVSpeechUtterance() let synthesizer = AVSpeechSynthesizer() override func viewDidLoad() { super.viewDidLoad() speaking = 0 let noInfo = "無資訊" if let act1 = act1{ navigationItem.title = "詳細資訊" titleLabel2.text = act1.title if act1.showInfo?.count != 0{ showInfoTime.text = act1.showInfo![0].time! showInfoLocationTextField.text = act1.showInfo![0].locationName! + "\n" + act1.showInfo![0].location! //顯示價格 if act1.showInfo![0].price! != ""{ priceLabel.text = act1.showInfo![0].price } else{ priceLabel.text = "免費" } } else{ showInfoTime.text = noInfo showInfoLocationTextField.text = noInfo priceLabel.text = noInfo } detail.text = act1.descriptionFilterHtml speakdetail = detail.text//給朗讀詳細內容的功能使用 //若有買票網址,按鈕顯示“我要索票“,顏色呈咖啡色,按鈕可以使用;若無,按鈕顯示“無法索票“,顏色呈灰色,按鈕不可使用 BuyTicketButton.setTitle("無法索票",for: .normal) BuyTicketButton.isEnabled = false BuyTicketButton.setTitleColor(UIColor(red:0.66, green:0.66, blue:0.66, alpha:1.0), for: .normal) if act1.webSales != ""{ BuyTicketButton.isEnabled = true BuyTicketButton.setTitle("我要索票",for: .normal) BuyTicketButton.setTitleColor(UIColor(red:0.55, green:0.33, blue:0.12, alpha:1.0), for: .normal) web = act1.webSales! } let task = URLSession.shared.dataTask(with: act1.imageUrl) { (data, response , error) in if let data = data { DispatchQueue.main.async { self.actImg2.image = UIImage(data: data)//上方小圖 self.actImg3.image = UIImage(data: data)//底部大圖 } } } task.resume() } } //一進來這個view,就顯示scroll bar,讓使用者知道可以往下滑 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.detail.flashScrollIndicators() self.scrollV.flashScrollIndicators() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) synthesizer.stopSpeaking(at: .immediate)//可以點選按鈕請手機朗讀詳細文字,當離開此頁就閉嘴 print("viewDidDisappear") } //點選“我要索票”按鈕去買票網站 @IBAction func BuyTicket(_ sender: AnyObject) { if let url = URL(string: web) { UIApplication.shared.open(url, options: [:]) } } //點選說話按鈕請手機朗讀詳細文字,第一次點選會朗讀,再次點選會閉嘴,再次點選會朗讀 @IBAction func speakPressed(_ sender: Any) { speechUtterance = AVSpeechUtterance(string: speakdetail) print(speakdetail) speechUtterance.voice = AVSpeechSynthesisVoice(language: "zh-TW") synthesizer.speak(speechUtterance)//朗讀 if speaking == 0 { speaking = 1 print("speak") } else { speaking = 0 print("stop") synthesizer.stopSpeaking(at: .immediate)//閉嘴 } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
a0c770ea1daccb16c8b335204aad342f4cbe9fa6
Swift
theodinspire/EgredientTraveler
/EgredientTraveler/Array.swift
UTF-8
319
2.515625
3
[]
no_license
// // Array.swift // EgredientTraveler // // Created by Eric Cormack on 5/28/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import Foundation extension Array { func yield<T>(output: inout T, op: (_ a: inout T, _ b: Element) -> Void ) { for element in self { op(&output, element) } } }
true
af0b58462b15937eecc6c4f5cb889b712c59eec2
Swift
YahiaRagae/WimduSearch
/WimduSearch/WimduSearch/DataAccessController/DataFetchers/SearchDataFetcher.swift
UTF-8
1,492
2.546875
3
[]
no_license
// // SearchDataFetcher.swift // WimduSearch // // Created by Yahia Mahrous on 6/22/16. // Copyright © 2016 Yahia Mahrous. All rights reserved. // import Foundation import SwiftyJSON import Alamofire class SearchDataFetcher: BaseDataFetcher { let URL_SEARCH_SUGGESTIONS : String = "URL_SEARCH_SUGGESTIONS" let SEARCH_WORD_PARAM : String = "q" func search(searchWord : String , withCompletion completion:(items : NSMutableArray, status : Bool )->Void) { let link = getLink(URL_SEARCH_SUGGESTIONS) getRequestWithJsonReponse(link: link, andSearchKewWord: searchWord) { (response, status) in let items:NSMutableArray = self.parseSugestions(response: response) completion(items: items , status: status) } } // MARK: Parsers func parseSugestions(response response: Response<AnyObject, NSError>) -> NSMutableArray{ let items:NSMutableArray = NSMutableArray(); if(response.result.value != nil ){ let result = JSON(response.result.value!) if(result["search_suggestions"].count > 0){ let resultArray = result["search_suggestions"]; for i in 0 ..< resultArray.count{ let item:SugestionGroup = SugestionGroup(json: resultArray[i] ) items.addObject(item) } } } return items; } }
true
9f4eccff1d593b6734591be8f1ca12c86cf9ace8
Swift
ostapyshyn/Practice-projects
/SwiftBook/HW2/HW2/SettingsViewController.swift
UTF-8
5,789
2.65625
3
[]
no_license
// // ViewController.swift // HW2 // // Created by Volodymyr Ostapyshyn on 26.08.2020. // Copyright © 2020 Volodymyr Ostapyshyn. All rights reserved. // import UIKit protocol ColorDelegate { func setColor(_ color: UIColor, text: String) } class SettingsViewController: UIViewController, UITextFieldDelegate { var delegate: ColorDelegate? var colorFromMainVC: UIColor! @IBOutlet var colorView: UIView! @IBOutlet var redSlider: UISlider! @IBOutlet var greenSlider: UISlider! @IBOutlet var blueSlider: UISlider! @IBOutlet var redLabel: UILabel! @IBOutlet var greenLabel: UILabel! @IBOutlet var blueLabel: UILabel! @IBOutlet var redTF: UITextField! @IBOutlet var greenTF: UITextField! @IBOutlet var blueTF: UITextField! override func viewDidLoad() { super.viewDidLoad() colorView.layer.cornerRadius = 10 configureSliders() configureLabels() configureTexFields() updateColor() colorView.backgroundColor = colorFromMainVC } func configureSliders() { redSlider.minimumValue = 0 redSlider.maximumValue = 1 redSlider.value = 1 redSlider.minimumTrackTintColor = .red redSlider.maximumTrackTintColor = .gray greenSlider.minimumValue = 0 greenSlider.maximumValue = 1 greenSlider.value = 1 greenSlider.minimumTrackTintColor = .green greenSlider.maximumTrackTintColor = .gray blueSlider.minimumValue = 0 blueSlider.maximumValue = 1 blueSlider.value = 1 blueSlider.minimumTrackTintColor = .blue blueSlider.maximumTrackTintColor = .gray } func configureLabels() { redLabel.text = String(redSlider.value) greenLabel.text = String(greenSlider.value) blueLabel.text = String(blueSlider.value) } func configureTexFields() { let toolBar = UIToolbar() toolBar.sizeToFit() let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneClicked)) toolBar.setItems([flexibleSpace, doneButton], animated: true) redTF.text = String(redSlider.value) redTF.keyboardType = .decimalPad redTF.borderStyle = .roundedRect redTF.contentVerticalAlignment = .center redTF.textAlignment = .center redTF.delegate = self redTF.inputAccessoryView = toolBar greenTF.text = String(greenSlider.value) greenTF.keyboardType = .decimalPad greenTF.borderStyle = .roundedRect greenTF.contentVerticalAlignment = .center greenTF.textAlignment = .center greenTF.delegate = self greenTF.inputAccessoryView = toolBar blueTF.text = String(blueSlider.value) blueTF.keyboardType = .decimalPad blueTF.borderStyle = .roundedRect blueTF.contentVerticalAlignment = .center blueTF.textAlignment = .center blueTF.delegate = self blueTF.inputAccessoryView = toolBar } @objc func doneClicked() { setSliderAndLabels() view.endEditing(true) } @IBAction func redSliderAction(_ sender: UISlider) { let number = Double(redSlider.value) let value = String(format: "%.2f", number) updateColor() redLabel.text = value redTF.text = value } @IBAction func greenSliderAction(_ sender: UISlider) { let number = Double(greenSlider.value) let value = String(format: "%.2f", number) updateColor() greenLabel.text = value greenTF.text = value } @IBAction func blueSliderAction(_ sender: UISlider) { let number = Double(blueSlider.value) let value = String(format: "%.2f", number) updateColor() blueLabel.text = value blueTF.text = value } @IBAction func donePressed() { let color = colorView.backgroundColor delegate?.setColor(color ?? .red, text: "Hello") print("hi") dismiss(animated: true, completion: nil) // //print(colorView.backgroundColor!) } func updateColor() { let red = CGFloat(redSlider.value) let green = CGFloat(greenSlider.value) let blue = CGFloat(blueSlider.value) let color = UIColor(red: red, green: green,blue: blue, alpha: 1) colorView.backgroundColor = color } func setSliderAndLabels() { if let number = redTF.text, let value = Float(number) { redSlider.value = value redLabel.text = number } if let number = greenTF.text, let value = Float(number) { greenSlider.value = value greenLabel.text = number } if let number = blueTF.text, let value = Float(number) { blueSlider.value = value blueLabel.text = number } updateColor() } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { setSliderAndLabels() return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) view.endEditing(true) } }
true
fb2bfc2af5440f60e68d2fd25682022164d59bab
Swift
jsamboni/PlasticTestPublic
/PlasticTest/Scenes/DisplaySpinningSquare/DisplaySpinningSquareInteractor.swift
UTF-8
1,156
2.671875
3
[]
no_license
// // DisplaySpinningSquareInteractor.swift // PlasticTest // // Created by Juan Carlos Samboni Ramirez on 3/6/19. // Copyright (c) 2019 Juan Carlos Samboni Ramirez. All rights reserved. // import UIKit protocol DisplaySpinningSquareBusinessLogic { func fetchTime() } class DisplaySpinningSquareInteractor: DisplaySpinningSquareBusinessLogic { var presenter: DisplaySpinningSquarePresentationLogic? var worker: DisplaySpinningSquareWorker = DisplaySpinningSquareWorker(service: NetworkService()) private var fetchTimer = DispatchSource.makeTimerSource() // MARK: fetchTime func fetchTime() { fetchTimer.schedule(deadline: .now(), repeating: .milliseconds(100)) fetchTimer.setEventHandler(handler: { [weak self] in self?.worker.fetchTime(completionHandler: { [weak self] (rawTime) in let response = DisplaySpinningSquare.FetchTime.Response(rawTime: rawTime ?? "") self?.presenter?.presentTime(response: response) }) }) fetchTimer.resume() } deinit { fetchTimer.setEventHandler {} fetchTimer.cancel() fetchTimer.resume() } }
true
c7a0ff59e70b5994e01bd413fc902931e3b9e9c9
Swift
demianjun/JOINUS
/JOINUS/JOINUS/ViewControllers/OnboardingViewController/OnboardingModel/OnboardingModel.swift
UTF-8
681
2.65625
3
[]
no_license
// // OnboardingModel.swift // JOINUS // // Created by Demian on 2021/08/31. // import Foundation class OnboardingModel { static let shared = OnboardingModel() enum myGame: String { case lol, suddenAttack, overwatch, battleGround, mapleStory } enum myTier: String { case iron = "iron", bronze = "bronze", silver = "silver", gold = "gold", platinum = "platinum", diamond = "diamond", master = "master", challenger = "challenger" } var ages: [String] { var temp = [String]() for i in 20...70 { temp.append(String(i).appending("세")) } return temp } }
true
26752da4bd21efabed2b70a98771493b486eb0dd
Swift
Luis-X/DayDay-Swift
/DayDaySwift/UI/CustomeTableView/View/CustomTableViewCell.swift
UTF-8
4,487
2.578125
3
[]
no_license
// // CustomTableViewCell.swift // DayDaySwift // // Created by LuisX on 16/3/31. // Copyright © 2016年 apple. All rights reserved. // import UIKit //协议 protocol CustomTableViewCellDelegate { func rowsForChatTable(tableviewCell cell:UITableViewCell) -> Int //返回对话记录中的全部行数 func chatTableView(tableviewCell cell:UITableViewCell, dataForRow row:Int) -> MessageItem //返回某一行的内容 //外部形参 dataForRow } class CustomTableViewCell: UITableViewCell { var customView:UIView! var bubbleImage:UIImageView! var avatarImage:UIImageView! var msgItem:MessageItem! var myDelegate:CustomTableViewCellDelegate? //设置代理人 //重写初始化 init(data:MessageItem, reuseIdentifier cellId:String){ super.init(style: .default, reuseIdentifier: cellId) self.msgItem = data self.rebuildUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //重建视图 func rebuildUserInterface(){ self.selectionStyle = .none if (self.bubbleImage == nil) { self.bubbleImage = UIImageView() self.addSubview(self.bubbleImage) } let type = self.msgItem.mType let width = self.msgItem.view.frame.size.width let height = self.msgItem.view.frame.size.height var x = (type == ChatType.someone) ? 0 : self.frame.size.width - width - self.msgItem.insets.left - self.msgItem.insets.right var y:CGFloat = 0 //显示头像 if (self.msgItem.logo != "") { let logo = self.msgItem.logo self.avatarImage = UIImageView(image: UIImage(named: (logo != "" ? logo! : "1.jpg"))) self.avatarImage.layer.cornerRadius = 9.0 self.avatarImage.layer.masksToBounds = true self.avatarImage.layer.borderColor = UIColor(white: 0.0, alpha: 0.2).cgColor self.avatarImage.layer.borderWidth = 1.0 //别人头像,在左边,我的头像在右边 let avatarX = (type == ChatType.someone) ? 2 : self.frame.size.width - 52 let avatarY = height //头像居于消息底部 self.avatarImage.frame = CGRect(x: avatarX, y: avatarY, width: 50, height: 50) self.addSubview(self.avatarImage) let delta = self.frame.size.height - (self.msgItem.insets.top + self.msgItem.insets.bottom + self.msgItem.view.frame.size.height) if (delta > 0) { y = delta } if (type == ChatType.someone) { x += 54 } if (type == ChatType.mine) { x -= 54 } self.customView = self.msgItem.view self.customView.frame = CGRect(x: x + self.msgItem.insets.left, y: y + self.msgItem.insets.top, width: width, height: height) self.addSubview(self.customView) //如果是别人的消息,在左边,如果是我输入的消息,在右边 if (type == .someone) { //self.bubbleImage.image = UIImage(named: ("1.jpg"))?.stretchableImageWithLeftCapWidth(21, topCapHeight: 14) }else{ //self.bubbleImage.image = UIImage(named: "2.jpg")?.stretchableImageWithLeftCapWidth(15, topCapHeight: 14) } self.bubbleImage.frame = CGRect(x: x, y: y, width: width + self.msgItem.insets.left + self.msgItem.insets.right, height: height + self.msgItem.insets.top + self.msgItem.insets.bottom) //轻拍手势(使用代理) self.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.useMyDelegateFunc))) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } //代理方法 @objc func useMyDelegateFunc() { self.myDelegate?.rowsForChatTable(tableviewCell: self) self.myDelegate?.chatTableView(tableviewCell: self, dataForRow: 1) } }
true
3fe433a01a545d4bcc64bd41f20e7b42225bd0cd
Swift
risrael-1/Projet-annuel
/IosProject/IosProject/Service/APIResponseFactory.swift
UTF-8
552
2.65625
3
[]
no_license
// // APIResponseFactory.swift // IosProject // // Created by Eduard Serban on 25/07/2021. // import Foundation class APIResponseFactory { public static func responseFromElement(_ dict: [String: Any]) -> APIResponse? { guard let success = dict["success"] as? Bool, let requestCode = dict["requestCode"] as? Int else { return nil } let errorMessage = dict["error"] as? String return APIResponse(success: success, requestCode: requestCode, errorMessage: errorMessage) } }
true
0e69cb2619d00541bb5ecec3297f51ed126d1cec
Swift
walterfernandes/teamwork.com
/teamwork/Features/Tasks/AddTasks/AddTaskCell.swift
UTF-8
1,809
2.984375
3
[ "MIT" ]
permissive
import UIKit protocol AddTaskCellDelegate: class { func didAddTask(_ cell: AddTaskCell, taskContent: String) func didRemoveTask(_ cell: AddTaskCell, taskContent: String) } class AddTaskCell: UITableViewCell { enum Style { case add case remove } @IBOutlet weak var contentTextField: UITextField! @IBOutlet weak var addRemoveButton: UIButton! weak var delegate: AddTaskCellDelegate? var style: Style = .add { didSet { switch style { case .add: contentTextField.isEnabled = true addRemoveButton.setImage(#imageLiteral(resourceName: "add"), for: .normal) addRemoveButton.tintColor = UIColor("#60BB46") case .remove: contentTextField.isEnabled = false addRemoveButton.setImage(#imageLiteral(resourceName: "remove"), for: .normal) addRemoveButton.tintColor = UIColor("#D6D8D6") } } } override func awakeFromNib() { super.awakeFromNib() contentTextField.delegate = self } @IBAction func addRemoveAction(_ sender:Any) { guard let taskContent = contentTextField.text, !taskContent.isEmpty else { return } switch style { case .add: delegate?.didAddTask(self, taskContent: taskContent) contentTextField.text = nil case .remove: delegate?.didRemoveTask(self, taskContent: taskContent) } } } extension AddTaskCell: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { addRemoveAction(textField) return true } }
true
7ebe9b1dcebd765f4d3e9bf4e43e2863716d5be0
Swift
ankush-bhatia/SwiftUI-Views
/SwiftUIViewsExample/Buttons/ButttonView.swift
UTF-8
654
3.015625
3
[ "MIT" ]
permissive
// // ButttonView.swift // SwiftUIViewsExample // // Created by Ankush Bhatia on 09/09/20. // import SwiftUI struct TitleButton: View { let title: String? = nil let image: Image? = nil var body: some View { Button(action: { }, label: { if title != nil { HStack { Spacer() Text(title!) .font(Font.title) Spacer() } } }) } } struct ButttonView_Previews: PreviewProvider { static var previews: some View { TitleButton(title: "Submit") } }
true
5d434a55bd807ed06d7a06544fb744e597c021de
Swift
svdfold/HW2.3
/HW2.3/Utils.swift
UTF-8
497
2.8125
3
[]
no_license
// // Utils.swift // HW2.3 // // Created by Mike Albright on 14.07.2021. // import Foundation import UIKit extension UIView { func setGradient(upperColor: UIColor, bottomColor: UIColor) { let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = [upperColor.cgColor, bottomColor.cgColor] gradient.startPoint = CGPoint(x: 0.5, y: 0) gradient.endPoint = CGPoint(x: 0.5, y: 1) self.layer.insertSublayer(gradient, at: 0) } }
true
8ec3b47e638c4c29b2726f3bacd56f3a5833cf1d
Swift
getyarley/COVID-Tracker
/COVID-Tracker/Views/MainPageView.swift
UTF-8
4,389
2.859375
3
[]
no_license
// // ContentView.swift // COVID-Tracker // // Created by Jeremy Yarley on 11/9/20. // import SwiftUI struct MainPageView: View { @EnvironmentObject var caseStore: CaseStore @State var region: Region = .us @State var state: SelectedState = .ny @State var dataFrequency: DataFrequency = .daily @State var searchCriteria: DataCriteria = .positiveIncrease @State var rotateReloadButton: Bool = false @State var showInfoSheet: Bool = false var body: some View { ScrollView{ VStack(alignment: .leading) { VStack(alignment: .leading) { HStack(alignment: .top) { Text((caseStore.region == .us) ? "United States" : Constants.states[caseStore.state.rawValue] ?? "") .font(.largeTitle) Spacer() Button(action: {self.showInfoSheet.toggle()}) { Image(systemName: "info.circle") .resizable() .frame(width: 20, height: 20) } .foregroundColor(Color.divider) } //HSTACK Text(Constants.dataCriteria[caseStore.searchCriteria.rawValue] ?? "") .font(.headline) .padding(.bottom) PlotView(frequency: self.$dataFrequency, dailyData: self.$caseStore.dailyCases, criteria: self.$searchCriteria) .environmentObject(self.caseStore) .frame(height: 300) .blur(radius: self.caseStore.loading ? 5 : 0) } //VSTACK .padding() CurrentDataRow(caseStore: self.caseStore) .padding(.horizontal) HStack(alignment: .center) { Text("Data Reported: \(self.caseStore.lastUpdated)") .font(.caption) .foregroundColor(Color.divider) LoadingView(isShowing: self.$caseStore.loading) { Button(action: { reloadData() withAnimation(.easeOut(duration: 0.6)) { self.rotateReloadButton.toggle() } self.rotateReloadButton.toggle() }) { ReloadButton() .rotationEffect(Angle.degrees(self.rotateReloadButton ? 360 : 0)) } } } //HSTACK .padding(.horizontal) Divider().background(Color.divider) LocationSelectionRow(region: self.$caseStore.region, state: self.$caseStore.state, reloadData: self.reloadData) .padding(.bottom, 8) .padding(.horizontal) CriteriaSelectionRow(dataFrequency: self.$caseStore.dataFrequency, searchCriteria: self.$caseStore.searchCriteria, reloadData: self.reloadData) .padding(.horizontal) .padding(.bottom, 30) Spacer() } //VSTACK } //SCROLLVIEW .sheet(isPresented: self.$showInfoSheet) { InformationView(closeView: self.closeInfoSheet) } } } extension MainPageView { func reloadData() { if caseStore.region == self.region, caseStore.dataFrequency == self.dataFrequency, caseStore.state == self.state, caseStore.searchCriteria == self.searchCriteria { return } else { self.caseStore.loading = true self.region = caseStore.region self.dataFrequency = caseStore.dataFrequency self.state = caseStore.state self.searchCriteria = caseStore.searchCriteria caseStore.loadJSONData() } } func closeInfoSheet() { self.showInfoSheet = false } } struct MainPageView_Previews: PreviewProvider { static var previews: some View { MainPageView() } }
true
cb78f6e123c77b77438d2bb35cc289b72f32c006
Swift
DyaDya709/PDD
/PddViewController.swift
UTF-8
1,957
2.734375
3
[]
no_license
// // PddViewController.swift // PDD // // Created by Дмитрий on 28.03.17. // Copyright © 2017 Ratnikov Dmitry. All rights reserved. // import UIKit class PddViewController: UIViewController, UITableViewDataSource { var questionModel = QuestionModel() @IBOutlet var realUrlImageView: UIImageView! @IBOutlet var question: UILabel! @IBOutlet var comment: UILabel! @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self let tranzit = DataLoad.dataLoad(fileName: "b2") for element in tranzit { self.question.text = element.quest self.comment.text = element.comment self.title = String(element.biletNumber!) questionModel.answers = element.answers realUrlImageView.image = element.image } } // Do any additional setup after loading the view. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)-> Int { return (questionModel.answers?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath) cell.textLabel?.text = questionModel.answers?[indexPath.row] return cell } } //private func loadData() { // // создали объект, который загрузит данные // let loader = DataLoader() // let result = loader.loadData(fileName: biletNum) // // вывели результат в консоль // // print (result) // // // self.title = "Номер билета:\(biletNum), номер вопроса:\(currentQuestionIndex + 1)" // у viewController есть свойство title // self.questionList = result // // //}
true
c14977c773b51fbeff2f3358252e98e9c8c13be9
Swift
nauaros/learn-swift
/05-making-decisions/challenge/Challenges.playground/Contents.swift
UTF-8
1,051
4.15625
4
[]
no_license
import Foundation // Challenge A /* let firstName = "Matt" if firstName == "Matt" { let lastName = "Galloway" } else if firstName == "Ray" { let lastName = "Wenderlich" } let fullName = firstName + " " + lastName ^ This line is wrong. 'lastName' is not visible to this scope. */ // This is the correct solution: let firstName = "Matt" var lastName = "" if firstName == "Matt" { lastName = "Galloway" } else if firstName == "Ray" { lastName = "Wenderlich" } let fullName = firstName + " " + lastName // Challenge B let coordinates = (1, 5, 0) // "On the x/y plane" //let coordinates = (2, 2, 2) // "x = y = z" //let coordinates = (3, 0, 1) // "On the x/z plane" //let coordinates = (3, 2, 5) // "Nothing special" //let coordinates = (0, 2, 4) // "On the y/z plane" switch (coordinates) { case (let x, let y, let z) where x == y && y == z: print("x = y = z") case (_, _, 0): print("On the x/y plane") case (_, 0, _): print("On the x/z plane") case (0, _, _): print("On the y/z plane") default: print("Nothing special") }
true
1ed1448e11126e838fa15222caa6fd0af664b035
Swift
ralungei/cdi_app
/CDI/Controlador.swift
UTF-8
3,173
2.703125
3
[]
no_license
// // Controlador.swift // CDI // // Created by ETSISI on 11/4/17. // Copyright © 2017 ETSISI. All rights reserved. // import UIKit class Controlador: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var vaccines = [Vaccine]() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self loadSampleVaccines() tableView.setEditing(true, animated: true) self.tableView.tableFooterView = UIView() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.vaccines.count + 1) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if(indexPath.row < self.vaccines.count){ let cell1 = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! VaccineTableViewCell! cell1?.nombre.text = vaccines[indexPath.row].nombre cell1?.fecha.text = vaccines[indexPath.row].fecha return cell1! } else{ let cell2 = self.tableView.dequeueReusableCell(withIdentifier: "finalCell") as UITableViewCell! cell2!.textLabel?.text = "añadir vacuna" return cell2! } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("hola") } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { if (indexPath.row == self.vaccines.count) { return UITableViewCellEditingStyle.insert } else{ return UITableViewCellEditingStyle.delete } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source self.vaccines.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .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 self.vaccines.append(Vaccine(id: "", nombre: "", fecha: "")!) tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .automatic) tableView.endUpdates() // tableView.reloadData() } } // LOAD Samples private func loadSampleVaccines() { guard let vaccine1 = Vaccine(id: "3 mg", nombre: "Vacuna1", fecha: "12/12/1996") else { fatalError("Unable to instantiate vaccine1") } guard let vaccine2 = Vaccine(id: "6 mg", nombre: "Vacuna2", fecha: "12/12/2000") else { fatalError("Unable to instantiate vaccine1") } vaccines += [vaccine1, vaccine2] } }
true
81bba144cef36df9a64d07d0e0cbf2439a93f5f7
Swift
smkumar84/clock
/Clock/Clock/Clock/ClockView.swift
UTF-8
7,858
2.6875
3
[]
no_license
// // ClockView.swift // ClockView // // Created by R on 25.10.2019. // Copyright © 2019 R. All rights reserved. // import UIKit final class ClockView: UIView { // Storyboard @IBInspectable var autostart: Bool = true @IBInspectable var showMarkers: Bool = true { didSet { define() }} @IBInspectable var showSecondHand: Bool = true { didSet { define() }} @IBInspectable var faceColor: UIColor = .white { didSet { define() }} @IBInspectable var borderColor: UIColor = .lightGray { didSet { define() }} @IBInspectable var fiveMarkerColor: UIColor = .black { didSet { define() }} @IBInspectable var oneMarkerColor: UIColor = .red { didSet { define() }} @IBInspectable var hourHandColor: UIColor = .black { didSet { define() }} @IBInspectable var minuteHandColor: UIColor = .black { didSet { define() }} @IBInspectable var secondHandColor: UIColor = .red { didSet { define() }} @IBInspectable var borderThickness: CGFloat = 1 { didSet { define() }} @IBInspectable var fiveMarkerHeight: CGFloat = 10 { didSet { define() }} @IBInspectable var oneMarkerHeight: CGFloat = 5 { didSet { define() }} @IBInspectable var fiveMarkerThickness: CGFloat = 5 { didSet { define() }} @IBInspectable var oneMarkerThickness: CGFloat = 1 { didSet { define() }} @IBInspectable var hourHandThickness: CGFloat = 5 { didSet { define() }} @IBInspectable var minuteHandThickness: CGFloat = 5 { didSet { define() }} @IBInspectable var secondHandThickness: CGFloat = 1 { didSet { define() }} private var startTime: Date? private var faceLayer: CALayer? private var roundLayer: CAShapeLayer! private var hourHandLayer: CALayer! private var minuteHandLayer: CALayer! private var secondHandLayer: CALayer! override var bounds: CGRect { didSet { define() }} // MARK: - Action func start(time: Date? = nil) { startTime = time ?? Date() updateHands() } func stop() { clear() startTime = nil } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) define() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) define() } private func define() { let isDefined = faceLayer != nil clear() if startTime != nil { startTime = startTime?.addingTimeInterval(-startTime!.timeIntervalSinceNow) updateHands() } else if !isDefined && autostart { start() } } private func clear() { if faceLayer != nil { faceLayer!.removeFromSuperlayer() faceLayer = nil } createFace() createHands() } private func createFace() { let radius = frame.width > frame.height ? frame.height / 2 : frame.width / 2 let frame = CGRect( x: self.frame.width > self.frame.height ? self.frame.width / 2 - radius : 0, y: self.frame.width < self.frame.height ? self.frame.height / 2 - radius : 0, width: radius * 2, height: radius * 2) faceLayer = CALayer() faceLayer!.frame = frame layer.addSublayer(faceLayer!) roundLayer = CAShapeLayer() roundLayer.lineWidth = borderThickness roundLayer.fillColor = faceColor.cgColor roundLayer.strokeColor = borderColor.cgColor roundLayer.path = UIBezierPath( arcCenter: CGPoint(x: frame.size.width / 2, y: frame.size.height / 2), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath faceLayer!.addSublayer(roundLayer) if showMarkers { let markerFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) faceLayer!.addSublayer(markerLayer( frame: markerFrame, count: 60 / 1, thickness: oneMarkerThickness, height: oneMarkerHeight, color: oneMarkerColor)) faceLayer!.addSublayer(markerLayer( frame: markerFrame, count: 60 / 5, thickness: fiveMarkerThickness, height: fiveMarkerHeight, color: fiveMarkerColor)) } } private func markerLayer(frame: CGRect, count: Int, thickness: CGFloat, height: CGFloat, color: UIColor) -> CAReplicatorLayer { let replicatorLayer = CAReplicatorLayer() replicatorLayer.frame = frame replicatorLayer.instanceCount = count let angle: CGFloat = .pi * 2 / CGFloat(count) replicatorLayer.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 1) let instanceLayer = CALayer() instanceLayer.frame = CGRect(x: frame.midX - thickness / 2, y: 0, width: thickness, height: height) instanceLayer.backgroundColor = color.cgColor replicatorLayer.addSublayer(instanceLayer) return replicatorLayer } private func createHands() { hourHandLayer = handLayer( thickness: hourHandThickness, height: 0.3, color: hourHandColor) roundLayer.addSublayer(hourHandLayer) minuteHandLayer = handLayer( thickness: minuteHandThickness, height: 0.4, color: minuteHandColor) roundLayer.addSublayer(minuteHandLayer) if showSecondHand { secondHandLayer = handLayer( thickness: secondHandThickness, height: 0.5, color: secondHandColor) roundLayer.addSublayer(secondHandLayer) } } private func handLayer(thickness: CGFloat, height: CGFloat, color: UIColor) -> CALayer { let layer = CALayer() layer.position = CGPoint(x: faceLayer!.frame.width / 2, y: faceLayer!.frame.height / 2) layer.anchorPoint = CGPoint(x: 0.5, y: 0.15) layer.bounds = CGRect(x: 0, y: 0, width: thickness, height: faceLayer!.frame.width * height) layer.backgroundColor = color.cgColor return layer } // MARK: - Update private func updateHands() { let calendar = Calendar.current let hours = calendar.component(.hour, from: startTime!) let minutes = calendar.component(.minute, from: startTime!) let seconds = calendar.component(.second, from: startTime!) animateHand( layer: hourHandLayer, angle: (CGFloat(hours) + CGFloat(minutes) * (1 / 60)) * (360 / 12), duration: 60 * 60 * 12, for: "hour") animateHand( layer: minuteHandLayer, angle: (CGFloat(minutes) + CGFloat(seconds) * (1 / 60)) * (360 / 60), duration: 60 * 60, for: "minute") if showSecondHand { animateHand( layer: secondHandLayer, angle: CGFloat(seconds) * (360 / 60), duration: 60, for: "second") } } private func animateHand(layer: CALayer, angle: CGFloat, duration: Double, for key: String) { layer.transform = CATransform3DMakeRotation(angle / 180 * .pi, 0, 0, 1) let secondAnimation = CABasicAnimation(keyPath: "transform.rotation.z") secondAnimation.repeatCount = .infinity secondAnimation.duration = duration secondAnimation.isRemovedOnCompletion = false secondAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) secondAnimation.fromValue = (angle + 180) * .pi / 180 secondAnimation.byValue = 2 * CGFloat.pi layer.add(secondAnimation, forKey: key) } }
true
7493827206946140ccca74d6c30d2e0bfac89ece
Swift
thachgiasoft/SwiftUI_Views
/SwiftUI_Views/ControlViews/DatePicker/DatePicker_YourOwnTitle.swift
UTF-8
1,253
3.375
3
[]
no_license
// // DatePicker_YourOwnTitle.swift // SwiftUI_Views // // Created by Mark Moeykens on 10/5/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct DatePicker_YourOwnTitle: View { @State private var nextFullMoonDate = Date() var body: some View { VStack(spacing: 20) { Text("DatePicker").font(.largeTitle) Text("Your Own Title").foregroundColor(.gray) Text("Even when you add your own title, you still have the problem with the date picker indenting.") .padding() .frame(maxWidth: .infinity) .background(Color.yellow) VStack(spacing: 0) { Text("Date of next full moon") .font(.title) DatePicker("", selection: $nextFullMoonDate, displayedComponents: .date) } Text("How can you prevent the indenting?") .padding() .frame(maxWidth: .infinity) .background(Color.yellow) }.font(.title) } } struct DatePicker_YourOwnTitle_Previews: PreviewProvider { static var previews: some View { DatePicker_YourOwnTitle() } }
true
5363959ba880ed1865ae2ab3193be30e5540a598
Swift
karenminasyan123/ModernCollectionViewSample
/ModernCollectionViewSample/ViewControllers/MenuViewController.swift
UTF-8
3,748
2.828125
3
[]
no_license
// // SamplesViewController.swift // ModernCollectionViewSample // // Created by Karen Minasyan on 10/17/20. // import UIKit private let reuseIdentifier = "Cell" final class MenuViewController: UICollectionViewController { enum Section { case main } struct MenuItem: Hashable { let title: String let viewControllerType: UIViewController.Type private let identifier = UUID() func hash(into hasher: inout Hasher) { hasher.combine(identifier) } static func == (lhs: MenuItem, rhs: MenuItem) -> Bool { return lhs.identifier == rhs.identifier } static func getMenuItems() -> [MenuItem] { [MenuItem(title: "List Sample", viewControllerType: ListViewController.self), MenuItem(title: "Grid Sample", viewControllerType: GridViewController.self), MenuItem(title: "Adaptive Grid Sample", viewControllerType: AdaptiveGridViewController.self), MenuItem(title: "Supplementary Items Sample", viewControllerType: SupplementaryItemsViewController.self), MenuItem(title: "Nested Groups Sample", viewControllerType: NestedGroupsViewController.self), MenuItem(title: "Different Scroll Behaviors", viewControllerType: ScrollBehaviorsViewController.self), MenuItem(title: "App Store Sample", viewControllerType: AppStoreViewController.self), MenuItem(title: "Waterfall layout", viewControllerType: WaterfallLayoutViewController.self)] } } private var dataSource: UICollectionViewDiffableDataSource<Section, MenuItem>! = nil override func viewDidLoad() { super.viewDidLoad() configureCollectionView() configureDataSource() } } extension MenuViewController { private func configureCollectionView() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.backgroundColor = .systemBackground collectionView.showsVerticalScrollIndicator = false view.addSubview(collectionView) } private func createLayout() -> UICollectionViewCompositionalLayout { let configuration = UICollectionLayoutListConfiguration(appearance: .plain) let layout = UICollectionViewCompositionalLayout.list(using: configuration) return layout } private func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, MenuItem> { cell, indexPath, menuItem in var configuration = cell.defaultContentConfiguration() configuration.text = menuItem.title cell.contentConfiguration = configuration } dataSource = UICollectionViewDiffableDataSource<Section, MenuItem>(collectionView: collectionView) { collectionView, indexPath, menuItem in collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: menuItem) } var snapshot = NSDiffableDataSourceSnapshot<Section, MenuItem>() snapshot.appendSections([.main]) snapshot.appendItems(MenuItem.getMenuItems()) dataSource.apply(snapshot) } } extension MenuViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) let menuItem = dataSource.itemIdentifier(for: indexPath) if let viewController = menuItem?.viewControllerType.init() { navigationController?.pushViewController(viewController, animated: true) } } }
true
2c0cadba4ef5cc6af43a3c9a2b0325c0adf4db50
Swift
SwiftStudies/OysterKit
/Sources/stlrc/Framework/Argument.swift
UTF-8
2,762
3.4375
3
[ "BSD-2-Clause" ]
permissive
// // Argument.swift // CommandKit // // Created by Sean Alling on 11/8/17. // import Foundation /** An object that represents a parsed command line interface argument. Every argument is seperated by a single space. */ public struct Argument { public var value: String public var type: ParsedType /** Represents the kind or type of Argument */ public enum ParsedType { case tool case command case option case parameter } /** An error relating to improper user input */ enum Errors: Error { case invalidToolName case commandNotFound(for: String) case optionNotFound case noCommandProvided case parametersNotFound case insufficientParameters(requiredOccurence: Cardinality) case invalidParameterType case tooManyParameters case unrecognizedOptionParameterSignature case incorrectParameterFormat(expected:String, actual:String) case requiredOptionNotFound(optionName:String) } public init(value: String, type: ParsedType) { self.value = value self.type = type } } public class Arguments { private var unprocessed = [Argument]() init(forTool tool:Tool){ for (index, element) in CommandLine.arguments.enumerated() { switch index { case 0: unprocessed.append(Argument(value: element, type: .tool)) case 1: if tool[commandNamed: element] != nil { unprocessed.append(Argument(value: element, type: .command)) break } fallthrough default: if element.hasPrefix("-") { let start : String.Index if element.hasPrefix("--"){ start = element.index(element.startIndex, offsetBy: 2) } else { start = element.index(after: element.startIndex) } unprocessed.append(Argument(value: String(element[start..<element.endIndex]), type: .option)) } else { // Parameter let newArg = Argument(value: element, type: .parameter) unprocessed.append(newArg) } } } } public var top : Argument? { return unprocessed.first } public var count : Int { return unprocessed.count } public func consume(){ assert(unprocessed.count > 0, "Attempt to consume an argument when none remain") unprocessed.removeFirst() } }
true
762816cbf33b6b21171376f6ffdb93d45489493f
Swift
sakshiprit/PasswordManager
/Manager/Shared/Utils/Extensions.swift
UTF-8
8,040
2.984375
3
[]
no_license
// // Extensions.swift // Manager // // Created by Sakshi patil on 01/09/2021. // import Foundation import SwiftUI import CommonCrypto struct AES { // MARK: - Value // MARK: Private private let key: Data private let iv: Data // MARK: - Initialzier init?(key: String, iv: String) { guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else { debugPrint("Error: Failed to set a key.") return nil } guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else { debugPrint("Error: Failed to set an initial vector.") return nil } self.key = keyData self.iv = ivData } // MARK: - Function // MARK: Public func encrypt(string: String) -> Data? { return crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt)) } func decrypt(data: Data?) -> String? { guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil } return String(bytes: decryptedData, encoding: .utf8) } func crypt(data: Data?, option: CCOperation) -> Data? { guard let data = data else { return nil } let cryptLength = data.count + kCCBlockSizeAES128 var cryptData = Data(count: cryptLength) let keyLength = key.count let options = CCOptions(kCCOptionPKCS7Padding) var bytesLength = Int(0) let status = cryptData.withUnsafeMutableBytes { cryptBytes in data.withUnsafeBytes { dataBytes in iv.withUnsafeBytes { ivBytes in key.withUnsafeBytes { keyBytes in CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes.baseAddress, keyLength, ivBytes.baseAddress, dataBytes.baseAddress, data.count, cryptBytes.baseAddress, cryptLength, &bytesLength) } } } } guard UInt32(status) == UInt32(kCCSuccess) else { debugPrint("Error: Failed to crypt data. Status \(status)") return nil } cryptData.removeSubrange(bytesLength..<cryptData.count) return cryptData } } extension String { func hexToString()->String{ var finalString = "" let chars = Array(self) for count in stride(from: 0, to: chars.count - 1, by: 2){ let firstDigit = Int.init("\(chars[count])", radix: 16) ?? 0 let lastDigit = Int.init("\(chars[count + 1])", radix: 16) ?? 0 let decimal = firstDigit * 16 + lastDigit let decimalString = String(format: "%c", decimal) as String finalString.append(Character.init(decimalString)) } return finalString } func base64Decoded() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .init(rawValue: 0)) } func md5Hash (str: String) -> String { if let strData = str.data(using: String.Encoding.utf8) { /// #define CC_MD5_DIGEST_LENGTH 16 /* digest length in bytes */ /// Creates an array of unsigned 8 bit integers that contains 16 zeros var digest = [UInt8](repeating: 0, count:Int(CC_MD5_DIGEST_LENGTH)) /// CC_MD5 performs digest calculation and places the result in the caller-supplied buffer for digest (md) /// Calls the given closure with a pointer to the underlying unsafe bytes of the strData’s contiguous storage. strData.withUnsafeBytes { // CommonCrypto // extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md) --| // OpenSSL | // unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md) <-| CC_MD5($0.baseAddress, UInt32(strData.count), &digest) } var md5String = "" /// Unpack each byte in the digest array and add them to the md5String for byte in digest { md5String += String(format:"%02x", UInt8(byte)) } // MD5 hash check (This is just done for example) if md5String.uppercased() == "8D84E6C45CE9044CAE90C064997ACFF1" { // print("Matching MD5 hash: 8D84E6C45CE9044CAE90C064997ACFF1") } else { // print("MD5 hash does not match: \(md5String)") } return md5String } return "" } } extension Data { init?(fromHexEncodedString string: String) { // Convert 0 ... 9, a ... f, A ...F to their decimal value, // return nil for all other input characters func decodeNibble(u: UInt16) -> UInt8? { switch(u) { case 0x30 ... 0x39: return UInt8(u - 0x30) case 0x41 ... 0x46: return UInt8(u - 0x41 + 10) case 0x61 ... 0x66: return UInt8(u - 0x61 + 10) default: return nil } } self.init(capacity: string.utf16.count/2) var even = true var byte: UInt8 = 0 for c in string.utf16 { guard let val = decodeNibble(u: c) else { return nil } if even { byte = val << 4 } else { byte += val self.append(byte) } even = !even } guard even else { return nil } } } extension String { /// Create `Data` from hexadecimal string representation /// /// This creates a `Data` object from hex string. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed. /// /// - returns: Data represented by this hexadecimal string. var hexadecimal: Data? { var data = Data(capacity: count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: self, range: NSRange(startIndex..., in: self)) { match, _, _ in let byteString = (self as NSString).substring(with: match!.range) let num = UInt8(byteString, radix: 16)! data.append(num) } guard data.count > 0 else { return nil } return data } } /* let password = "UserPassword1!" let key256 = "12345678901234561234567890123456" // 32 bytes for AES256 // let iv = "abcdefghijklmnop" // 16 bytes for AES128 var iv = "abcdefghijklmnopdjhhfkjhdjkjfkhds" // 16 bytes for AES128 iv = iv.md5Hash(str: iv) // iv = iv.hexToString() let base64ReadableKey = iv.base64Decoded() ?? "" print(base64ReadableKey) let aes256 = AES(key: key256, iv: iv) let encryptedPassword256 = aes256?.encrypt(string: password) print(aes256?.decrypt(data: encryptedPassword256)) */ /* func showPasswordEnter(text:String) { let password = "UserPassword1!" let iv = "abcdefghijklmnop" let key256 = "".md5Hash(str: "pp") let aes256 = AES(key: key256, iv: iv) let encryptedPassword256 = aes256?.encrypt(string: password) let strBase64 = encryptedPassword256!.base64EncodedString() print (strBase64) testingss(str: strBase64) } func testingss(str:String) { let iv = "abcdefghijklmnop" let key256 = "".md5Hash(str: "pp") let aes256 = AES(key: key256, iv: iv) let data = Data(base64Encoded: str, options: .ignoreUnknownCharacters) let decryptedValue = aes256?.decrypt(data: data) print(decryptedValue) } */
true
295b489bb8bf856d8fdb7dbc2d42a0c25c2c2bd4
Swift
hosamasd/grocery-swiftui
/grocery swiftui/view/applock/LockScreen.swift
UTF-8
4,533
3.03125
3
[]
no_license
// // LockScreen.swift // App Lock // // Created by hosam on 12/23/20. // import SwiftUI struct LockScreen: View { @State var password = "" // you can change it when user clicks reset password.... // AppStorage => UserDefaults.... @AppStorage("lock_Password") var key = "1111" @Binding var unLocked : Bool @State var wrongPassword = false let height = UIScreen.main.bounds.width < 750 ? true : false @State var isType = false @State var showAlert = false var body: some View { ZStack { if showAlert { // DispatchQueue.main.async { AlertControlView(textString: $key, showAlert: $showAlert, title: "Reset Password", message: "Type your password here\n defaul pass : \(key)") } else { VStack{ HStack{ Spacer(minLength: 0) Menu { Button(action: { print(123) }, label: { Label( title: { Text("Help") }, icon: { Image(systemName: "info.circle.fill") }) }) Button(action: { self.showAlert.toggle() }, label: { Label( title: { Text("Reset Password") }, icon: { Image(systemName: "key.fill") }) }) } label: { Image("menu") .renderingMode(.template) .resizable() .frame(width: 19, height: 19) .foregroundColor(.white) .padding() } } .padding(.leading) Image("logo") .resizable() .frame(width: 95, height: 95) .padding(.top,20) Text("Enter Pin to Unlock") .font(.title2) .fontWeight(.heavy) .padding(.top,20) HStack(spacing: 22){ // Password Circle View... ForEach(0..<4,id: \.self){index in PasswordView(index: index, password: $password) } } // for smaller size iphones... .padding(.top,height ? 20 : 30) // KeyPad.... Spacer(minLength: 0) if isType { Text(wrongPassword ? "Incorrect Pin" : "Passed!!") .foregroundColor(wrongPassword ? .red : .green) .fontWeight(.heavy) } Spacer(minLength: 0) LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3),spacing: height ? 5 : 15){ // Password Button .... ForEach(1...9,id: \.self){value in PasswordButton(value: "\(value)",password: $password, key: $key, unlocked: $unLocked, wrongPass: $wrongPassword, isType: $isType) } PasswordButton(value: "delete.fill",password: $password, key: $key, unlocked: $unLocked, wrongPass: $wrongPassword, isType: $isType) PasswordButton(value: "0", password: $password, key: $key, unlocked: $unLocked, wrongPass: $wrongPassword, isType: $isType) } .padding(.bottom) } } } .navigationTitle("") .navigationBarHidden(true) } // func make() -> View { // var body: some View { // AlertControlView(textString: $textString, // showAlert: $showAlert, // title: "Title goes here", // message: "Message goes here") // } // } } struct Home_Psreviews: PreviewProvider { static var previews: some View { Home() } }
true
f9d171aa54373411e8159fdd3469c2cbc78a2058
Swift
systers/malaria-app-ios
/Malaria Prevention App/ViewControllers/Take Pills Screen and Pills Stats/PillStats/MonthAdherenceCell.swift
UTF-8
1,254
3.125
3
[]
no_license
import Foundation import UIKit import HorizontalProgressView /// `AdherenceHorizontalBarCell` shows a graph bar for the adhrence for a month. class AdherenceHorizontalBarCell: UITableViewCell { @IBInspectable var LowAdherenceColor: UIColor = UIColor(red: 0.894, green: 0.429, blue: 0.442, alpha: 1.0) @IBInspectable var HighAdherenceColor: UIColor = UIColor(red: 0.374, green: 0.609, blue: 0.574, alpha: 1.0) @IBOutlet weak var month: UILabel! @IBOutlet weak var horizontalBar: HorizontalGraphBar! @IBOutlet weak var adherenceValue: UILabel! func configureCell(date: NSDate, adhrenceValue: Float) -> AdherenceHorizontalBarCell{ horizontalBar.progressColor = adhrenceValue < 50 ? LowAdherenceColor : HighAdherenceColor horizontalBar.progressValue = adhrenceValue // Yes, it is really needed to remove white background color from ipad. // https://stackoverflow.com/questions/27551291/uitableview-backgroundcolor-always-white-on-ipad self.backgroundColor = self.backgroundColor month.text = (date.formatWith("MMM") as NSString).substringToIndex(3).capitalizedString adherenceValue.text = "\(Int(adhrenceValue))%" return self } }
true
8fc1573312ad24c757a0e2810c5b8a35a90c4671
Swift
SakoHovaguimian/Weedmaps-Challenge
/WeedmapsChallenge/Sources/Home/HomeDetailViewController.swift
UTF-8
793
2.671875
3
[]
no_license
// // Copyright © 2018 Weedmaps, LLC. All rights reserved. // import UIKit import WebKit class HomeDetailViewController: UIViewController { // MARK: Properties public var business: Business? //MARK: Outlets @IBOutlet private var webView: WKWebView! //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.configureWebView() } // MARK: Helper Functions func configureWebView() { self.webView.allowsBackForwardNavigationGestures = true guard let business = self.business, let url = business.url else { return } if let businessURL = URL(string: url) { self.webView.load(URLRequest(url: businessURL)) } } }
true
919d8e8903ebf80b49d6962021ba66e1a11e6835
Swift
JotaGalera/ShopAPP
/ShopAPP/ShopAPP/Domain/UseCases/GetProductDetailUseCase.swift
UTF-8
626
3.140625
3
[]
no_license
import Foundation protocol GetProductDetailUseCase{ func execute(id: Int, onSuccess: @escaping (Product)->(), onFailure: @escaping (String)->() ) } class GetProductDetailUseCaseImplementation: GetProductDetailUseCase { private let repository: APIRepository init(repository: APIRepository = APIRepositoryImplementation()) { self.repository = repository } func execute(id: Int, onSuccess: @escaping (Product) -> (), onFailure: @escaping (String)->() ){ self.repository.getProductDetail(id: id, onSuccess: onSuccess, onFailure: onFailure) } }
true
b58fb819b0aaa84de0f68628400118bce61a8f0a
Swift
CoulsonWang/CWWeibo
/CWWeibo/CWWeibo/Classes/Tools/Tool/CWNetworkTool.swift
UTF-8
3,802
2.765625
3
[ "Apache-2.0" ]
permissive
// // 网络请求工具类 // // Created by Coulson_Wang on 2017/7/5. // Copyright © 2017年 Coulson_Wang. All rights reserved. // import AFNetworking //枚举请求类型 enum RequestType : String { case get = "get" case post = "post" } class CWNetworkTool: AFHTTPSessionManager { /// 单例 static let sharedInstance : CWNetworkTool = { let tool : CWNetworkTool = CWNetworkTool() //增加允许的解析类型 tool.responseSerializer.acceptableContentTypes?.insert("text/html") tool.responseSerializer.acceptableContentTypes?.insert("text/plain") return tool }() } // MARK:- 封装请求 extension CWNetworkTool { func request(_ requestType : RequestType, urlString : String, parameters : [String : Any], completion : @escaping (Any?, Error?) -> ()) { //成功回调 let successCallBack = { (task : URLSessionDataTask, result : Any) in completion(result, nil) } //失败回调 let failureCallBack = { (task : URLSessionDataTask?, error : Error) in completion(nil, error) } if requestType == .get { get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } else { post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } } } // MARK:- 封装AccessToken请求 extension CWNetworkTool { func loadAccessToken(code : String, completion : @escaping (_ result : [String : Any]?, _ error : Error?)->()) -> Void { let urlString = "https://api.weibo.com/oauth2/access_token" let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : grant_type, "code" : code, "redirect_uri" : redirect_uri] request(.post, urlString: urlString, parameters: parameters) { (result, error) in completion(result as? [String : Any], error) } } } // MARK:- 请求用户信息 extension CWNetworkTool { func loadUserInfo(access_token : String, uid : String, completion : @escaping (_ result : [String : Any]?, _ error : Error?)->()) -> Void { let urlString = "https://api.weibo.com/2/users/show.json" let parameters = ["access_token" : access_token, "uid" : uid] request(.get, urlString: urlString, parameters: parameters) { (result, error) in completion(result as? [String : Any], error) } } } // MARK:- 请求主页数据 extension CWNetworkTool { func loadStatusesData(since_id : Int , max_id : Int, completion : @escaping (_ result : [[String : Any]]?, _ error : Error?)->()) { let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" let parameters = ["access_token" : (WBUserAccountViewModel.sharedInstance.account?.access_token)!, "since_id" : "\(since_id)", "max_id" : "\(max_id)"] request(.get, urlString: urlString, parameters: parameters) { (result, error) in guard let resultDict = result as? [String : Any] else { completion(nil, error) return } completion(resultDict["statuses"] as? [[String : Any]], error) } } } // MARK:- 发布微博 extension CWNetworkTool { func postStatus(statusText : String, isSuccess : (_ isSuccess : Bool) -> ()) -> Void { let urlString = "https://api.weibo.com/2/statuses/update.json" let parameters = ["access_token": (WBUserAccountViewModel.sharedInstance.account?.access_token)!, "status": statusText] request(.post, urlString: urlString, parameters: parameters) { (result, error) in } } }
true
979aa7a3029b638571528c21ebf9804362f85e91
Swift
ardenkim/ikid
/iKid/PunViewController.swift
UTF-8
1,114
2.703125
3
[]
no_license
// // PunViewController.swift // iKid // // Created by studentuser on 11/3/17. // import UIKit class PunViewController: UIViewController { @IBOutlet weak var label: UILabel! let jokeLines = ["Knock, knock.", "Who's there?", "Yah.", "Yah who?", "No, I prefer Google."] var flip = 0 override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func flipJoke(_ sender: UIButton) { self.flip += 1 if (self.flip == 5) { self.flip = 0 } self.label.text = jokeLines[self.flip] } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
fa9f432d61e001b6b5f9f29252fe6f35c7228238
Swift
heramb21/StoreIT
/StoreTask/View Controllers/ViewController.swift
UTF-8
3,688
2.953125
3
[]
no_license
// // ViewController.swift // StoreTask // // Created by Mac on 30/06/18. // Copyright © 2018 Me. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Global Variables var sections = [Category]() var selectedItem = String() var selectedImageStr = String() // MARK: - Outlets @IBOutlet weak var productsTblView: UITableView! // MARK: - View Controller Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.productsTblView.separatorStyle = .none self.navigationItem.title = "Available Products" loadData() } // MARK: - Structure For Home Screen Data Using Category Object func loadData(){ let womenApparel = ["Jeans","Designer Dress"] let menApparel = ["Men Jeans"] let electronics = ["Television","Sound System"] let homeAppliance = ["Juicer & Mixers"] self.sections = [Category(name:"Women Apparel", items:womenApparel, images: ["GirlsJeans","DesignerDresses"]), Category(name:"Men Apparel", items:menApparel, images: ["MenJeans"]), Category(name:"Electronics", items:electronics, images: ["Television","SoundSystem"]), Category(name:"Home Appliance", items:homeAppliance, images: ["Juicer"])] self.productsTblView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if (segue.identifier == "DetailVC") { let detailVC:DetailViewController = segue.destination as! DetailViewController detailVC.productTitle = selectedItem detailVC.productImageStr = selectedImageStr } } } // MARK: - Tableview Datasource methods extension ViewController:UITableViewDataSource,UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let items = self.sections[section].items return items.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section].name } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: "StoreCell") let items = self.sections[indexPath.section].items let item = items[indexPath.row] // print(item) cell.textLabel?.text = item return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let items = self.sections[indexPath.section].items let item = items[indexPath.row] selectedItem = item let availableImages = self.sections[indexPath.section] let selectedImage = availableImages.images[indexPath.row] selectedImageStr = selectedImage self.performSegue(withIdentifier: "DetailVC", sender: self) } }
true
260d28a6d8ac344edfac0a2aa97a665fddefb137
Swift
ThaysPrado/Pokedex
/Pokedex/Models/PokemonItem.swift
UTF-8
871
2.75
3
[]
no_license
// // PokemonIte,.swift // Pokedex // // Created by Thays Prado on 10/04/20. // Copyright © 2020 ThaysPrado. All rights reserved. // import Foundation final class PokemonItem: PokemonItemPresentable { var name: String? var index: String? var urlImg: String? let url = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/" init(json: [String: Any]) { if let name = json["name"] as? String { self.name = "\(name)" } if let url = json["url"] as? String { let arr = url.components(separatedBy: "pokemon/") self.index = arr[1].components(separatedBy: "/")[0] self.urlImg = self.url + "\(self.index!).png" } } static func getModels(_ json: [[String: Any]]) -> [PokemonItem] { return json.map { PokemonItem(json: $0) } } }
true
3552d38009f1915e111169140283d9ce603b8345
Swift
byersc18/iOS---Ball-Bonanza
/Ball.swift
UTF-8
2,465
3.234375
3
[]
no_license
// // Ball.swift // Ball Bouncer // // Created by Cameron Byers on 6/30/16. // Copyright © 2016 Cameron Byers. All rights reserved. // import Foundation import SpriteKit class Ball: SKShapeNode { var ball: SKSpriteNode! var xSpeed: CGFloat! var ySpeed: CGFloat! var x: CGFloat! var y: CGFloat! init(radius: CGFloat, xPos: CGFloat, yPos: CGFloat, xS: CGFloat, yS: CGFloat, physics: Bool) { super.init() xSpeed = xS ySpeed = yS x = xPos y = yPos ball = SKSpriteNode(imageNamed: "blue") ball.size = CGSizeMake(radius * 2.45, radius * 2.45) ball.position = CGPointMake(xPos, yPos) if physics == true { ball.physicsBody = SKPhysicsBody(circleOfRadius: radius) ball.physicsBody?.affectedByGravity = false ball.physicsBody?.categoryBitMask = PhysicsCategory.ball ball.physicsBody?.contactTestBitMask = PhysicsCategory.square | PhysicsCategory.border } addChild(ball) } func directionMovement(speedMultiplier: Double, angleX: Double, angleY: Double) { let moveX = angleX * speedMultiplier let moveY = angleY * speedMultiplier x = x + CGFloat(moveX) y = y + CGFloat(moveY) ball.position.x = ball.position.x + CGFloat(moveX) ball.position.y = ball.position.y + CGFloat(moveY) } func constantMovement() { x = x + xSpeed y = y + ySpeed ball.position.x = ball.position.x + xSpeed ball.position.y = ball.position.y + ySpeed } func changeColor() { let random = Int(arc4random_uniform(6) + 1) if random == 1 { ball.texture = SKTexture(imageNamed: "aqua") } else if random == 2 { ball.texture = SKTexture(imageNamed: "blue") } else if random == 3 { ball.texture = SKTexture(imageNamed: "green") } else if random == 4 { ball.texture = SKTexture(imageNamed: "pink") } else if random == 5 { ball.texture = SKTexture(imageNamed: "red") } else { ball.texture = SKTexture(imageNamed: "yellow") } } func stop() { xSpeed = 0 ySpeed = 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
3eb18620c982e6dba6d7bd43e4ccb5d381906398
Swift
AOFStudentCheckSystem/StudentManager
/SystemManager/UI/Settings/SettingsTVC.swift
UTF-8
2,899
2.6875
3
[]
no_license
// // SettingsTVC.swift // SystemManager // // Created by Codetector on 14/10/2017. // Copyright © 2017 Guardian Tech. All rights reserved. // import UIKit import StaticDataTableViewController import Alertift class SettingsTVC: StaticDataTableViewController { @IBOutlet weak var signInCell: ButtonTableViewCell! @IBOutlet weak var userStatusCell: UserStatusCell! override func viewDidLoad() { super.viewDidLoad() self.configureAuthenticationSectionCells() NotificationCenter.default.addObserver(forName: Notification.Name("AUTH_TOKEN_CHANGED"), object: nil, queue: nil) { (_) in self.configureAuthenticationSectionCells() } // Setup SignIn Callback signInCell.setCallback { DispatchQueue.main.async { Alertift.alert(title: "Sign in", message: "Authenticate to enable more features") .textField { textField in textField.placeholder = "Username / Email" textField.autocorrectionType = .no } .textField { textField in textField.placeholder = "Password" textField.isSecureTextEntry = true } .action(.cancel("Cancel")) .action(.default("Sign in")) { _, _, textFields in let id = textFields?.first?.text ?? "" let password = textFields?.last?.text ?? "" // sign in StudentCheckAPI.shared.auth.authenticate(email: id, password: password, completionHandler: { (result) in print(result) }) } .show() } } } private func configureAuthenticationSectionCells() { let authenticationStatus = StudentCheckAPI.shared.auth.isAuthenticated self.cell(signInCell, setHidden: authenticationStatus) self.cell(userStatusCell, setHidden: !authenticationStatus) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) else { print("Settings View: ERROR - Failed to cast cellClass") return } if cell.responds(to: Selector(("onClick"))) { cell.perform(Selector(("onClick"))) } else { print("Settings View: INFO - Target cell does not respond to \"onClick()\" selector") } } }
true
291fd55554e711e499376fa908bfc49983ac1467
Swift
bereket6725/WeatherApp
/WeatherApp/WeatherApp/TableViewController.swift
UTF-8
3,415
2.890625
3
[ "MIT" ]
permissive
// // TableViewController.swift // WeatherApp // // Created by Bereket Ghebremedhin on 1/3/17. // Copyright © 2017 Bereket Ghebremedhin. All rights reserved. // import Foundation import UIKit class TableViewController: UIViewController, UITableViewDelegate { var tableView: UITableView! var dataSource: TableDataSource! var counter = 2//used to keep track of completed API requests //sets up tableView and calls the function to make the network request override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: view.bounds) tableView.register(UINib(nibName:"WeatherTableViewCell", bundle: nil), forCellReuseIdentifier: "weatherCell") tableView.rowHeight = 250.00 view.addSubview(tableView) dataSource = TableDataSource() tableView.dataSource = dataSource //sets up the pull to refresh let myRefreshControl = UIRefreshControl() myRefreshControl.backgroundColor = UIColor.gray myRefreshControl.tintColor = UIColor.white myRefreshControl.addTarget(self, action: #selector(TableViewController.makeNetworkRequests), for: .valueChanged) self.tableView.refreshControl = myRefreshControl makeNetworkRequests() } //calls the API's and assigns returned values to corresponding properties on the data source func makeNetworkRequests() { callCatFactsAPI { catFactsArray in self.dataSource.catFactsArray = catFactsArray self.stopRefreshing() } callWeatherAPI { parsedArray in self.dataSource.weatherArray = parsedArray print("made API call") self.stopRefreshing() } } //function gets called twice by both API requests and decrements our counter //when our counter hits zero we know that both API calls have returned and we can refresh the tableView and end the refresh animation func stopRefreshing(){ let decrementCounter = { self.counter -= 1 } decrementCounter() if self.counter == 0 { self.counter = 2 reloadTableData() } } //reloads tableView and ends refreshing func reloadTableData(){ DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() self.tableView.reloadData() //self.tableView.refreshControl?.endRefreshing() } } //in case we come up short from our network request func showErrorMessage() { let alertController = UIAlertController(title: nil, message: "Error Grabbing Weather", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertAction) DispatchQueue.main.async { self.present(alertController, animated: true, completion: nil) } } //calls the openWeatherMaps API func callWeatherAPI(completion:@escaping ([WeatherObject]) -> Void) { APIManager.makeAPICall(urlString: Constants.openWeatherMapsAPI.url, completion: { results in DispatchQueue.main.async { completion(results) } }) } //calls the catFacts API func callCatFactsAPI(completion: @escaping ([String]) -> Void) { APIManager.makeAPICall(urlString: Constants.CatFactsAPI.url, completion: completion) } }
true
3b1996590d24f0d8d10051f84f84fb957bccdda1
Swift
vladhamilton/TVShows
/TVShows/TVShows/Network/Request.swift
UTF-8
2,653
2.9375
3
[]
no_license
// // Request.swift // TVShows // // Created by Vladyslav Kolomiiets on 21.06.2020. // Copyright © 2020 Vladyslav Kolomiiets. All rights reserved. // import Foundation class Request { enum BaseURL: String { case movie case movieDetails case movieCredits case search var description: String { get { switch self { case .movie: return "https://api.themoviedb.org/3/trending/movie/week" case .movieDetails, .movieCredits: return "https://api.themoviedb.org/3/movie/" case .search: return "https://api.themoviedb.org/3/search/movie" } } } } enum ApiKey: String { case movieDataBaseAPI var description: String { get { switch self { case .movieDataBaseAPI: return "d932dec74e4382869f1dea81aa37ba5a" } } } } enum HttpMetod: String { case GET, POST } func getRequest(baseURL: Request.BaseURL, httpMetod: Request.HttpMetod, apiKey: Request.ApiKey, path: String?, urlParams: [URLQueryItem], completion: @escaping (Data?) -> ()) { let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) var urlComponents = URLComponents(string: baseURL.description)! if let path = path { urlComponents.path.append(path) } urlComponents.queryItems = [ URLQueryItem(name: "api_key", value: apiKey.description) ] urlComponents.queryItems?.append(contentsOf: urlParams) urlComponents.percentEncodedQuery = urlComponents.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") var request = URLRequest(url: urlComponents.url!) print(request.url!) request.httpMethod = httpMetod.rawValue let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if (error == nil) { // Success let statusCode = (response as! HTTPURLResponse).statusCode print("URL Session Task Succeeded: HTTP \(statusCode)") completion(data) } else { // Failure print("URL Session Task Failed: %@", error!.localizedDescription); } }) task.resume() session.finishTasksAndInvalidate() } }
true
163eaacbfeae9acb98a91a0c23e7643d8b556eb3
Swift
sroik/flappy-bird
/FlappyBird/Sources/Game/Node/Pipe.swift
UTF-8
747
2.578125
3
[]
no_license
// // Copyright © 2019 sroik. All rights reserved. // import SpriteKit final class Pipe: SKShapeNode { let size: CGSize init(size: CGSize) { self.size = size super.init() setup() } required convenience init?(coder aDecoder: NSCoder) { self.init(size: .zero) } private func setup() { path = CGPath(rect: CGRect(center: .zero, size: size), transform: nil) fillColor = .grass strokeColor = .clear blendMode = .replace setupPhysics() } private func setupPhysics() { physicsBody = SKPhysicsBody(rectangleOf: size) physicsBody?.isDynamic = false physicsBody?.categoryBitMask = CollisionCategory.pipe.rawValue } }
true
d37b271545ff7e93e8af38265743986c300ef140
Swift
yuta24/Podcasts
/Podcasts/Sources/Services/AudioClient.swift
UTF-8
3,763
2.6875
3
[ "MIT" ]
permissive
// // AudioClient.swift // Podcasts // // Created by Yu Tawata on 2020/09/14. // import Foundation import Combine import AVFoundation import ComposableArchitecture struct AudioClient { struct Properties: Equatable { var rate: Float? var isMuted: Bool? var volume: Float? } enum Action: Equatable { case updatePeriodicTime(CMTime) } var play: (AnyHashable, URL) -> Effect<Action, Never> var resume: (AnyHashable) -> Effect<Never, Never> var pause: (AnyHashable) -> Effect<Never, Never> var stop: (AnyHashable) -> Effect<Never, Never> var rate: (AnyHashable) -> Float? var currentTime: (AnyHashable) -> CMTime? var seek: (AnyHashable, CMTime) -> Effect<Never, Never> var isMuted: (AnyHashable) -> Bool? var volume: (AnyHashable) -> Float? var set: (AnyHashable, Properties) -> Void } private struct Dependencies { let player: AVPlayer let subscriber: Effect<AudioClient.Action, Never>.Subscriber } private var dependencies: [AnyHashable: Dependencies] = [:] extension AudioClient { static let live: AudioClient = { return .init( play: { id, url in Effect.run { subscriber in let player = AVPlayer() dependencies[id] = Dependencies(player: player, subscriber: subscriber) player.replaceCurrentItem(with: .init(url: url)) player.addPeriodicTimeObserver(forInterval: .init(value: 10, timescale: 10), queue: .none) { time in subscriber.send(.updatePeriodicTime(time)) } player.play() return AnyCancellable { dependencies[id]?.player.pause() dependencies[id] = .none } } .cancellable(id: id) }, resume: { id in Effect.fireAndForget { dependencies[id]?.player.play() } }, pause: { id in Effect.fireAndForget { dependencies[id]?.player.pause() } }, stop: { id in Effect.fireAndForget { dependencies[id]?.player.pause() dependencies[id] = .none } }, rate: { dependencies[$0]?.player.rate }, currentTime: { dependencies[$0]?.player.currentTime() }, seek: { id, time in Effect.fireAndForget { dependencies[id]?.player.seek(to: time) } }, isMuted: { dependencies[$0]?.player.isMuted }, volume: { dependencies[$0]?.player.volume }, set: { id, properties in if let rate = properties.rate { dependencies[id]?.player.rate = rate } } ) }() } extension AudioClient { static let mock = AudioClient( play: { _, _ in Effect.fireAndForget { } }, resume: { _ in Effect.fireAndForget { } }, pause: { _ in Effect.fireAndForget { } }, stop: { _ in Effect.fireAndForget { } }, rate: { _ in return .none }, currentTime: { _ in return .none }, seek: { _, _ in Effect.fireAndForget { } }, isMuted: { _ in return .none }, volume: { _ in return .none }, set: { _, _ in } ) }
true
e2661aa5cd0f5516dd4339bed6465e1dba627baf
Swift
chuangss/m3u8_download_ios
/ios/Classes/logic/FileOperation.swift
UTF-8
4,066
3.15625
3
[]
no_license
// // FileOperation.swift // WLM3U_Example // // Created by one on 2021/10/15. // Copyright © 2021 CocoaPods. All rights reserved. // import Foundation //文件操作类 class FileOperation { //把字符串写入指定文件中 static func writeStrToFile(writeFilePath:String, writeContent:String){ FileManager.default.createFile(atPath: writeFilePath, contents: nil, attributes: nil) let str = writeContent as String let wr = NSMutableData() wr.append(str.data(using:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!) do { let writeHandler = try? FileHandle(forWritingAtPath:writeFilePath) if writeHandler != nil { writeHandler!.seekToEndOfFile() writeHandler?.write(wr as Data) } } catch { printDebug("写入文件中断 writeFilePath = \(writeFilePath)") } printDebug("文件写入完成:\(writeFilePath)") } //创建文件夹 无则创建 有则跳过 static func createFinder(path:String){ let isExist = FileManager.default.fileExists(atPath: path) if !isExist { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } catch { printDebug("createDirectory error:\(error)") } } } // 复制一个文件,到目标位置 static func copyFile(sourceUrl:String, targetUrl:String) { let fileManager = FileManager.default do{ try fileManager.copyItem(atPath: sourceUrl, toPath: targetUrl) printDebug("Success to copy file.") }catch{ printDebug("Failed to copy file.") } } // 移动文件到目标位置 static func movingFile(sourceUrl:String, targetUrl:String){ let fileManager = FileManager.default let targetUrl = targetUrl printDebug("targetUrl = \(targetUrl)") do{ try fileManager.moveItem(atPath: sourceUrl, toPath: targetUrl) printDebug("Succsee to move file.") }catch{ printDebug("Failed to move file.") } } // 删除目标文件 static func removeFile(sourceUrl:String){ let fileManger = FileManager.default do{ try fileManger.removeItem(atPath: sourceUrl) printDebug("Success to remove file.") }catch{ printDebug("Failed to remove file.") } } // 删除目标文件夹下所有的内容 // rmFolder 是否下载文件夹 static func removeFolder(folderUrl:String, rmFolder:Bool){ let fileManger = FileManager.default //然后获得所有该目录下的子文件夹 let files:[AnyObject]? = fileManger.subpaths(atPath: folderUrl)! as [AnyObject] //创建一个循环语句,用来遍历所有子目录 for file in files! { do{ //删除指定位置的内容 try fileManger.removeItem(atPath: folderUrl + "/\(file)") printDebug("Success to remove folder: \(folderUrl + "/\(file)")") }catch{ printDebug("Failder to remove folder") } } if rmFolder { do{ //删除文件夹 try fileManger.removeItem(atPath: folderUrl) printDebug("Success to remove folder: \(folderUrl)") }catch{ printDebug("Failder to remove folder") } } } // 遍历目标文件夹 static func listFolder(folderUrl:String){ let manger = FileManager.default // 获得文档目录下所有的内容,以及子文件夹下的内容,在控制台打印所有的数组内容 let contents = manger.enumerator(atPath: folderUrl) printDebug("contents:\(String(describing: contents?.allObjects))") } }
true
7d78d2461f3c28da728fb40de344f464c9b1c310
Swift
asuarezd/TUCommunicationCheckoutSystem
/TUCommunicationCheckoutSystem/Kit.swift
UTF-8
1,485
2.6875
3
[]
no_license
// // Inventory-Items.swift // TUCommunicationCheckoutSystem // // Created by Michael Bryce on 1/29/19. // Copyright © 2019 CheckoutGurus. All rights reserved. // import UIKit import Foundation import os.log class Kit: NSObject{ // Properties var kitName: String var items: Array<(Int,String)> var checkIn: Int var checkOut: Int var lastUsers: Array<Int> // Archiving Paths static let DocumentsDirectory = FileManager().urls( for: .documentDirectory, in:.userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("Kits") // Types struct PropertyKey { static let kitName = "name" static let items = "description" static let checkIn = "checkIn" static let checkOut = "checkOut" static let lastUsers = "LastUsers" } //Initialization init?(kitName:String, items:Array<(Int,String)>){ self.kitName = kitName self.items = items self.checkIn = 000000 self.checkOut = 000000 self.lastUsers = [] } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
6b0b9e2c032cf74c5346b36c425846ec14da29d2
Swift
objchris/LeetCodePearl
/数据结构/堆/313超级丑数/Solution.swift
UTF-8
769
3.375
3
[]
no_license
/* 313. 超级丑数 https://leetcode-cn.com/problems/super-ugly-number/ */ class Solution { func nthSuperUglyNumber(_ n: Int, _ primes: [Int]) -> Int { var superUglyNumbers = [1] superUglyNumbers.reserveCapacity(n) var primesWithCountIndex = primes.map { (prime: $0, countIndex: 0) } for _ in 1..<n { let candidates = primesWithCountIndex.map { $0.prime * superUglyNumbers[$0.countIndex] } let nextNumber = candidates.min()! for index in candidates.enumerated().filter({ $0.element == nextNumber }).map(\.offset) { primesWithCountIndex[index].countIndex += 1 } superUglyNumbers.append(nextNumber) } return superUglyNumbers.last! } }
true
16b2844c7c12b1250a1785ed4f382cfab12dac4c
Swift
CS-52/Tree-To-Tree
/TreeToTree/CreateUsers.swift
UTF-8
2,120
2.828125
3
[]
no_license
// // CreateUsers.swift // TreeToTree // // Created by Jose Miguel Giron on 22/5/18. // Copyright © 2018 CS+Social Good. All rights reserved. // import Foundation class CreateUsers { class func addUsers() { ///*// CODE TO CREATE EVENTS IN BACK END. REMOVE AFTER FIRST RUN \\ //let userIDs = ["0000", "0001", "0002", "0003"] //USER 0 let name0 = "Austin" let lastName0 = "Chow" let year0 = "Sophomore" let major0 = "Computer Science" //let photo1 let hours0 = 30 let badgesIDs0 = ["0000"] let friendsIDs0 = ["0001"] let goingIDs0 = [ "0000": [ "shifts": ["0000", "0001"] ] ] let interestedIDs0 = ["0001"] let userInfo0: [String: Any] = [ "firstName": name0, "lastName": lastName0, "year": year0, "major": major0, "hours": hours0, "friends": friendsIDs0, "badgesIDs": badgesIDs0, "goingIDs": goingIDs0, "interestedIDs": interestedIDs0 ] //USER 1 let name1 = "Suzanne" let lastName1 = "Joh" let year1 = "Sophomore" let major1 = "Computer Science" //let photo1 let hours1 = 30 let badgesIDs1 = ["0000"] let friendsIDs1 = ["0000"] let goingIDs1 = [ "0000": [ "shifts": ["0001"] ] ] let interestedIDs1 = ["0001"] let userInfo1: [String: Any] = [ "firstName": name1, "lastName": lastName1, "year": year1, "major": major1, "hours": hours1, "friends": friendsIDs1, "badgesIDs": badgesIDs1, "goingIDs": goingIDs1, "interestedIDs": interestedIDs1 ] let userInfos = [userInfo0, userInfo1] for i in 0...1{ API.createUser(userInfo: userInfos[i] as Dictionary<String, AnyObject>) } } }
true
6bdaa0d012d8f00c8623435920076125de8675b2
Swift
rlarcher/yes-chef
/Yes Chef/Yes Chef/String+Utils.swift
UTF-8
5,154
3.203125
3
[]
no_license
// // String+Utils.swift // Yes Chef // // Created by Adam Larsen on 2016/02/17. // Copyright © 2016 Conversant Labs. All rights reserved. // import Foundation extension String { func containsAny(strings: [String]) -> Bool { for string in strings { if self.containsString(string) { return true } } return false } func fuzzyContains(other: String, useLowercase shouldUseLowercase: Bool = true) -> Bool { if shouldUseLowercase { return self.lowercaseString.scoreByTokens(other.lowercaseString) > Utils.kFuzzyScoreThreshold } else { return self.scoreByTokens(other) > Utils.kFuzzyScoreThreshold } } // Also does token-wise checking when calculating score, instead of just checking against the entire string. func scoreByTokens(other: String, fuzziness: Double = 0.7) -> Double { var highestScore = 0.0 var currentScore = 0.0 // Start by scoring the entire string currentScore = self.score(other, fuzziness: fuzziness) if currentScore > highestScore { highestScore = currentScore } let selfTokens = self.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet) let otherTokens = other.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet) for selfToken in selfTokens { for otherToken in otherTokens { currentScore = selfToken.score(otherToken, fuzziness: fuzziness) if currentScore > highestScore { highestScore = currentScore } } } return highestScore } // Returns true if this string is empty or contains only whitespace. var isBlank: Bool { if self.isEmpty { return true } let trimmedSelf = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if trimmedSelf.isEmpty { return true } return false } func plural(count: Int) -> String { return plural(count, pluralForm: self + "s") } func plural(count: Int, pluralForm: String) -> String { if count == 1 { return self } else { return pluralForm } } func toOrdinalNumber() -> NSNumber? { let formatter = NSNumberFormatter() // Handle a numerical ordinal (e.g. "4th"). formatter.numberStyle = .OrdinalStyle if let number = formatter.numberFromString(self) { return number } // Handle a spelled-out ordinal (e.g. "fourth"). formatter.numberStyle = .SpellOutStyle if let number = formatter.numberFromString(self) { return number } return nil } func toNumber() -> NSNumber? { if let number = self.decimalOrSpellOutToNumber() { return number } else if let number = self.ordinalToNumber() { return number } else { return nil } } private func decimalOrSpellOutToNumber() -> NSNumber? { let formatter = NSNumberFormatter() // Remove any extraneous spaces around punctuation // (e.g. "3 . 5" -> "3.5") // (e.g. "10 , 000" -> "10,000"). // These white spaces may be inserted by the speech recognition service to separate out tokens. Luis definitely does this. let despacedText = self.stringByReplacingOccurrencesOfString("((?<=\\d) (?=.|,))|((?<=.|,) (?=\\d))", withString: "", options: .RegularExpressionSearch, range: nil) // Handle a numerical string (e.g. "4"). formatter.numberStyle = .DecimalStyle if let number = formatter.numberFromString(despacedText) { return number } // Pre-process the raw number text so multi-word numbers are in a format expected by NSNumberFormatterSpellOutStyle (e.g. we want "thirty-eight", not "thirty eight"). let hyphenatedText = Utils.insertHyphensBetweenNumbersInText(self) // Handle a spelled-out number (e.g. "four"). formatter.numberStyle = .SpellOutStyle if let number = formatter.numberFromString(hyphenatedText) { return number } return nil } private func ordinalToNumber() -> NSNumber? { let formatter = NSNumberFormatter() // Handle a numerical ordinal (e.g. "4th"). formatter.numberStyle = .OrdinalStyle if let number = formatter.numberFromString(self) { return number } // Handle a spelled-out ordinal (e.g. "fourth"). formatter.numberStyle = .SpellOutStyle if let number = formatter.numberFromString(self) { return number } return nil } }
true
a9b4b276c67d18a4cd6636d0c1a7392fd485a3e1
Swift
freishya/Kopid19Tracker
/Kopid19Tracker/TrackingViewModel.swift
UTF-8
1,529
2.5625
3
[]
no_license
// // TrackingViewModel.swift // Kopid19Tracker // // Created by Izzan Oktiadi on 24/11/20. // import Foundation class TrackingListViewModel: ObservableObject { @Published var trackings = [TrackingViewModel]() func getTrackingData() { Services().getCovidTrackingResult{ trackingList in if let trackingList = trackingList { DispatchQueue.main.async { self.trackings = trackingList.map(TrackingViewModel.init) } } } } } class TrackingViewModel { var tracking: Tracking init(tracking: Tracking) { self.tracking = tracking } // For ID Data var fid: Int { return self.tracking.attributes.fid } var province: String { return self.tracking.attributes.provinsi } var positive: Int { return self.tracking.attributes.kasusPosi } var death: Int { return self.tracking.attributes.kasusMeni } var recovered: Int { return self.tracking.attributes.kasusSemb } // For US Data // let id: UUID = UUID() // // var state: String { // return self.tracking.state // } // // var total: Int { // return self.tracking.total // } // // var positive: Int { // return self.tracking.positive // } // // var death: Int { // return self.tracking.death // } // // var hospitalized: Int { // return self.tracking.hospitalized ?? 0 // } }
true
40f0fcb550de1e8cc6ef372eb7dff81879015111
Swift
alvincrisuy/SwiftKit
/Sources/SwiftKit/Services/KitService/DefaultKitService.swift
UTF-8
884
2.90625
3
[ "MIT" ]
permissive
// // DefaultKitService.swift // SwiftKitCLI // // Created by Sven Tiigi on 01.05.19. // import Foundation // MARK: - DefaultKitService /// The DefaultKitService struct DefaultKitService { /// The KitSetupService let kitSetupService: KitSetupService /// The KitMigrationService let kitMigrationService: KitMigrationService } // MARK: - KitService extension DefaultKitService: KitService { /// Generate Kit at Directory /// /// - Parameters: /// - kit: The Kit /// - directory: The Kit Directory /// - Throws: If generating fails func generate(kit: Kit, at directory: Kit.Directory) throws { // Try to setup Kit at Directory try self.kitSetupService.setup(at: directory) // Try to migrate Kit at Directory try self.kitMigrationService.migrate(kit: kit, at: directory) } }
true
77e3923c0cb3732f7135f773e721d9ce37072b49
Swift
ThePowerOfSwift/ios-app
/CodandoJuntasApp/CodandoJuntasApp/Storage/LocalStorageImpl.swift
UTF-8
1,224
2.96875
3
[]
no_license
// // LocalStorageImpl.swift // CodandoJuntasApp // // Created by Alexandre Vassinievski on 17/09/2018. // Copyright © 2018 Codando Juntas. All rights reserved. // import Foundation import RxSwift struct LocalStorageKeys { private init() {} static let lastSearch = "last_search" static let firstAccess = "first_access" } class LocalStorageImpl: LocalStorage { let userDefaults: UserDefaults init(userDefaults: UserDefaults = UserDefaults.standard) { self.userDefaults = userDefaults userDefaults.register(defaults: [LocalStorageKeys.firstAccess: true]) } var lastSearch: Observable<[String]> { return userDefaults.rx .observe([String].self, LocalStorageKeys.lastSearch) .distinctUntilChanged() .unwrap() } var firstAccess: Bool { get { return userDefaults.bool(forKey: LocalStorageKeys.firstAccess) } set { userDefaults.set(newValue, forKey: LocalStorageKeys.firstAccess) } } func clear() { userDefaults.removeObject(forKey: LocalStorageKeys.lastSearch) userDefaults.removeObject(forKey: LocalStorageKeys.firstAccess) } }
true
1d204d90b663b7dcad9520dcbdbe2b80755732bd
Swift
dmaulikr/Chatify-ios
/Chatify/Chatify/Controllers/Chat/ChatsListTableViewController.swift
UTF-8
1,990
2.546875
3
[ "MIT" ]
permissive
// // ChatsListTableViewController.swift // Chatify // // Created by Marcel Canhisares on 14/02/17. // Copyright © 2017 Azell. All rights reserved. // import UIKit class ChatsListTableViewController: UITableViewController { var selectedUser: User? override func viewDidLoad() { super.viewDidLoad() self.fillUsers() } func fillUsers() { ProfileService.sharedInstance.fillUsers { self.tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return ProfileService.sharedInstance.users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kChatListCellIdentifier, for: indexPath) as! ChatListTableViewCell cell.configure(user: ProfileService.sharedInstance.users[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.selectedUser = ProfileService.sharedInstance.users[indexPath.row] self.performSegue(withIdentifier: kChatListToDetails, sender: self) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == kChatListToDetails, let destinationViewController = segue.destination as? ChatDetailViewController { destinationViewController.selectedUser = self.selectedUser } } }
true
e024e8dfad9913eb1b7d3dada635e0d7c126ff63
Swift
gabe351/ShowMovies
/ShowMovies/Utils/DefaultValues.swift
UTF-8
1,294
3.21875
3
[]
no_license
// // DefaultValue.swift // ShowMovies // // Created by Gabriel Rosa on 18/08/18. // Copyright © 2018 Gabe. All rights reserved. // import Foundation public func defaultStringIfNil(_ value: String?, defaultValue: String = "") -> String { return defaultIfNil(value, defaultValue: defaultValue) } public func defaultIntIfNil(_ value: Int?, defaultValue: Int = 0) -> Int { return defaultIfNil(value, defaultValue: defaultValue) } public func defaultFloatIfNil(_ value: Float?, defaultValue: Float = 0.0) -> Float { return defaultIfNil(value, defaultValue: defaultValue) } public func defaultDateIfNil(_ value: Date?, defaultValue: Date = Date()) -> Date { return defaultIfNil(value, defaultValue: defaultValue) } public func defaultBoolIfNil(_ value: Bool?, defaultValue: Bool = false) -> Bool { return defaultIfNil(value, defaultValue: defaultValue) } public func defaultArrayInt(_ array: [Int]?) -> [Int] { var defaultArray = [Int]() guard let foundInts = array else { return defaultArray } foundInts.forEach { defaultArray.append(defaultIntIfNil($0)) } return defaultArray } public func defaultIfNil<T>(_ value: T?, defaultValue: T) -> T { if value == nil { return defaultValue } return value! }
true
7b4b5de6fe64790dbe372e12e11f7bb673f7f623
Swift
sberrevoets/SDCAlertView
/Source/Text Fields/TextFieldCell.swift
UTF-8
2,259
2.5625
3
[ "MIT" ]
permissive
import UIKit @objc(SDCTextFieldCell) @available(iOSApplicationExtension, unavailable) final class TextFieldCell: UITableViewCell { @IBOutlet private var borderView: UIView! @IBOutlet private var textFieldContainer: UIView! var textField: UITextField? { didSet { oldValue?.removeFromSuperview() if let textField = self.textField { self.add(textField) } } } var visualStyle: AlertVisualStyle? { didSet { self.textField?.font = self.visualStyle?.textFieldFont self.borderView.backgroundColor = self.visualStyle?.textFieldBorderColor self.textFieldContainer.backgroundColor = self.visualStyle?.textFieldBackgroundColor guard let padding = self.visualStyle?.textFieldMargins else { return } self.paddingConstraints?.leading.constant = padding.left self.paddingConstraints?.trailing.constant = -padding.right self.paddingConstraints?.top.constant = padding.top self.paddingConstraints?.bottom.constant = -padding.bottom } } private var paddingConstraints: (leading: NSLayoutConstraint, trailing: NSLayoutConstraint, top: NSLayoutConstraint, bottom: NSLayoutConstraint)? private func add(_ textField: UITextField) { let container = self.textFieldContainer container?.addSubview(textField) textField.translatesAutoresizingMaskIntoConstraints = false let insets = self.visualStyle?.textFieldMargins ?? UIEdgeInsets() let leading = textField.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: insets.left) let trailing = textField.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: insets.right) let top = textField.topAnchor.constraint(equalTo: self.topAnchor, constant: insets.top) let bottom = textField.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: insets.bottom) self.paddingConstraints = (leading: leading, trailing: trailing, top: top, bottom: bottom) NSLayoutConstraint.activate([leading, trailing, top, bottom]) } }
true
34ca7a1b953431d08c476f479f9e61fd0c22632a
Swift
Inquis1t0r/Edabit
/Swift/CheckifanIntegerisDivisibleByFive.swift
UTF-8
62
2.921875
3
[]
no_license
func divisibleByFive(_ num: Int) -> Bool { return num%5==0 }
true
2a85793e9a7b4f349d79b3283bba57030981c665
Swift
BJap/SwiftCrypt
/SwiftCrypt/Protocols/Key.swift
UTF-8
467
3
3
[ "MIT" ]
permissive
// // Key.swift // SwiftCrypt // // Created by Bobby Jap on 11/14/16. // Copyright © 2016 Bobby Jap. All rights reserved. // import Foundation protocol Key { /// Generates a random key. /// /// - Returns: A random key. static func generateKey() -> String /// Validates a key. /// /// - Parameter key: The key to validate. /// - Returns: Whether or not the key is valid for encryption. static func validate(key: String) -> Bool }
true