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
e812c5c4e4e69eb30e05c48172098151c906d4d2
Swift
aalbargi92/On-The-Map
/On The Map/Controller/AddLocationViewController.swift
UTF-8
2,359
2.65625
3
[]
no_license
// // AddLocationViewController.swift // On The Map // // Created by Abdullah AlBargi on 25/10/2019. // Copyright © 2019 Abdullah AlBargi. All rights reserved. // import UIKit import MapKit class AddLocationViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var addButton: UIButton! var studentLocation: StudentLocation! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let annotation = Annotation() annotation.title = studentLocation.mapString annotation.coordinate = studentLocation.coordinate mapView.addAnnotation(annotation) mapView.setRegion(.init(center: studentLocation.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000), animated: true) mapView.selectAnnotation(annotation, animated: true) } @IBAction func finishPressed(_ sender: Any) { setAdding(true) if UdacityService.Auth.objectId == "" { UdacityService.addStudentLocation(studentLocation: studentLocation, completion: handleAddResponse(success:error:)) } else { UdacityService.updateStudentLocation(studentLocation: studentLocation, completion: handleAddResponse(success:error:)) } } func handleAddResponse(success: Bool, error: Error?) { setAdding(false) if success { dismiss(animated: true, completion: nil) } else { showAlert(title: "Error", message: error!.localizedDescription) } } func setAdding(_ adding: Bool) { addButton.isEnabled = !adding addButton.showLoading(adding) } } extension AddLocationViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard annotation is Annotation else { return nil } let identifier = "marker" var view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) view?.canShowCallout = true } else { view?.annotation = annotation } return view } }
true
d2ef900c51d17d0a4e6d8d392258870280c29fd4
Swift
NghiaTranUIT/CodableKit
/Sources/CodableKit/JSON/JSON.swift
UTF-8
6,765
3.296875
3
[ "MIT" ]
permissive
// // JSON.swift // CodableKit // // Created by 李孛 on 2018/6/15. // import Foundation /// JSON value. /// /// [https://json.org](https://json.org) public enum JSON: Equatable { case object([String: JSON]) case array([JSON]) case number(NSNumber) case string(String) case `true` case `false` case null } // MARK: - Initializers extension JSON { public init(_ object: [String: JSON]) { self = .object(object) } public init?(_ dictionary: [String: Any]) { var object: [String: JSON] = [:] for (key, value) in dictionary { guard let json = JSON(value) else { return nil } object[key] = json } self.init(object) } public init(_ array: [JSON]) { self = .array(array) } public init?(_ array: [Any]) { var jsonArray: [JSON] = [] for element in array { guard let json = JSON(element) else { return nil } jsonArray.append(json) } self.init(jsonArray) } public init(_ number: NSNumber) { if type(of: number) == NSNumber.typeOfBooleanNumber { self.init(number.boolValue) } else { self = .number(number) } } public init(_ value: Int) { self = .number(NSNumber(value: value)) } public init(_ value: Int8) { self = .number(NSNumber(value: value)) } public init(_ value: Int16) { self = .number(NSNumber(value: value)) } public init(_ value: Int32) { self = .number(NSNumber(value: value)) } public init(_ value: Int64) { self = .number(NSNumber(value: value)) } public init(_ value: UInt) { self = .number(NSNumber(value: value)) } public init(_ value: UInt8) { self = .number(NSNumber(value: value)) } public init(_ value: UInt16) { self = .number(NSNumber(value: value)) } public init(_ value: UInt32) { self = .number(NSNumber(value: value)) } public init(_ value: UInt64) { self = .number(NSNumber(value: value)) } public init(_ value: Double) { self = .number(NSNumber(value: value)) } public init(_ value: Float) { self = .number(NSNumber(value: value)) } public init(_ string: String) { self = .string(string) } public init(_ bool: Bool) { self = bool ? .true : . false } public init(_ null: NSNull) { self = .null } public init?(_ value: Any) { switch value { case let object as [String: JSON]: self.init(object) case let dictionary as [String: Any]: self.init(dictionary) case let array as [JSON]: self.init(array) case let array as [Any]: self.init(array) case let number as NSNumber: self.init(number) case let string as String: self.init(string) case let null as NSNull: self.init(null) default: return nil } } } extension NSNumber { fileprivate static let typeOfBooleanNumber = type(of: NSNumber(value: true)) } // MARK: - Literals extension JSON: ExpressibleByDictionaryLiteral {} extension JSON: ExpressibleByArrayLiteral {} extension JSON: ExpressibleByIntegerLiteral {} extension JSON: ExpressibleByFloatLiteral {} extension JSON: ExpressibleByStringLiteral {} extension JSON: ExpressibleByBooleanLiteral {} extension JSON: ExpressibleByNilLiteral {} extension JSON { public init(dictionaryLiteral elements: (String, JSON)...) { self.init(Dictionary(uniqueKeysWithValues: elements)) } public init(arrayLiteral elements: JSON...) { self.init(elements) } public init(integerLiteral value: Int) { self.init(value) } public init(floatLiteral value: Double) { self.init(value) } public init(stringLiteral value: String) { self.init(value) } public init(booleanLiteral value: Bool) { self.init(value) } public init(nilLiteral: ()) { self = .null } } // MARK: - Properties extension JSON { public var isObject: Bool { switch self { case .object: return true default: return false } } public var object: [String: JSON]? { switch self { case .object(let object): return object default: return nil } } public var isArray: Bool { switch self { case .array: return true default: return false } } public var array: [JSON]? { switch self { case .array(let array): return array default: return nil } } public var isNumber: Bool { switch self { case .number: return true default: return false } } public var number: NSNumber? { switch self { case .number(let number): return number default: return nil } } public var isString: Bool { switch self { case .string: return true default: return false } } public var string: String? { switch self { case .string(let string): return string default: return nil } } public var isTrue: Bool { switch self { case .true: return true default: return false } } public var isFalse: Bool { switch self { case .false: return true default: return false } } public var isNull: Bool { switch self { case .null: return true default: return false } } } // MARK: - Subscripts extension JSON { public subscript(key: String) -> JSON? { switch self { case .object(let object): return object[key] default: return nil } } public subscript(index: Int) -> JSON? { switch self { case .array(let array): return array[index] default: return nil } } } // MARK: - CustomStringConvertible extension JSON: CustomStringConvertible { public var description: String { switch self { case .string(let string): return "string(\"\(string)\")" case .number(let number): return "number(\(number))" case .object(let object): return "object(\(object))" case .array(let array): return "array(\(array))" case .true: return "true" case .false: return "false" case .null: return "null" } } }
true
c00f19c491dbbea516bfa8781595c99ce76b1893
Swift
2019-DEV-198/TicTacToe
/TicTacToeTests/UIViewTests.swift
UTF-8
3,132
2.890625
3
[]
no_license
// // UIViewTests.swift // TicTacToeTests // // Created by 2019_DEV_198 on 30/09/2019. // Copyright © 2019 2019_DEV_198. All rights reserved. // import XCTest @testable import TicTacToe class UIViewTests: XCTestCase { var view: UIView! override func setUp() { view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) } func testTapTranslatesToPosition() { let game = TicTacToeTests.newGame let position0 = view.gamePosition(for: CGPoint(x: 0, y: 0), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position0, 0) let position1 = view.gamePosition(for: CGPoint(x: 150, y: 50), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position1, 1) let position2 = view.gamePosition(for: CGPoint(x: 299, y: 99), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position2, 2) let position3 = view.gamePosition(for: CGPoint(x: 0, y: 150), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position3, 3) let position4 = view.gamePosition(for: CGPoint(x: 150, y: 150), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position4, 4) let position5 = view.gamePosition(for: CGPoint(x: 299, y: 150), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position5, 5) let position6 = view.gamePosition(for: CGPoint(x: 50, y: 250), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position6, 6) let position7 = view.gamePosition(for: CGPoint(x: 150, y: 201), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position7, 7) let position8 = view.gamePosition(for: CGPoint(x: 299, y: 299), sizeX: game.width, sizeY: game.height) XCTAssertEqual(position8, 8) let outside = view.gamePosition(for: CGPoint(x: 0, y: 400), sizeX: game.width, sizeY: game.height) XCTAssertNil(outside) } func testNewGameRendersNoSubviews() { let newGame = TicTacToeTests.newGame let subviews = view.renderMoves(game: newGame) XCTAssertTrue(subviews.isEmpty) } func testMovesRenderToSubviews() { guard let game = TicTacToeTests.newGame .add(move: Move(player: .x, position: 0))? .add(move: Move(player: .o, position: 4))? .add(move: Move(player: .x, position: 8)) else { XCTFail() return } let positions = getPositionsFromRenderedGame(game) XCTAssertEqual(positions, [0, 4, 8]) } func testFullGameRendersToSubviews() { let positions = getPositionsFromRenderedGame(TicTacToeTests.fullGame) XCTAssertEqual(positions, [0, 1, 2, 3, 4, 5, 6, 7, 8]) } private func getPositionsFromRenderedGame(_ game: GameProtocol) -> [Int] { let subviews = view.renderMoves(game: game) return subviews.compactMap { guard let position = view.gamePosition(for: $0.center, sizeX: game.width, sizeY: game.height) else { return nil } return position } } }
true
b904b199e1021c78ea2ff1f2e5e127633118a4dd
Swift
kyung415/UniversityRideShare
/UniversityRideShare/DriverPostViewController.swift
UTF-8
2,196
2.625
3
[]
no_license
// // DriverPostViewController.swift // UniversityRideShare // // Created by Kyung Lee on 12/18/16. // Copyright © 2016 Kyung Lee. All rights reserved. // import UIKit import FirebaseDatabase class DriverPostViewController: UIViewController { var userID2 = "" var ref : FIRDatabaseReference! @IBOutlet weak var dateOfRide: UITextField! @IBOutlet weak var fromLocation: UITextField! @IBOutlet weak var toLocation: UITextField! @IBOutlet weak var roundTrip: UITextField! @IBOutlet weak var costOfTrip: UITextField! @IBOutlet weak var pickupLocation: UITextField! @IBOutlet weak var dropOffLocation: UITextField! @IBOutlet weak var numOfSeats: UITextField! @IBOutlet weak var timeOfPickup: UITextField! override func viewDidLoad() { super.viewDidLoad() print("UserID2: ") print(userID2) //gets everything from the database ref = FIRDatabase.database().reference() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func postRideButtonPressed(sender: AnyObject) { let hi : String = "hi" let entry = ["User": self.userID2, "Date": self.dateOfRide.text!, "From Location": self.fromLocation.text!, "To Location": self.toLocation.text!, "Round Trip": self.roundTrip.text!, "Cost of Trip": self.costOfTrip.text!, "Pickup Location": self.pickupLocation.text!, "Dropoff Location": self.dropOffLocation.text!, "Number of Seats": self.numOfSeats.text!, "Pickup Time": self.timeOfPickup.text!] var myString = String(arc4random()) self.ref.child("Driver Post").child(myString).setValue(entry) } /* // 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
73aa977d6fd1223851b0168a21f85ac87673981a
Swift
hslightnin/FlowCharts
/Geometry/BezierCurve.swift
UTF-8
530
3.25
3
[]
no_license
// // BezierCurve.swift // FlowCharts // // Created by Alexandr Kozlov on 02/06/2017. // Copyright © 2017 Brown Coats. All rights reserved. // import Foundation public protocol BezierCurve { var point1: Point { get } var point2: Point { get } func point(at t: Double) -> Point func split(at t: Double) -> (BezierCurve, BezierCurve) func intersections(with line: Line, extended: Bool) -> [Double] } public extension BezierCurve { subscript(t: Double) -> Point { return point(at: t) } }
true
b8b8b4602e5816fff008826b11f0154ab68fdb2e
Swift
lexxanderdream/laudo
/Sources/Laudo/Table View/Temp/Sections/TableViewSection.swift
UTF-8
1,632
2.75
3
[]
no_license
// // File.swift // // // Created by Alexander Zhuchkov on 03.06.2020. // import UIKit /* @available(iOS 13.0, *) open class TableViewSection<Item: Hashable, TableViewCell: UITableViewCell>: BaseTableViewSection { // MARK: - Types public typealias LayoutConfigurator = ((NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection) public typealias CellConfigurator = (Item, TableViewCell) -> Void // MARK: - Internal Properties private let cellIdentifier = String(describing: TableViewCell.self) private let cellConfigurator: CellConfigurator // MARK: - Initialization public init(cell: @escaping CellConfigurator) { self.cellConfigurator = cell } // MARK: - Overrides open override func registerCells(in tableView: UITableView) { tableView.register(TableViewCell.self, forCellReuseIdentifier: cellIdentifier) } open override func cell(for item: AnyHashable, at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell? { guard let item = item as? Item else { return nil } guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TableViewCell else { return nil } cellConfigurator(item, cell) return cell } } @available(iOS 13.0, *) public extension TableViewSection where TableViewCell: ConfigurableCell, TableViewCell.Item == Item { convenience init(a: Int = 0) { // Create default cell configurator self.init(cell: { (item, cell) in cell.configure(with: item) }) } } */
true
c1907eec39863a6fe90ce9856d566111602a2fef
Swift
piggogo0629/FoodPin
/FoodPin/Restaurant.swift
UTF-8
859
2.71875
3
[]
no_license
// // File.swift // FoodPin // // Created by Ollie on 2016/9/25. // Copyright © 2016年 Ollie. All rights reserved. // /* import Foundation import CoreData class Restaurant: NSManagedObject { @NSManaged var name: String @NSManaged var type: String @NSManaged var location: String @NSManaged var image: Data? @NSManaged var phoneNumber: String? @NSManaged var isVisited: NSNumber? @NSManaged var rating: String? /* init() { } init(name: String, type: String, location: String, phoneNumber: String, image: String, isVisited: Bool, rating: String = "") { self.name = name self.type = type self.location = location self.phoneNumber = phoneNumber self.image = image self.isVisited = isVisited self.rating = rating } */ } */
true
548228839e284f0b1e1aecf8fa093c5b81c9fff1
Swift
fortmarek/ReactantUI
/Sources/Tokenizer/Layout/Constraints/Constraint.swift
UTF-8
3,697
2.703125
3
[ "MIT" ]
permissive
// // Constraint.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation private func +=(lhs: inout [String], rhs: String) { lhs.append(rhs) } public struct Constraint { public var field: String? public var attribute: LayoutAttribute public var type: ConstraintType public var relation: ConstraintRelation public var priority: ConstraintPriority public var anchor: LayoutAnchor { return attribute.anchor } public init(field: String?, attribute: LayoutAttribute, type: ConstraintType, relation: ConstraintRelation, priority: ConstraintPriority) { self.field = field self.attribute = attribute self.type = type self.relation = relation self.priority = priority } public static func constraints(name: String, attribute: XMLAttribute) throws -> [Constraint] { let layoutAttributes = try LayoutAttribute.deserialize(name) let tokens = Lexer.tokenize(input: attribute.text) return try layoutAttributes.flatMap { try ConstraintParser(tokens: tokens, layoutAttribute: $0).parse() } } func serialize() -> XMLSerializableAttribute { var value = [] as [String] if let field = field { value += "\(field) =" } if relation != .equal { value += ":\(relation.serialized)" } switch type { case .constant(let constant): value += "\(constant)" case .targeted(let target, let targetAnchor, let multiplier, let constant): var targetString: String switch target { case .field(let field): targetString = "\(field)" case .layoutId(let layoutId): targetString = "id:\(layoutId)" case .parent: targetString = "super" case .this: targetString = "self" case .safeAreaLayoutGuide: if #available(iOS 11.0, tvOS 11.0, *) { targetString = "safeAreaLayoutGuide" } else { targetString = "fallback_safeAreaLayoutGuide" } } if targetAnchor != anchor && attribute != .before && attribute != .after { targetString += ".\(targetAnchor.description)" } value += targetString if multiplier != 1 { if multiplier > 1 { value += "multiplied(by: \(multiplier))" } else { value += "divided(by: \(1 / multiplier))" } } if constant != 0 { if case .parent = target, constant > 0 || attribute.insetDirection < 0 { value += "inset(by: \(constant * attribute.insetDirection))" } else { value += "offset(by: \(constant))" } } } if priority != ConstraintPriority.required { value += "@\(priority.serialized)" } return XMLSerializableAttribute(name: anchor.description, value: value.joined(separator: " ")) } } extension Constraint: Equatable { public static func ==(lhs: Constraint, rhs: Constraint) -> Bool { return lhs.field == rhs.field && lhs.attribute == rhs.attribute && lhs.priority == rhs.priority && lhs.relation == rhs.relation && lhs.type == rhs.type } }
true
aa06699e6375e1a94ba78f199d7131026f48294d
Swift
ahmedhafez-iws/swiftUIExample
/swiftUIExample/MVVM/SideMenu/MenuView.swift
UTF-8
1,541
3.015625
3
[]
no_license
// // MenuView.swift // swiftUIExample // // Created by user174699 on 7/9/20. // Copyright © 2020 user174699. All rights reserved. // import SwiftUI struct MenuView: View { var closeMenuClosure: () -> Void var body: some View { VStack(alignment: .leading) { Image("ic_close_side_menu") .onTapGesture { self.closeMenuClosure() } .padding(.top, 50) .padding(.bottom, -50) Spacer() HStack { Image(systemName: "person") .imageScale(.large) Text("Profile") .font(.headline) } HStack { Image(systemName: "envelope") .imageScale(.large) Text("Messages") .font(.headline) } .padding(.top, 30) HStack { Image(systemName: "gear") .imageScale(.large) Text("Settings") .font(.headline) } .padding(.top, 30) Spacer() } .padding() .frame(maxWidth: .infinity, alignment: .leading) .background(Color.clear) .foregroundColor(Color.white) .edgesIgnoringSafeArea(.all) } } struct MenuView_Previews: PreviewProvider { static var previews: some View { MenuView(closeMenuClosure: { }) } }
true
44fa44cb3ef62edf07e3d8cc6d2030dacb930fcc
Swift
oobii/PercistencePractice.playground
/Contents.swift
UTF-8
2,476
3.3125
3
[]
no_license
//: Playground - noun: a place where people can play // how to encode and decode model objects //: Playground - noun: a place where people can play // how to encode and decode model objects import UIKit import Foundation var str = "Hello, playground" class Note: NSObject,NSCoding { let title: String let text: String let timestamp: Date init(title:String, text: String, timestamp: Date){ self.title = title self.text = text self.timestamp = timestamp } // impl NSCoding protocol func encode(with aCoder: NSCoder){ aCoder.encode(title, forKey: "title") aCoder.encode(text, forKey: "text") aCoder.encode(timestamp, forKey: "timestamp") } // This is convinience initializer // impl NSCoding protocol convenience required init?(coder aDecoder: NSCoder) { guard let title = aDecoder.decodeObject(forKey: "title") as? String, let text = aDecoder.decodeObject(forKey: "text") as? String, let timestamp = aDecoder.decodeObject(forKey: "timestamp") as? Date else { return nil } self.init(title: title, text: text, timestamp: timestamp) } override var description: String { return "Note(title: \"\(title)\")" } } let note = Note(title: "My first note", text: "Notes are valuable", timestamp: Date()) let archivedNote = NSKeyedArchiver.archivedData(withRootObject: note) print("\(note)") NSKeyedUnarchiver.unarchiveObject(with: archivedNote) as? Note // The 4 lines below doesn't work in Playground var documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first! print("\(documentDirectory)") let archiveURL = documentDirectory.appendingPathComponent("notes") print("\(archiveURL)") // This works in Playground in XCode8 let archivedNote2 = NSKeyedArchiver.archiveRootObject(note, toFile: "nnn") let unarchvedNote = NSKeyedUnarchiver.unarchiveObject(withFile: "nnn") as? Note let note1 = Note(title: "My first note", text: "Notes are valuable", timestamp: Date()) let note2 = Note(title: "My second note", text: "Notes are valuable", timestamp: Date()) let note3 = Note(title: "My third note", text: "Notes are valuable", timestamp: Date()) var notes = [note1, note2, note3] let archivedNotes = NSKeyedArchiver.archiveRootObject(notes, toFile: "notes") let unarchvedNotes = NSKeyedUnarchiver.unarchiveObject(withFile: "notes") as? [Note]
true
1bd002b3455f71c915ea586fd882ce7e6fd37786
Swift
ULT-2016S1-IOS2/CourseFantastic
/CourseFantastic/EnrolmentsTableViewController.swift
UTF-8
16,190
2.5625
3
[]
no_license
// // EnrolmentsTableViewController.swift // CourseFantastic // // Created by Lee Kelly on 22/04/2016. // Copyright © 2016 LMK Technologies. All rights reserved. // import UIKit import CoreData import SwiftyJSON class EnrolmentsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, APIServiceDelegate { var courses: [Course] = [] var fetchedResultsController: NSFetchedResultsController! var courseDeliveryId: Int! var enrolmentId: Int! var course: Course! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() // Allow auto resizing of tableview row tableView.estimatedRowHeight = 60.0 tableView.rowHeight = UITableViewAutomaticDimension // Core Data if let managedObjectContext = AppDelegate.instance()?.managedObjectContext { fetchedResultsController = NSFetchedResultsController(fetchRequest: Course.fetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() courses = fetchedResultsController.fetchedObjects as! [Course] } catch { print(error) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return courses.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! EnrolmentsTableViewCell let course = courses[indexPath.row] // Configure the cell... cell.colourView.backgroundColor = UIColor(red: 0, green: 128.0/255.0, blue: 1, alpha: 1.0) // TODO: Implement Colour Handler cell.courseLabel.text = course.name return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { // Delete Button let deleteAction = UITableViewRowAction(style: .Destructive, title: "Withdraw", handler: { (action, indexPath) -> Void in // Attempt withdraw from course self.course = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Course self.attemptWithdraw(self.course) }) // deleteAction.backgroundColor = UIColor(red: 202.0/255.0, green: 202.0/255.0, blue: 203.0/255.0, alpha: 1.0) return [deleteAction] } /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Fetched Results Controller func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: if let _newIndexPath = newIndexPath { tableView.insertRowsAtIndexPaths([_newIndexPath], withRowAnimation: .Fade) } case .Delete: if let _indexPath = indexPath { tableView.deleteRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade) } case .Update: if let _indexPath = indexPath { tableView.reloadRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade) } default: tableView.reloadData() } // Sync our array with the fetchedResultsController courses = controller.fetchedObjects as! [Course] } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } // MARK: - Barcode func barcodeCaptured(barcode: String) { print("barcodeCaptured: \(barcode)") courseDeliveryId = Int(barcode) do { if let student = try StudentService.getStudent() { ActivityIndicator().show() let apiService = APIService() apiService.delegate = self apiService.postEnrolmentEnrol(student, courseDeliveryId: courseDeliveryId) } } catch { displayAlert("Oops!", message: "We couldn't load your profile.") } } // MARK: - APIService Calls func fetchCourse() { ActivityIndicator().show() let apiService = APIService() apiService.delegate = self apiService.getCourse(courseDeliveryId) } func fetchTimetable() { ActivityIndicator().show() let apiService = APIService() apiService.delegate = self apiService.getTimetable(forCourseId: courseDeliveryId) } func attemptWithdraw(course: Course) { do { if let student = try StudentService.getStudent() { ActivityIndicator().show() let apiService = APIService() apiService.delegate = self apiService.postEnrolmentWithdraw(student, enrolmentId: course.enrolmentId.integerValue) } } catch { displayAlert("Oops!", message: "We couldn't load your profile.") } } // MARK: - APIService Delegate func apiServiceResponse(responseType: APIServiceResponseType, error: String?, json: JSON?) { ActivityIndicator().hide() if let error = error { displayAlert("Oops!", message: error) return } if let json = json { switch responseType { case .POSTEnrol: handlePostEnrol(json) case .GETCourse: handleGetCourse(json) case .GETTimetable: handleGetTimetable(json) case .POSTWithdraw: handlePostWithdraw() default: print(json.description) } } } // MARK: - Handle Enrolment func handlePostEnrol(json: JSON) { /* { "CourseDeliveryId" : 4, "EnrolmentId" : 22, "StudentId" : "12345" } */ guard let id = json["EnrolmentId"].int else { displayAlert("Oops!", message: "We couldn't process the information received.") return } enrolmentId = id fetchCourse() } func handlePostWithdraw() { do { try CourseService.removeCourse(course) } catch let error as NSError { displayAlert("Oops!", message: error.localizedDescription) } } // MARK: - Handle Course func handleGetCourse(json: JSON) { do { let course = try CourseService.createCourse(json) course.enrolmentId = enrolmentId course.id = courseDeliveryId // TODO: change API to include id self.course = course // try managedObjectContext.save() fetchTimetable() } catch let error as NSError { displayAlert("Oops!", message: error.localizedDescription) } } // MARK: - Handle Timetable func handleGetTimetable(json: JSON) { /* [ { "Version" : "1", "Subjects" : [ { "Subject" : { "Code" : "SAD", "Name" : "Advanced System Analysis & Design", "Description" : "Learn advanced concepts in Analysis & Design. Software architecture fundamentals and contemporary software development methodologies delivered in the context of your major project." }, "Timetable" : [ { "Start" : "2016-05-23T13:00:00", "Location" : "GG.27", "End" : "2016-05-23T17:00:00", "Id" : 325 }, { "Start" : "2016-05-30T13:00:00", "Location" : "GG.27", "End" : "2016-05-30T17:00:00", "Id" : 326 } ] }, { "Subject" : { "Code" : "SD", "Name" : "Software Development", "Description" : "Learn advanced concepts in Software Development, working on a real world project using the latest technologies." }, "Timetable" : [ { "Start" : "2016-05-19T09:00:00", "Location" : "GG.28", "End" : "2016-05-19T13:00:00", "Id" : 340 }, { "Start" : "2016-05-19T14:00:00", "Location" : "GG.28", "End" : "2016-05-19T18:00:00", "Id" : 356 } ] } ] } ] */ guard let subjects = json[0]["Subjects"].array else { displayAlert("Oops!", message: "We couldn't process the information received.") return } do { for item in subjects { let subject = try SubjectService.createSubject(item) guard let events = item["Timetable"].array else { displayAlert("Oops!", message: "We couldn't process the information received.") return } for event in events { let subjectDelivery = try SubjectDeliveryService.createSubjectDelivery(event) subject.addTimetableItem(subjectDelivery) } course.addSubject(subject) } guard let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext else { throw NSError(domain: "CourseFantastic", code: -99, userInfo: [NSLocalizedDescriptionKey: "We couldn't load the database."]) } try managedObjectContext.save() print("Successfully Saved the Course Structure") integrateCalendar() } catch let error as NSError { displayAlert("Oops!", message: error.localizedDescription) } } // MARK: - Calendar Integration func integrateCalendar() { let calendarService = CalendarService() calendarService.attemptAccess({ do { let calendar = try calendarService.createCalendar() // returns existing calendar if already exists try calendarService.createEvents(inCalendar: calendar, forCourse: self.course) guard let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext else { throw NSError(domain: "CourseFantastic", code: -99, userInfo: [NSLocalizedDescriptionKey: "We couldn't load the database."]) } try managedObjectContext.save() } catch let error as NSError { self.displayAlert("Oops!", message: error.localizedDescription) } }) } // MARK: - Error Alert func displayAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } // 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. if let identifier = segue.identifier { if identifier == "scanBarcode" { // Get the new view controller using segue.destinationViewController let vc = segue.destinationViewController as! BarcodeViewController vc.delegate = self } } } */ @IBAction func unwindToEnrolments(segue: UIStoryboardSegue) { if let vc = segue.sourceViewController as? BarcodeViewController { if let barcode = vc.scannedBarcode { barcodeCaptured(barcode) } } } }
true
176707ff4aacd88312813785f083885bccf0a47d
Swift
aPuYue/ioscreator
/IOS12SpriteKitScenesTutorial/IOS12SpriteKitScenesTutorial/SecondScene.swift
UTF-8
1,264
2.953125
3
[ "MIT" ]
permissive
// // SecondScene.swift // IOS12SpriteKitScenesTutorial // // Created by Arthur Knopper on 03/10/2018. // Copyright © 2018 Arthur Knopper. All rights reserved. // import UIKit import SpriteKit class SecondScene: SKScene { override func didMove(to view: SKView) { backgroundColor = SKColor(red: 0.15, green:0.15, blue:0.3, alpha: 1.0) let button = SKSpriteNode(imageNamed: "previousbutton.png") button.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) button.name = "previousButton" self.addChild(button) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let location = touch.location(in: self) let nodesarray = nodes(at: location) for node in nodesarray { if node.name == "previousButton" { let firstScene = GameScene(fileNamed: "GameScene") let transition = SKTransition.doorsCloseHorizontal(withDuration: 0.5) firstScene?.scaleMode = .aspectFill scene?.view?.presentScene(firstScene!, transition: transition) } } } } }
true
5b86db4868c68a4787d439dde4d1e14667989a64
Swift
ravisharmaa/TinderAndRealTimeChat
/RealtimeChatAndTinderClone/ViewController.swift
UTF-8
7,903
2.71875
3
[]
no_license
import UIKit class ViewController: UIViewController { //MARK:- Properties lazy var createAccountLabel: UILabel = { let label = UILabel() return label }() lazy var facebookButton: UIButton = { let button = UIButton() button.setTitle("Sign In With Facebook", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 18) button.setImage(#imageLiteral(resourceName: "Facebook"), for: .normal) button.backgroundColor = UIColor(red: 58/255, green: 85/255, blue: 159/255, alpha: 1.0) button.layer.cornerRadius = 8 button.clipsToBounds = true button.imageView?.backgroundColor = UIColor(red: 58/255, green: 85/255, blue: 159/255, alpha: 1.0) button.imageView?.contentMode = .scaleAspectFit button.tintColor = .white button.imageEdgeInsets = UIEdgeInsets(top: 12, left: -15, bottom: 12, right: 0) return button }() lazy var googleButton: UIButton = { let button = UIButton() button.setTitle("Sign In With Google", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 18) button.setImage(#imageLiteral(resourceName: "Google"), for: .normal) button.backgroundColor = UIColor(red: 223/255, green: 74/255, blue: 50/255, alpha: 1.0) button.layer.cornerRadius = 8 button.clipsToBounds = true button.imageView?.contentMode = .scaleAspectFit button.tintColor = .white button.imageEdgeInsets = UIEdgeInsets(top: 12, left: -35, bottom: 12, right: 0) return button }() lazy var orLabel: UILabel = { let label = UILabel() label.text = "Or" label.font = UIFont.boldSystemFont(ofSize: 16) label.textColor = UIColor(white: 0, alpha: 0.45) label.textAlignment = .center return label }() lazy var createAccount: UIButton = { let button = UIButton() button.backgroundColor = .black button.setTitle("Create a new account", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18) button.layer.cornerRadius = 8 button.addTarget(self, action: #selector(showSignupView), for: .touchUpInside) return button }() lazy var termsOfUseLabel: UILabel = { let label = UILabel() label.textAlignment = .center return label }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground setupUI() } func setupUI() { setupTitleLabel() setupTermsLabel() NSLayoutConstraint.activate([ createAccountLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50), createAccountLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), createAccountLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), facebookButton.topAnchor.constraint(equalTo: createAccountLabel.bottomAnchor, constant: 40), facebookButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), facebookButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), facebookButton.bottomAnchor.constraint(equalTo: googleButton.topAnchor, constant: -25), facebookButton.heightAnchor.constraint(equalToConstant: 50), googleButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), googleButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), googleButton.bottomAnchor.constraint(equalTo: orLabel.topAnchor, constant: -25), googleButton.heightAnchor.constraint(equalToConstant: 50), orLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor, constant: 0), orLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor, constant: 0), orLabel.bottomAnchor.constraint(equalTo: createAccount.topAnchor, constant: -25), createAccount.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), createAccount.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), createAccount.heightAnchor.constraint(equalToConstant: 50), createAccount.bottomAnchor.constraint(equalTo: termsOfUseLabel.topAnchor, constant: -25), termsOfUseLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), termsOfUseLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), ]) } func setupTitleLabel() { let title = "Create a new account" let subtitle = "\n\n This is the subtitle which was meant to be a subtitle and ended up being a subtitle which to much more to be a subtitle." let attributedText = NSMutableAttributedString(string: title, attributes: [ NSAttributedString.Key.font: UIFont.init(name: "Didot", size: 28)!, NSAttributedString.Key.foregroundColor : UIColor.black, ]) let attributedSubtitle = NSMutableAttributedString(string: subtitle, attributes: [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(white: 0, alpha: 0.45) ]) attributedText.append(attributedSubtitle) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 5 attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length)) createAccountLabel.numberOfLines = 0 createAccountLabel.lineBreakMode = .byCharWrapping createAccountLabel.attributedText = attributedText [createAccountLabel, facebookButton, googleButton, orLabel, createAccount, termsOfUseLabel].forEach { (customViews) in view.addSubview(customViews) customViews.translatesAutoresizingMaskIntoConstraints = false } } func setupTermsLabel() { let attributedTermText = NSMutableAttributedString(string: "By Clicking the terms of service you agree to ", attributes: [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor : UIColor(white: 0, alpha: 0.65), ]) let attributedTermBoldText = NSMutableAttributedString(string: "Terms Of Service", attributes: [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor : UIColor(white: 0, alpha: 0.65), ]) attributedTermText.append(attributedTermBoldText) termsOfUseLabel.attributedText = attributedTermText termsOfUseLabel.numberOfLines = 0 } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: true) } @objc func showSignupView() { // let signupVc = SignupViewController() // signupVc.modalPresentationStyle = .fullScreen // present(signupVc, animated: true, completion: nil) self.navigationController?.pushViewController(SignupViewController(), animated: true) } }
true
8b238d4e0ad9884674a1364525164815208ee92a
Swift
jeongjaein/giphy-clone
/GiphyClone/Tabbar/SearchTab/SearchMain/SearchMainPresenter.swift
UTF-8
3,139
2.75
3
[]
no_license
// // SearchMainPresenter.swift // GiphyClone // // Created by 정재인 on 2021/04/20. // import Foundation class SearchMainPresenter: SearchMainPresenterProtocol { weak var view: SearchMainViewProtocol? var interactor: SearchMainInteractorInputProtocol? var wireFrame: SearchMainWireFrameProtocol? var listSwitch = false var searchSuggesion: [String] = [] var recentSearhes: [String] = [] var autoCompletes: [AutoComplete] = [] func viewDidLoad() { view?.showLoading() interactor?.fetchInitialElements() } // MARK: 상위 테이블뷰 리스트 func numberOfList() -> Int{ return listSwitch ? autoCompletes.count : searchSuggesion.count } func didSelectOfList(_ indexPath: IndexPath) { let keyword = listSwitch ? autoCompletes[indexPath.row].name : searchSuggesion[indexPath.row] wireFrame?.presentSearchResult(from: view!, keyword) } func itemOfList(_ indexPath: IndexPath) -> (Bool, String) { return (listSwitch, listSwitch ? autoCompletes[indexPath.row].name : searchSuggesion[indexPath.row]) } // MARK: 최근 검색어 관련 func numberOfRecentSearches() -> Int { return recentSearhes.count } func didSelectRecentSearches(_ indexPath: IndexPath) { wireFrame?.presentSearchResult(from: view!, recentSearhes[indexPath.row]) } func itemOfRecentSearches(_ indexPath: IndexPath) -> String { return recentSearhes[indexPath.row] } // MARK: 검색 버튼 탭 func searchKeyword(_ keyword: String) { view?.showLoading() interactor?.checkKeyword(keyword) } // MARK: 검색어 제안 func searchTextFieldChanged(_ keyword: String) { listSwitch = !keyword.isEmpty view?.topTableviewReload(listSwitch ? "Search Suggesion" : "Trending Searches") interactor?.fetchAutoComplete(keyword) } } extension SearchMainPresenter: SearchMainInteractorOutputProtocol { func retrivedSearchSuggesion(_ searchSuggesion: [String]) { self.searchSuggesion = Array(searchSuggesion[0..<5]) view?.topTableviewReload(nil) } func retrievedAutoComplete(_ autoCompletes: [AutoComplete]) { self.autoCompletes = autoCompletes view?.topTableviewReload(nil) } func retrievedRecentSearches(_ searches: [String]) { recentSearhes = searches view?.hideLoading() view?.didReceiveRecentSearches() } func checkKeywordResult(_ result: Bool, _ keyword: String) { if result { recentSearhes.insert(keyword, at: 0) view?.didReceiveRecentSearches() wireFrame?.presentSearchResult(from: view!, keyword) } else { view?.showError() } } func onError() { view?.showError() } }
true
868a9fc9e2ac91712d4d9fdd753f8c7d36a8d912
Swift
nfnunes/WODit
/WODit/MinuteSecondPicker.swift
UTF-8
1,512
2.90625
3
[]
no_license
// // MinuteSecondPicker.swift // WODit // // Created by Nuno on 18/12/2016. // Copyright © 2016 Nuno. All rights reserved. // import UIKit class MinuteSecondPicker: UIPickerView, UIPickerViewDelegate { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var timeSegueLabel: UILabel! let minutes = Array(0...9) let seconds = Array(0...59) var recievedString: String = "" func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 2 } override func numberOfRows(inComponent component: Int) -> Int { //row = [repeatPickerView selectedRowInComponent:0]; var row = pickerView.selectedRow(inComponent: 0) print("this is the pickerView\(row)") if component == 0 { return minutes.count } else { return seconds.count } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { if component == 0 { return String(minutes[row]) } else { return String(seconds[row]) } } override func viewDidLoad() { super.viewDidLoad() timeSegueLabel.text = recievedString } }
true
d1826cb51cde8067c4e15d47caced092dcb404f8
Swift
ioscjf/Feedback
/Feedback/QuestionFinder.swift
UTF-8
2,673
2.640625
3
[]
no_license
// // QuestionFinder.swift // Feedback // // Created by Connor Fitzpatrick on 7/16/17. // Copyright © 2017 Connor Fitzpatrick. All rights reserved. // import Foundation // // ReviewFinder.swift // Feedback // // Created by Connor Fitzpatrick on 7/15/17. // Copyright © 2017 Connor Fitzpatrick. All rights reserved. // import Foundation struct QuestionFinder { var question_id: Int? var shop_id: Int? var question1: String? var question2: String? var question3: String? var question4: String? var question5: String? var star1: Bool? var star2: Bool? var star3: Bool? var star4: Bool? var star5: Bool? var timer: Bool? init?(json: Dictionary<String, AnyObject>) { if let rid = Int((json["question_id"] as? String)!) { self.review_id = rid } else { self.review_id = 0 } if let sid = Int((json["shop_id"] as? String)!) { self.shop_id = sid } else { self.shop_id = 0 } if let q1 = json["question1"] as? String! { self.question1 = q1 } else { self.question1 = "" } if let q2 = json["question2"] as? String! { self.question2 = q2 } else { self.question2 = "" } if let q3 = json["question3"] as? String! { self.question3 = q3 } else { self.question3 = "" } if let q4 = json["question4"] as? String! { self.question4 = q4 } else { self.question4 = "" } if let q5 = json["question5"] as? String! { self.question5 = q5 } else { self.question5 = "" } if let s1 = Bool((json["star1"] as? String)!) { self.star1 = s1 } else { self.star1 = false } if let s2 = Bool((json["star2"] as? String)!) { self.star2 = s2 } else { self.star2 = false } if let s3 = Bool((json["star3"] as? String)!) { self.star3 = s3 } else { self.star3 = false } if let s4 = Bool((json["star4"] as? String)!) { self.star4 = s4 } else { self.star4 = false } if let s5 = Bool((json["star5"] as? String)!) { self.star5 = s5 } else { self.star5 = false } if let t = Bool((json["timer"] as? String)!) { self.timer = t } else { self.timer = false } } }
true
b12a8d4ee782915a18421fe97c7c32d59667ffbe
Swift
dorothyfu/sleepTimer
/sleepTimer/ViewController.swift
UTF-8
6,097
2.515625
3
[]
no_license
// // ViewController.swift // sleepTimer // // Created by Dorothy Fu on 2018-01-15. // Copyright © 2018 Dorothy. All rights reserved. // import UIKit import MediaPlayer extension CGRect { init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) { self.init(x:x, y:y, width:w, height:h) } } extension UIApplication { var isKeyboardPresented: Bool { if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"), self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) { return true } else { return false } } } // MARK: - UIViewController Properties class ViewController: UIViewController, UITextFieldDelegate { // MARK: - IBOutlets @IBOutlet weak var startButton: UIButton! @IBOutlet weak var pauseButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var editBox: UITextField! let button = UIButton(type: UIButtonType.custom) let limitLength = 10 var seconds = 0 var timer = Timer() var isTimerRunning = false var resumeTapped = false // MARK: - IBActions @IBAction func startButtonTapped(_ sender: UIButton) { stringToInt() if seconds == 0 { timerLabel.text = "Please enter a number greater than 0" } else if isTimerRunning == false { if seconds > 86400 { seconds = 86400 } runTimer() self.startButton.isEnabled = false editBox.resignFirstResponder() editBox.text = "" } } @IBAction func pauseButtonTapped(_ sender: UIButton) { if self.resumeTapped == false { timer.invalidate() isTimerRunning = false self.resumeTapped = true self.pauseButton.setTitle("Resume", for: .normal) } else { if isTimerRunning == false { runTimer() } self.resumeTapped = false isTimerRunning = true self.pauseButton.setTitle("Pause", for: .normal) } } @IBAction func resetButtonTapped(_ sender: UIButton) { timer.invalidate() seconds = 0 timerLabel.text = timeString(time: TimeInterval(seconds)) isTimerRunning = false pauseButton.isEnabled = false startButton.isEnabled = true self.pauseButton.setTitle("Pause", for: .normal) self.resumeTapped = false } @objc func runTimer() { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true) isTimerRunning = true pauseButton.isEnabled = true } @objc func updateTimer() { if seconds < 1 { timer.invalidate() // send alert for time's up timerLabel.text = "Turning music off ..." try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient) try? AVAudioSession.sharedInstance().setActive(true) DispatchQueue.main.asyncAfter(deadline: .now()+3.0) { self.seconds = 0 self.timerLabel.text = self.timeString(time: (TimeInterval(self.seconds))) } isTimerRunning = false pauseButton.isEnabled = false startButton.isEnabled = true } else { timerLabel.text = timeString(time: TimeInterval(seconds)) seconds -= 1 } } func timeString(time:TimeInterval) -> String { let hours = Int(time) / 3600 let minutes = Int(time) / 60 % 60 let seconds = Int(time) % 60 return String(format: "%02i:%02i:%02i", hours, minutes, seconds) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = editBox.text else { return true } let newLength = text.count + string.count - range.length return newLength <= limitLength } func stringToInt() { let totalSeconds:Int? = Int(editBox.text!) guard let text = editBox.text, !text.isEmpty else { seconds = 0 return } seconds = totalSeconds! * 60 } // Return button @objc func dismissKeyboard() { view.endEditing(true) } func addDoneButtonOnKeyboard() { let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(0, 0, 320, 50)) doneToolbar.barStyle = UIBarStyle.default let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewController.dismissKeyboard)) var items = [UIBarButtonItem]() items.append(flexSpace) items.append(done) doneToolbar.items = items doneToolbar.sizeToFit() self.editBox.inputAccessoryView = doneToolbar let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } override func viewDidLoad() { super.viewDidLoad() pauseButton.isEnabled = false self.view.backgroundColor = UIColor.black timerLabel.textColor = .white // Return button self.addDoneButtonOnKeyboard() editBox.delegate = self startButton.setTitleColor(UIColor(red:0.12, green:0.30, blue:0.57, alpha:1.0), for: .disabled) pauseButton.setTitleColor(UIColor(red:0.12, green:0.30, blue:0.57, alpha:1.0), for: .disabled) resetButton.setTitleColor(UIColor(red:0.20, green:0.47, blue:0.88, alpha:1.0), for: .disabled) } }
true
fc2e9ee18b1c6ee71ee5e76371ae166f861781c1
Swift
Lxrd-AJ/QuoteBook
/QuoteBook/WatchData.swift
UTF-8
603
2.6875
3
[]
no_license
// // WatchData.swift // QuoteBook // // Created by AJ Ibraheem on 10/11/2015. // Copyright © 2015 The Leaf Enterprise. All rights reserved. // import Foundation class WatchData: NSObject, NSCoding { var quotes:[Quote]! convenience init( quotes:[Quote] ){ self.init() self.quotes = quotes; } required convenience init?(coder aDecoder: NSCoder) { self.init() self.quotes = aDecoder.decodeObjectForKey("quotes") as! [Quote] } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(quotes, forKey: "quotes") } }
true
49d7cf9ade2b0479c08e53613e86ab61e758ca14
Swift
jertje260/MBDM2-IOS
/LocalChat/SettingsViewController.swift
UTF-8
2,548
2.640625
3
[]
no_license
// // SettingsViewController.swift // LocalChat // // Created by User on 08/04/15. // Copyright (c) 2015 Jeroen Broekhuizen. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var UsernameLabel: UILabel! @IBOutlet weak var DisplaynameField: UITextField! @IBOutlet weak var RadiusSlider: UISlider! @IBOutlet weak var SliderLabel: UILabel! @IBOutlet weak var PasswordField: UITextField! @IBOutlet weak var ConfirmPasswordField: UITextField! @IBOutlet weak var ErrorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() loadUserData() } func loadUserData(){ let preferences = NSUserDefaults.standardUserDefaults() UsernameLabel?.text = preferences.stringForKey("Username") DisplaynameField?.text = preferences.stringForKey("Displayname") RadiusSlider?.value = preferences.floatForKey("Radius") SliderLabel.text = preferences.stringForKey("Radius") } @IBAction func Logout(sender: AnyObject) { let preferences = NSUserDefaults.standardUserDefaults() preferences.removeObjectForKey("UserID") preferences.removeObjectForKey("Username") preferences.removeObjectForKey("Displayname") preferences.removeObjectForKey("Radius") preferences.synchronize() performSegueWithIdentifier("Logout", sender: nil) } @IBAction func SaveChanges(sender: AnyObject) { if(PasswordField.text == ConfirmPasswordField.text){ let preferences = NSUserDefaults.standardUserDefaults() preferences.setObject(DisplaynameField.text, forKey: "Displayname") preferences.setObject(Int(RadiusSlider.value), forKey: "Radius") preferences.synchronize() var user = User() user.ID = preferences.stringForKey("UserId") user.userName = preferences.stringForKey("Username") user.displayName = preferences.stringForKey("Displayname") user.radius = preferences.integerForKey("Radius") user.password = PasswordField.text JsonParser.saveUser(user) ErrorLabel.text = "Saved your settings" } else { ErrorLabel.text = "Password and Confirm Password are not the same" } } @IBAction func sliderValueChanged(sender: UISlider) { var currentValue = Int(sender.value) SliderLabel.text = "\(currentValue) m" } }
true
72239bb236dcb905d973ee9772d316f60237c563
Swift
GLaDO8/EmojiMatch
/emojimatcher/Array+Only.swift
UTF-8
252
2.515625
3
[]
no_license
// // Array+Only.swift // flippyCards // // Created by shreyas gupta on 02/06/20. // Copyright © 2020 shreyas gupta. All rights reserved. // import Foundation extension Array{ var only: Element?{ return self.count == 1 ? self.first : nil } }
true
a7c19663c7ac7d7bf338d0c31476c865f7e312af
Swift
qclubfoo/AtlantApps
/AtlantAppReworked/AtlantAppReworked/SettingsViewController.swift
UTF-8
2,387
2.796875
3
[]
no_license
// // SettingsViewController.swift // AtlantAppReworked // // Created by Дмитрий on 08.02.2020. // Copyright © 2020 Дмитрий. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var emailButton: UIButton! @IBOutlet weak var callButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupButton(button: emailButton) setupButton(button: callButton) // Do any additional setup after loading the view. } @IBAction func emailButtonTaped(_ sender: Any) { let alert = UIAlertController(title: "Send email to us", message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: { textField in textField.placeholder = "Input your message here" }) let sendAction = UIAlertAction(title: "Send email", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: { action in alert.dismiss(animated: true, completion: nil) }) alert.addAction(sendAction) alert.addAction(cancelAction) self.present(alert, animated: true) } @IBAction func callButtonTaped(_ sender: Any) { let alert = UIAlertController(title: "Call to us", message: nil, preferredStyle: .alert) let sendAction = UIAlertAction(title: "Call", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: { action in alert.dismiss(animated: true, completion: nil) }) alert.addAction(sendAction) alert.addAction(cancelAction) self.present(alert, animated: true) } func setupButton(button: UIButton) { button.layer.cornerRadius = 10 } /* // 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
34aa4970e1ab4a9f23c7e1506ee6b02e59a751f8
Swift
joaquin-perezbarroso/webService
/WebService.swift
UTF-8
1,515
2.578125
3
[]
no_license
// // WebService.swift // WebServices // // Created by Joaquin Perez on 15/03/2018. // Copyright © 2018 Joaquin Perez. All rights reserved. // import Foundation class NetworkObject { let urlString = "https://devops.jovaz21.tekisware.com/nodepop/apiv1" func postUser(email:String = "guest@foo.bar",password:String = "guest") { let url = URL(string: urlString + "/users/authenticate") var request = URLRequest(url: url!) request.httpMethod = "POST" let httpBody = ["email":email,"password":password] let body = try! JSONSerialization.data(withJSONObject: httpBody, options: []) request.httpBody = body request.setValue("application/json", forHTTPHeaderField: "Content-Type") let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in let httpResponse = response as! HTTPURLResponse if httpResponse.statusCode == 200 { let dict = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] if let result = dict!["result"] as! [String:String]? { if let token = result["token"]{ print(token) } } } } dataTask.resume() } }
true
3b1382a34ee3545404f294e5a020449b85bddf2f
Swift
JohnnyApps/Shreks
/Shreks/BlackViewController.swift
UTF-8
2,268
2.59375
3
[ "MIT" ]
permissive
// // BlackViewController.swift // Shreks // // Created by Jan Smolinski on 02/05/2018. // Copyright © 2018 Jan Smolinski. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class BlackViewController: UIViewController { var audioPlayer: AVAudioPlayer! @IBOutlet weak var TimeLabel: UILabel! var timer = Timer() var seconds = 11 var text = "" var data = NSData() @objc func Clock() { seconds = seconds-1 TimeLabel.text = String(seconds) if seconds == 0 { timer.invalidate() } } override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "holding12", ofType: ".mp3")! let url = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.prepareToPlay() } catch let error as NSError { print(error.debugDescription) } audioPlayer.play() if seconds > 0 { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(BlackViewController.Clock), userInfo: nil, repeats: true) } DispatchQueue.main.asyncAfter(deadline: .now() + 11, execute: { let storyBoardd : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let gameView = storyBoardd.instantiateViewController(withIdentifier: "GameVC") as! GameViewController gameView.modalTransitionStyle = .crossDissolve self.present(gameView, animated:true, completion:nil) }) // Do any additional setup after loading the view. } 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. } */ }
true
62787b256ba5b5083eee1d6ade569f038bbfa942
Swift
vaslee/QuizzesApp
/Quizzes/Quizzes/Controllers/DetailViewController.swift
UTF-8
2,135
2.640625
3
[ "MIT" ]
permissive
// // DetailViewController.swift // Quizzes // // Created by TingxinLi on 2/1/19. // Copyright © 2019 Alex Paul. All rights reserved. // import UIKit class DetailViewController: UIViewController { var detailLabel: String? let detailView = DetailView() public var quiz: Create! override func viewDidLoad() { super.viewDidLoad() detailView.detailCollectionView.dataSource = self detailView.detailCollectionView.delegate = self view.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1) view.addSubview(detailView) self.detailView.detailCollectionView.register(DetailCell.self, forCellWithReuseIdentifier: "DetailCell") } } extension DetailViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return quiz.facts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DetailCell", for: indexPath) as? DetailCell else { return UICollectionViewCell() } cell.detailTitleLabel.text = quiz.quizTitle return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = self.detailView.detailCollectionView.cellForItem(at: indexPath) as? DetailCell else {return} if cell.detailTitleLabel.text == quiz.quizTitle { UIView.transition(with: cell, duration: 1.0, options: [.transitionFlipFromRight], animations: { cell.detailTitleLabel.text = self.quiz.facts[indexPath.row] }) } else { UIView.transition(with: cell, duration: 1.0, options: [.transitionFlipFromRight], animations: { cell.detailTitleLabel.text = self.quiz.quizTitle }) } } }
true
d79b3bac4b664d3e9447f13b76313fd64a8eed25
Swift
DariusVil/PixPik
/PixPik/Screens/CameraView.swift
UTF-8
6,363
2.609375
3
[]
no_license
import UIKit protocol CameraViewDelegate: class { func shutterTapped(in: CameraView) func switchTapped(in: CameraView) func libraryTapped(in: CameraView) func pixelizationLevelIncreased(in: CameraView) func pixelizationLevelDecreased(in: CameraView) } final class CameraView: UIView { weak var delegate: CameraViewDelegate? private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 12 return imageView }() private lazy var shutterButtonImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "appbar.location.circle")) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(shutterTapped)) imageView.addGestureRecognizer(tapGesture) return imageView }() private lazy var cameraSwitchButtonImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "appbar.camera.switch")) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true; let tapGesture = UITapGestureRecognizer(target: self, action: #selector(switchTapped)) imageView.addGestureRecognizer(tapGesture) return imageView }() private lazy var libraryButtonImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "appbar.image.gallery")) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true; let tapGesture = UITapGestureRecognizer(target: self, action: #selector(libraryTapped)) imageView.addGestureRecognizer(tapGesture) return imageView }() private lazy var buttonStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .equalSpacing stackView.contentMode = .scaleAspectFit stackView.axis = .horizontal return stackView }() private lazy var transparentView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.init(displayP3Red: 0, green: 0, blue: 0, alpha: 0.4) view.layer.cornerRadius = 12 view.clipsToBounds = true view.layer.maskedCorners = [ .layerMinXMaxYCorner, .layerMaxXMaxYCorner] return view }() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(with image: UIImage) { imageView.image = image } private func setup() { backgroundColor = .black setupSwipeGestures() addImageView() addTransparentView() addButtons() } private func setupSwipeGestures() { let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGestures)) swipeRight.direction = UISwipeGestureRecognizer.Direction.right addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGestures)) swipeLeft.direction = UISwipeGestureRecognizer.Direction.left addGestureRecognizer(swipeLeft) } private func addTransparentView() { addSubview(transparentView) NSLayoutConstraint.activate([ transparentView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), transparentView.leadingAnchor.constraint(equalTo: imageView.leadingAnchor), transparentView.trailingAnchor.constraint(equalTo: imageView.trailingAnchor), transparentView.heightAnchor.constraint(equalToConstant: 80) ]) } private func addImageView() { addSubview(imageView) NSLayoutConstraint.activate([ imageView.centerXAnchor.constraint(equalTo: centerXAnchor), imageView.centerYAnchor.constraint(equalTo: centerYAnchor), imageView.widthAnchor.constraint(equalTo: widthAnchor), imageView.heightAnchor.constraint(equalTo: widthAnchor, multiplier: 4/3) ]) } private func addButtons() { addSubview(buttonStackView) buttonStackView.addArrangedSubview(libraryButtonImageView) buttonStackView.addArrangedSubview(shutterButtonImageView) buttonStackView.addArrangedSubview(cameraSwitchButtonImageView) NSLayoutConstraint.activate([ buttonStackView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), buttonStackView.leadingAnchor.constraint(equalTo: leadingAnchor), buttonStackView.trailingAnchor.constraint(equalTo: trailingAnchor), buttonStackView.heightAnchor.constraint(equalToConstant: 80) ]) } @objc private func shutterTapped(gesture: UIGestureRecognizer) { delegate?.shutterTapped(in: self) } @objc private func switchTapped(gesture: UIGestureRecognizer) { delegate?.switchTapped(in: self) } @objc private func libraryTapped(gesture: UIGestureRecognizer) { delegate?.libraryTapped(in: self) } @objc private func respondToSwipeGestures(gesture: UIGestureRecognizer) { if let swipeGesture = gesture as? UISwipeGestureRecognizer { switch swipeGesture.direction { case UISwipeGestureRecognizer.Direction.right: delegate?.pixelizationLevelIncreased(in: self) case UISwipeGestureRecognizer.Direction.left: delegate?.pixelizationLevelDecreased(in: self) default: break } } } }
true
7523aa7f3aa9b97a180c3c745c6fcaeff8e18628
Swift
mudgalshubham/Mudgal_MAD
/Labs/Lab2/Bollywood/ViewController.swift
UTF-8
2,403
2.671875
3
[]
no_license
// // ViewController.swift // Bollywood // // Created by Shubham Mudgal on 9/8/16. // Copyright © 2016 Shubham. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageArt: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var imageControl: UISegmentedControl! @IBOutlet weak var labelFontControl: UISegmentedControl! @IBOutlet weak var capitalSwitch: UISwitch! @IBOutlet weak var fontSizeLabel: UILabel! @IBAction func updateFont(sender: UISwitch) { updateCaps() } func updateImage(){ if imageControl.selectedSegmentIndex == 0 { titleLabel.text = "Hunn Dabang!" imageArt.image = UIImage(named: "salman") } else if imageControl.selectedSegmentIndex == 1 { titleLabel.text = "kkk..kkiran!" imageArt.image = UIImage(named: "shahrukh") } } func updateFontStyle(){ if labelFontControl.selectedSegmentIndex == 0 { titleLabel.font = UIFont(name: "Baskerville", size: titleLabel.font.pointSize) } else if labelFontControl.selectedSegmentIndex == 1 { titleLabel.font = UIFont(name: "Papyrus", size: titleLabel.font.pointSize) } } func updateCaps(){ if capitalSwitch.on { titleLabel.text = titleLabel.text?.uppercaseString } else { titleLabel.text = titleLabel.text?.lowercaseString } } @IBAction func changeInfo(sender: UISegmentedControl) { updateImage() updateCaps() } @IBAction func changeFontStyle(sender: UISegmentedControl) { updateFontStyle() } @IBAction func changeFontSize(sender: UISlider) { let fontSize = sender.value //float fontSizeLabel.text = String(format: "%.0f", fontSize) let fontSizeCGFloat = CGFloat(fontSize) titleLabel.font = UIFont.systemFontOfSize(fontSizeCGFloat) updateFontStyle() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
30d31e1c2ef8b75816f902c19fbe6e38afac364f
Swift
ShobhitChourasia/InvestmentBuddy
/InvestmentBuddy/InvestmentBuddy/View/App Modules/App Sub Modules/Explore/Themes/ThemesView.swift
UTF-8
1,323
2.59375
3
[]
no_license
// // ThemesView.swift // InvestmentBuddy // // Created by Shobhit on 22/11/20. // Copyright © 2020 Shobhit. All rights reserved. // import UIKit class ThemesView: UIView { var collectionView: UICollectionView = { let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) return view }() let collectionViewLayout = UICollectionViewFlowLayout() override init(frame: CGRect) { super.init(frame: frame) collectionView.backgroundColor = .clear collectionViewLayout.scrollDirection = .vertical collectionView.setCollectionViewLayout(collectionViewLayout, animated: true) collectionView.translatesAutoresizingMaskIntoConstraints = false addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), collectionView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
0e7c2695291080bef511e91e45c3db819e125f66
Swift
PoketraderApp/poketrader
/Poketrader/Poketrader/Controller/OfertasUsuarioController.swift
UTF-8
1,069
2.703125
3
[]
no_license
// // OfertasUsuarioController.swift // Poketrader // // Created by Bruno da Fonseca on 06/02/21. // import Foundation class OfertasUsuarioController { private var ofertas: Ofertas? private var oferta: OfertaElement? func loadOfertas(completion: @escaping (Bool, String?) -> ()) { OfertasWorker().loadOffersForIUD { (ofertas, erro) in if erro == nil { self.ofertas = ofertas completion(true, "") } else { completion(false, "deu ruim") } } } // func editOffer(obs: String) { // OfertasWorker().updateOffer(offer: self.oferta ?? OfertaElement(), obs: obs) // } func getOferta(at posicao: Int) -> OfertaElement? { return ofertas?.ofertas?[posicao] } func setOferta(ofer: OfertaElement) { self.oferta = ofer } func getOferta() -> OfertaElement? { return self.oferta } var numberOfRows: Int { return self.ofertas?.ofertas?.count ?? 0 } }
true
8728042bdb9de14414294614ddffa3fd74cb2be6
Swift
kevinthrailkill/twittr
/Twittr/Twittr/ComposeViewController.swift
UTF-8
2,093
2.5625
3
[ "Apache-2.0" ]
permissive
// // ComposeViewController.swift // Twittr // // Created by Kevin Thrailkill on 4/8/17. // Copyright © 2017 kevinthrailkill. All rights reserved. // import UIKit /// Base compose class for tweet and reply class ComposeViewController: UIViewController, UITextViewDelegate { //outlets @IBOutlet weak var tweetCharacterCountBarButton: UIBarButtonItem! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var composeTextView: UITextView! @IBOutlet weak var sendButton: UIBarButtonItem! //vars let twitterAPIService = TwitterAPIService.sharedInstance var maxtext: Int = 140 weak var delegate: ComposeTweetDelegate? override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "twittericon.png") self.navigationItem.titleView = UIImageView(image: image) configureComposeView() tweetCharacterCountBarButton.title = "\(maxtext)" } func configureComposeView() { composeTextView.becomeFirstResponder() } @IBAction func sendButtonPressed(_ sender: Any) { sendOutTweet() } func sendOutTweet(){ } @IBAction func cancelButtonPresses(_ sender: Any) { self.dismiss(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Mark: Textview Delegates func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return textView.text.characters.count + (text.characters.count - range.length) <= maxtext } func textViewDidChange(_ textView: UITextView) { tweetCharacterCountBarButton.title = "\(maxtext - textView.text.characters.count)" if textView.text.characters.count > 0 { sendButton.isEnabled = true } else { sendButton.isEnabled = false } } }
true
5a27c4c0cc54f4fbd33d133236b283959045f206
Swift
Veleza/Veleza-SDK-iOS
/Example/Example/Controllers/SurveysPhotosTableViewController.swift
UTF-8
2,294
2.5625
3
[ "BSD-3-Clause" ]
permissive
// // SurveysPhotosTableViewController.swift // Example // // Created by Vytautas Povilaitis on 20/11/2018. // Copyright © 2018 Veleza. All rights reserved. // import Foundation import VelezaSDK class SurveysPhotosTableViewController: UITableViewController { var widgetCell: SurveysPhotosTableViewWidgetCell? var widgetIndexPath = IndexPath(row: 2, section: 1) var widgetIsLoaded = false override func numberOfSections(in tableView: UITableView) -> Int { return 5 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Section \(section + 1)" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath == widgetIndexPath && widgetIsLoaded { return widgetCell! } let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) cell.textLabel?.text = "Section \(indexPath.section + 1) Row \(indexPath.row + 1)" return cell } } extension SurveysPhotosTableViewController: VelezaWidgetDelegate { override func awakeFromNib() { super.awakeFromNib() widgetCell = self.tableView.dequeueReusableCell(withIdentifier: "WidgetCell", for: widgetIndexPath) as? SurveysPhotosTableViewWidgetCell widgetCell?.widget?.delegate = self widgetCell?.widget?.identifier = "00689304051019" } func velezaWidget(_ widget: VelezaWidget, shouldBeDisplayed: Bool) { if widgetIsLoaded != shouldBeDisplayed { widgetIsLoaded = shouldBeDisplayed self.tableView.beginUpdates() self.tableView.reloadRows(at: [widgetIndexPath], with: UITableView.RowAnimation.automatic) self.tableView.endUpdates() } } func velezaWidget(needsLayoutUpdateFor widget: VelezaWidget) { self.tableView.beginUpdates() self.tableView.endUpdates() } } class SurveysPhotosTableViewWidgetCell: UITableViewCell { @IBOutlet var widget: VelezaSurveysPhotosWidget? }
true
33ffdbda286dcb4f878c19ad0dcd72d691d5d513
Swift
awsdocs/aws-doc-sdk-examples
/swift/example_code/iam/basics/Sources/ServiceHandler/ServiceHandlerSTS_Ext.swift
UTF-8
1,083
2.53125
3
[ "Apache-2.0", "MIT" ]
permissive
/* Extensions to the `ServiceHandlerSTS` class to handle tasks needed for testing that aren't the purpose of this example. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ import Foundation import AWSSTS import AWSIAM import ClientRuntime import SwiftUtilities public extension ServiceHandlerSTS { /// Given an IAM access key, return the corresponding AWS account number. /// /// - Parameter key: An `IAMClientTypes.AccessKey` object describing an /// IAM access key. /// /// - Returns: The account number that owns the access key, as a `String`. func getAccessKeyAccountNumber(key: IAMClientTypes.AccessKey) async throws -> String { let input = GetAccessKeyInfoInput( accessKeyId: key.accessKeyId ) do { let output = try await stsClient.getAccessKeyInfo(input: input) guard let account = output.account else { throw ServiceHandlerError.keyError } return account } } }
true
4b5fe78b3dc022de361fc468231098917a51079d
Swift
AleGit/NyTermsHub
/TentativeTests/SharingTests.swift
UTF-8
2,355
3.375
3
[]
no_license
// // SharingTests.swift // NyTerms // // Created by Alexander Maringele on 21.03.16. // Copyright © 2016 Alexander Maringele. All rights reserved. // import XCTest private protocol Uniqueness { static func insert(element:Self) -> Self init (symbol:String, children: [Self]?) } extension Uniqueness { init(symbol:String) { self.init(symbol:symbol, children:nil) self = Self.insert(self) // this works even for classes // despite the fact that we can't do this in classes: // self is immutable in classes } } final class Unique : Uniqueness { static var repository = Set<Unique>(minimumCapacity: 32000) static func insert(element: Unique) -> Unique { if let index = Unique.repository.indexOf(element) { return Unique.repository[index] } Unique.repository.insert(element) return element } private(set) var symbol : String private(set) var children : [Unique]? private init(symbol:String, children:[Unique]?) { self.symbol = symbol self.children = children } } extension Unique : CustomStringConvertible { var description : String { guard let childs = self.children else { return "\(symbol)" } let array = childs.map { $0.description } let arguments = array.joinWithSeparator(",") return "\(self.symbol)[\(arguments)]" } } extension Unique : Hashable { var hashValue : Int { return self.description.hashValue } } func ==(lhs:Unique,rhs:Unique) -> Bool { return (lhs === rhs) || lhs.description == rhs.description } class SharingTests: XCTestCase { func testSharing() { var repository = Set<Unique>() let x0 = Unique(symbol: "X") repository.insert(x0) let x1 = Unique(symbol: "X") repository.insert(x1) XCTAssertEqual(x0.description,x1.description) XCTAssertEqual(x0,x1) XCTAssertEqual(x0.hashValue,x1.hashValue) XCTAssertTrue(x1 === x0) if let index = repository.indexOf(x1) { let x2 = repository[index] XCTAssertTrue(x0 === x2) } else { XCTFail() } } }
true
578e747533a91ded22668840275956d82d48e943
Swift
maxicasal/artDecoMVD
/ArtDecoMvd/LocationSearchTableViewController.swift
UTF-8
2,312
2.84375
3
[]
no_license
// // LocationSearchTableViewController.swift // ArtDecoMvd // // Created by Gabriela Peluffo on 10/26/16. // Copyright © 2016 Gabriela Peluffo. All rights reserved. // import UIKit import MapKit protocol LocationSearchDelegate { func buildingSelected(building:Building) } class LocationSearchTableViewController : UITableViewController { var matchingBuildings : [Building] = [] var buildingsList : [Building] = [] var delegate : LocationSearchDelegate! override func viewDidLoad() { buildingsList = Building.loadBuildings() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return matchingBuildings.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) let building = matchingBuildings[indexPath.row] cell.textLabel!.text = building.name cell.detailTextLabel!.text = building.address cell.textLabel?.font = UIFont(name: kFontMedium, size: 17) cell.detailTextLabel?.font = UIFont(name: kFontLight, size: 14) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if delegate != nil { let building = matchingBuildings[indexPath.row] dismiss(animated: true, completion: nil) delegate.buildingSelected(building: building) } } } extension LocationSearchTableViewController : UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { if searchController.searchBar.text! == "" { matchingBuildings = [] } else { matchingBuildings = buildingsList.filter { building in let searchTextLower = searchController.searchBar.text!.lowercased() return building.name.lowercased().range(of: searchTextLower) != nil || building.address.lowercased().range(of: searchTextLower) != nil } } tableView.reloadData() } }
true
5b9b0a25dfaa3a83e99a60ab7adf1362f0f1900c
Swift
AhmedMousa7/Ahmed-Card-SwiftUI
/AhmedCard/InfoView.swift
UTF-8
825
3.140625
3
[]
no_license
// // InfoView.swift // AhmedCard // // Created by Ahmed Mousa on 12/01/2021. // import SwiftUI struct InfoView: View { let text: String let imageName: String var body: some View { RoundedRectangle(cornerRadius: 20) .fill(Color.white) .frame(height: 45) .overlay( HStack { Image(systemName: imageName) .foregroundColor( Color(red: 0.09, green: 0.63, blue: 0.52)) Text(text) .foregroundColor(.black) } ) } } struct InfoView_Previews: PreviewProvider { static var previews: some View { InfoView(text: "123456789", imageName: "phone.fill") .previewLayout(.sizeThatFits) } }
true
05444e4c8bfd266126f171a325c901a08bc6b63f
Swift
julian395/Food2ForkApp
/f2fApp/RestApiManager.swift
UTF-8
1,705
2.75
3
[]
no_license
// // RestApiManager.swift // BookOfRecipes // // Created by Julian1 on 15.09.16. // Copyright © 2016 juliankob.com. All rights reserved. // import Foundation typealias ServiceResponse = (JSON, NSError?) -> Void class RestApiManager: NSObject { static let sharedInstance = RestApiManager() var searchApi = "http://food2fork.com/api/search?key=52575f1f6c6b0fd7d2bff775e3e83e59" var recipePage = "" var getApi = "http://food2fork.com/api/get?key=52575f1f6c6b0fd7d2bff775e3e83e59" var recipeId = "" func getRecipesPage(s: String) -> String { recipePage = searchApi + s return recipePage } func getSearchRequestByPage(onCompletion: (JSON) -> Void) { let route = recipePage makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func getRecipeId(s: String) -> String { recipeId = getApi + s return recipeId } func getDetailRequest(onCompletion: (JSON) -> Void) { let route = recipeId makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } private func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) { let request = NSMutableURLRequest(URL: NSURL(string: path)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if let jsonData = data { let json:JSON = JSON(data: jsonData) onCompletion(json, error) } else { onCompletion(nil, error) } }) task.resume() } }
true
f05068e3f557fcaa093a33369c24bb28dd96fb27
Swift
bolmax/Libraries
/MainLibraries/Libraries/Libraries/Libraries/Extensions/UIKit/UIImageView.swift
UTF-8
883
2.515625
3
[ "MIT" ]
permissive
// // UIImageView.swift // MOETeachers // // Created by Valera on 9/3/18. // Copyright © 2018 IdeoDigital. All rights reserved. // //import Kingfisher import UIKit extension UIImageView { // func setImage(with urlString: String?, placeholder: UIImage? = nil) { // self.setImage(with: urlString, placeholder: placeholder, completionHandler: nil) // } // // func setImage(with urlString: String?, placeholder: UIImage? = nil, completionHandler: CompletionHandler? = nil) { // // if let urlString = urlString, // let url = URL(string: urlString) { // // let resource = ImageResource(downloadURL: url) // self.kf.setImage(with: resource, placeholder: placeholder, options: nil, progressBlock: nil, completionHandler: completionHandler) // // } else { // self.image = placeholder // } // } }
true
159640b1048a172db39c2fb7eef5d98c9975ea88
Swift
irvifa/PlanOutSwift
/Source/Operator/Binary/Divide.swift
UTF-8
683
3.28125
3
[ "MIT" ]
permissive
// // Divide.swift // PlanOutSwift extension PlanOutOperation { // Division operation. final class Divide: PlanOutOpBinary { typealias ResultType = Double func binaryExecute(left: Any?, right: Any?) throws -> Double? { guard let leftValue = left, let rightValue = right, case let (Literal.number(leftNumber), Literal.number(rightNumber)) = (Literal(leftValue), Literal(rightValue)) else { throw OperationError.typeMismatch(expected: "Numeric", got: "\(String(describing: left)) and \(String(describing: right))") } return leftNumber / rightNumber } } }
true
2fc30c2e319a4952e6c1d6621c62a268962e2684
Swift
magic-IOS/leetcode-swift
/0415. Add Strings.swift
UTF-8
1,799
3.859375
4
[ "Apache-2.0" ]
permissive
class Solution { // 415. Add Strings // Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. // You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. // Example 1: // Input: num1 = "11", num2 = "123" // Output: "134" // Example 2: // Input: num1 = "456", num2 = "77" // Output: "533" // Example 3: // Input: num1 = "0", num2 = "0" // Output: "0" // Constraints: // 1 <= num1.length, num2.length <= 10^4 // num1 and num2 consist of only digits. // num1 and num2 don't have any leading zeros except for the zero itself. func addStrings(_ num1: String, _ num2: String) -> String { var index1 = num1.index(before: num1.endIndex) var index2 = num2.index(before: num2.endIndex) var result = "" var digit = 0 while index1 != num1.endIndex || index2 != num2.endIndex{ var temp = 0 if index1 != num1.endIndex { temp += Int(String(num1[index1]))! index1 = index1 == num1.startIndex ? num1.endIndex : num1.index(before: index1) } if index2 != num2.endIndex { temp += Int(String(num2[index2]))! index2 = index2 == num2.startIndex ? num2.endIndex : num2.index(before: index2) } temp += digit if temp >= 10 { temp -= 10 digit = 1 }else { digit = 0 } result = "\(temp)" + result } result = digit == 1 ? "1" + result : result return result } }
true
e7719c521d468ce346468e72efa82d4b5f46f06f
Swift
remobjects/SwiftFoundation
/Sources/FoundationConvertible/NSUUID.swift
UTF-8
1,673
2.578125
3
[ "MIT" ]
permissive
// // NSUUID.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/4/15. // Copyright © 2015 PureSwift. All rights reserved. // #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) import Glibc import SwiftFoundation import CUUID #endif import Foundation extension UUID: FoundationConvertible { public init(foundation: NSUUID) { self.init(byteValue: foundation.byteValue) } public func toFoundation() -> NSUUID { return NSUUID(byteValue: byteValue) } } public extension NSUUID { convenience init(byteValue: uuid_t) { var value = byteValue let buffer = withUnsafeMutablePointer(&value, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> UnsafeMutablePointer<UInt8> in let bufferType = UnsafeMutablePointer<UInt8>.self return unsafeBitCast(valuePointer, bufferType) }) self.init(UUIDBytes: buffer) } var byteValue: uuid_t { var uuid = uuid_t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) withUnsafeMutablePointer(&uuid, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> Void in let bufferType = UnsafeMutablePointer<UInt8>.self let buffer = unsafeBitCast(valuePointer, bufferType) self.getUUIDBytes(buffer) }) return uuid } var rawValue: String { return UUIDString } convenience init?(rawValue: String) { self.init(UUIDString: rawValue) } }
true
0c8b2e2f87b6f3798ccaaa41bd8600e0c63afb85
Swift
clown0425/ladderGame2
/ladderGame2/Parse.swift
UTF-8
1,764
3.21875
3
[]
no_license
// // convertor.swift // ladderGame2 // // Created by 이희찬 on 2020/02/08. // Copyright © 2020 이희찬. All rights reserved. // import Foundation struct Parse { func convertToLadderBoard(userInput:(String, String)) throws -> LadderBoard { let players = convertToPlayer(inputplayerName: userInput.0) let ladderHeight = try convertToLadderHeight(inputLadderHeight: userInput.1) let ladderExistence = markLadder(playerNumber: players.count, ladderHeight: ladderHeight) return LadderBoard(parsedInput: (players, ladderHeight, ladderExistence)) } private func markLadder(playerNumber:Int, ladderHeight:Int) -> [[Bool]] { var ladderExistence:[[Bool]] = Array(repeating: Array(repeating: false, count: playerNumber - 1), count: ladderHeight) for i in 0..<ladderHeight{ ladderExistence[i][0] = Bool.random() for j in 1..<(playerNumber - 1){ if ladderExistence[i][j-1] == false { ladderExistence[i][j] = Bool.random() } } } return ladderExistence } private func convertToPlayer(inputplayerName:String) -> [Player] { let playerNames = inputplayerName.split(separator: ",").map(String.init) var players = [Player]() for playerName in playerNames { players.append(Player(playerName: playerName)) } return players } private func convertToLadderHeight(inputLadderHeight:String) throws -> Int { if let ladderHeight = Int(inputLadderHeight) { return ladderHeight } throw InputError.isNotInt } }
true
d8ec441f8613d5843aba8f8bdac31eb682e5c8cf
Swift
davewachtel/Kango-IOS
/Kango/InboxMessage.swift
UTF-8
2,183
2.828125
3
[]
no_license
// // InboxMessage.swift // Kango // // Created by James Majidian on 12/15/14. // Copyright (c) 2014 Cornice Labs. All rights reserved. // import Foundation class InboxMessage { var assetId: Int; var fromUser: String; var phoneNumber: String; var msg: String; var timeAgo: String; var msgID: String; var isRead : Bool; init(assetId: Int, fromUser: String, phoneNumber: String, msg: String, timeAgo: String, isRead: Bool, MessageID: String) { self.assetId = assetId; self.fromUser = fromUser; self.phoneNumber = phoneNumber; self.msg = msg; self.timeAgo = timeAgo; self.isRead = isRead; self.msgID = MessageID; } class func toMessage(allResults: NSArray) -> [InboxMessage] { // Create an empty array of Albums to append to from this list var messages = [InboxMessage]() // Store the results in our table data array if allResults.count > 0 { // Sometimes iTunes returns a collection, not a track, so we check both for the 'name' for result in allResults { let resultData = result as! NSDictionary let assetId = resultData["assetid"] as! Int; let fromUser = resultData["fromuser"] as! String; var phoneNumber = "" if let phone = resultData["phone"] as? String { phoneNumber = phone } let message = ""; let timeago = resultData["timeago"] as! String; let idMessage = Int((resultData["messageid"] as AnyObject) as! NSNumber) let messageID = String(idMessage); let isRead = resultData["isread"] as! Bool; let msg = InboxMessage(assetId: assetId, fromUser: fromUser, phoneNumber: phoneNumber, msg: message, timeAgo: timeago, isRead: isRead , MessageID : messageID) messages.append(msg) } } return messages; } }
true
657155d98448beca1287d352ac050884f1b5163e
Swift
InspireIdaho/myprogress-vapor-api
/Sources/App/Models/Member.swift
UTF-8
2,542
2.8125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Member.swift // App // // Created by M. Sean Bonner on 8/10/19. // import Vapor import FluentMySQL import Authentication /// Represent Team with User members final class Member: ModifiablePivot { var id: UUID? var memberRoleEnum: Int = Member.Role.participant.rawValue // relationships var userID: User.ID var groupID: Group.ID typealias Left = User typealias Right = Group static var leftIDKey: LeftIDKey = \.userID static var rightIDKey: RightIDKey = \.groupID enum Role : Int { case participant = 0 case expert case mentor } init(_ user: User, _ group: Group, _ role: Member.Role) throws { userID = try user.requireID() groupID = try group.requireID() memberRoleEnum = role.rawValue } init(_ user: User, _ group: Group) throws { userID = try user.requireID() groupID = try group.requireID() memberRoleEnum = Member.Role.participant.rawValue } struct AttachUserToGroup: Content { let userID: User.ID let groupID: Group.ID let role: Int? } static func attach(member: AttachUserToGroup, on conn: DatabaseConnectable) throws -> Future<Member> { var role = Member.Role.participant if let roleID = member.role { if let possRole = Member.Role.init(rawValue: roleID) { role = possRole } } return flatMap(to: Member.self, User.find(member.userID, on: conn), Group.find(member.groupID, on: conn)) { user, group in guard let user = user else { throw HelpfulError(identifier: "Invalid Membership", reason: "User with ID[\(member.userID)] not found") } guard let group = group else { throw HelpfulError(identifier: "Invalid Membership", reason: "Group with ID[\(member.groupID)] not found") } return try Member(user, group, role).save(on: conn) } } } extension Member: MySQLUUIDModel {} extension Member: Content {} extension Member: Parameter {} extension Member: Migration { static func prepare(on connection: MySQLConnection) -> Future<Void> { return Database.create(self, on: connection) { builder in // default behavior, try addProperties(to: builder) } } }
true
762d4daf0faa1ede397796524ba18e1348dab243
Swift
free-gate/lang
/swift/unique.swift
UTF-8
887
3.65625
4
[ "MIT" ]
permissive
#!/usr/bin/swift // given a list of integer where every element appears even number of time // except for one, find that unique one in O(1) space. func findUniqueID(numbers: [Int]) -> Int { var ones = 0 for num in numbers { ones ^= num } return ones } func assertEqual(s1: Int, s2: Int) { if s1 != s2 { print("'\(s1)' is not equal to '\(s2)'") } else { print("passed") } } struct test { let input: [Int] let expected: Int } let tests: [test] = [ test(input: [], expected: 0), test(input: [6], expected: 6), test(input: [10, 10], expected: 0), test(input: [6, 2, 2, 4, 4, 1, 1, 1, 1], expected: 6), test(input: [1, 1, 2, 4, 2, 1, 4, 6, 1], expected: 6), test(input: [4, 1, 2, 1, 6, 1, 4, 2, 1], expected: 6) ] for t in tests { assertEqual(s1: t.expected, s2: findUniqueID(numbers: t.input)) }
true
0e9061dfad671131bc32c25785b3c6d89274d575
Swift
jorjuela33/Kisi
/Kisi/Modules/Locks/Presenter/LocksPresenter.swift
UTF-8
1,466
2.703125
3
[]
no_license
// // LocksPresenter.swift // Kisi // // Created by Jorge Orjuela on 10/26/17. // Copyright © 2017 Jorge Orjuela. All rights reserved. // import Foundation protocol LocksPresenterInterface: class { func getLocks() } class LocksPresenter { let interactor: LocksInteractorInput weak var interface: LocksTableViewControllerInterface? var wireframe: LocksWireframe? // MARK: Initialization required init(interactor: LocksInteractorInput) { self.interactor = interactor } } extension LocksPresenter: LocksPresenterInterface { // MARK: LocksPresenterInterface func getLocks() { interactor.getLocks() } } extension LocksPresenter: LocksInteractorOutput { // MARK: LocksInteractorOutput func didFailFetchingLocks(_ errors: [Error]) { interface?.showErrorMessage("We are not able to fetch the locks at this moment") } func didFinishFetchingLocks(_ locks: [LockDisplayItem]) { interface?.didFinishFechingLocks(locks) } func didFoundLock(_ identifier: Int) { wireframe?.presentUnlockView(identifier) } func locationManagerDidFail(withError error: LocationManagerError) { interface?.showErrorMessage("We are not able to start the location updates") } func locationPermissionNotAuthorized() { interface?.showErrorMessage("Please go to settings and grant access to the location services") } } extension LocksPresenter: Presenter {}
true
4098542de33d5497003a684bf2422c0548a18471
Swift
phindilemfeka/SBGApp
/Standardbank App/ViewControllers/MethodsTableViewController.swift
UTF-8
1,662
2.78125
3
[]
no_license
// // MethodsTableViewController.swift // Standardbank App // // Created by Phindile on 2020/11/04. // Copyright © 2020 Phindile Mfeka. All rights reserved. // import UIKit var methods = ["With fingerprint", "Voice recognition", "Face Recognition", "With 4-digit PIN"].shuffled() var heading = "Choose How to Sign In" var methodsIndex = 0 class MethodsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationItem.setHidesBackButton(true, animated: false) } override func viewDidAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } override func viewDidDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: false) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return methods.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Choose How to Sign In" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "mycell",for: indexPath) cell.textLabel?.text = methods[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { methodsIndex = indexPath.row performSegue(withIdentifier: "segue", sender: self) } }
true
6a35d18cbe7f2ca634a1015787bbc18fbfabbc19
Swift
luoyu1993/Jasmine
/Jasmine/GameCommons/ViewModels/BaseViewModelProtocol.swift
UTF-8
483
2.8125
3
[]
no_license
import Foundation /// Sets the shared functionalities that are applicable across all view model declarations. /// This protocol will be inherited by all the specialised view model protocols. protocol BaseViewModelProtocol: class, GameDescriptorProtocol { // MARK: Game Operations /// Stores the grid data that will be used to display in the view controller. var gridData: TextGrid { get } /// Tells the view model that the game has started. func startGame() }
true
b359e09a90e5ab75b618e9bc333acda92cfdb382
Swift
appteur/simpleanalytics
/Example/Source/Analytics/Events/Actions/AnalyticsActionLoginPage.swift
UTF-8
909
2.78125
3
[ "MIT" ]
permissive
// // AnalyticsAction.swift // Analytics // // Created by Seth on 2/23/17. // Copyright © 2017 Arnott Industries, Inc. All rights reserved. // import Foundation import SimpleAnalytics /// This describes analytics events related to user actions on the login page /// Add cases for any specific events along with values for those events below. public enum AnalyticsActionLoginPage: AnalyticsEvent { case tapLoginButton public var category: String { return "USER_ACTION" } public var action: String { switch self { case .tapLoginButton: return "BUTTON_TAP" } } public var label: String { switch self { case .tapLoginButton: return "Login Button" } } public var value: Any? { switch self { case .tapLoginButton: return "1" } } }
true
ce47b9c39a61e6511ea69e6b20c20901f9bb25df
Swift
amnnkaur/C0782918_MidTerm_MAD3115W2020
/C0782918_MidTerm_MAD3115W2020/NewCustomerViewController.swift
UTF-8
2,376
2.5625
3
[]
no_license
// NewCustomerViewController.swift // C0782918_MidTerm_MAD3115W2020 // // Created by MacStudent on 2020-03-05. // Copyright © 2020 MacStudent. All rights reserved. // import UIKit class NewCustomerViewController: UIViewController { @IBOutlet weak var txtFirstName: UITextField! @IBOutlet weak var txtLastName: UITextField! @IBOutlet weak var txtEmail: UITextField! let a = Singleton.getInstance() var firstName: String! var lastName: String! var email: String! var cust: Customer! override func viewDidLoad() { super.viewDidLoad() } // func btnClick() { // // self.performSegue(withIdentifier: "thirdSegue", sender: self) // } @IBAction func barBtnSave(_ sender: UIBarButtonItem) { firstName = self.txtFirstName.text lastName = self.txtLastName.text email = self.txtEmail.text if firstName == "" || lastName == "" || email == "" { print("if") let alertController = UIAlertController(title: "Error!", message:"All fields are required", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Try Again", style: .cancel)) self.present(alertController, animated: true, completion: nil) } else{ print("else") let sb = UIStoryboard(name: "Main", bundle: nil) let customerListVC = sb.instantiateViewController(identifier: "customerListVC") as! CustomerListTableViewController customerListVC.firstName = firstName customerListVC.lastName = lastName customerListVC.email = email a.addNewCustomer(First_Name: firstName!, Last_Name: lastName!, email: email!) // Singleton.addNewCustomer(self.firstName,self.lastName,self.email) self.navigationController?.pushViewController(customerListVC, animated: true) } } // // @IBAction func backToCustomers(_ sender: UIButton) { // // self.navigationController?.popViewController(animated: true) // } // /* // 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
0a527d47bc3f17e54f995c42db95204628e515c6
Swift
matheusamancio/homekitTeste
/HomeKitTest1.1/HomeViewController.swift
UTF-8
4,661
2.546875
3
[]
no_license
// // ViewController.swift // HomeKitTest1.1 // // Created by Matheus Amancio Seixeiro on 8/28/15. // Copyright (c) 2015 Matheus Amancio Seixeiro. All rights reserved. // import UIKit import HomeKit class HomeViewController: UIViewController, HMHomeManagerDelegate, UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var editButton: UIBarButtonItem! // variaveis da Casa lazy var homeManager: HMHomeManager = { let manager = HMHomeManager() manager.delegate = self return manager }() @IBOutlet weak var tableView: UITableView! override func viewWillAppear(animated: Bool) { tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ let numberOfRowns = homeManager.homes.count editButton.enabled = (numberOfRowns > 0) if numberOfRowns == 0{ Done() } return numberOfRowns } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let home = homeManager.homes[indexPath.row] cell.textLabel?.text = home.name return cell } func homeManagerDidUpdateHomes(manager: HMHomeManager) { tableView.reloadData() } // override func prepareForSegue(segue: UIStoryboardSegue, // sender: AnyObject!) { // // if segue.identifier == "segueIdentifier"{ // // let controller = segue.destinationViewController // as! AddViewController // controller.homeManager = homeManager // // } // // super.prepareForSegue(segue, sender: sender) // // } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: let home = homeManager.homes[indexPath.row] homeManager.removeHome(home, completionHandler: { (error: NSError?) -> Void in let strongself = self if error != nil{ UIAlertController.showAlertControllOnHostController(strongself, title: "Error", message: "An error occurred = \(error)") } else{ tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }) default: return } } @IBAction func Edit(sender: AnyObject) { if editButton.title == "Edit"{ isEditingMode() } else{ Done() } } func isEditingMode(){ editButton.title = "Done" self.tableView.setEditing(true, animated: true) self.navigationItem.rightBarButtonItem?.enabled = false } func Done(){ editButton.title = "Edit" self.tableView.setEditing(false, animated: true) self.navigationItem.rightBarButtonItem?.enabled = true } @IBAction func addHome(sender: AnyObject) { UIAlertController.addAlert(self, title: "Nova Casa", message: "coloca uma casa") { (texto) -> Void in self.homeManager.addHomeWithName(texto, completionHandler: {[weak self] (home: HMHome?, error: NSError?) -> Void in if error != nil { UIAlertController.showAlertControllOnHostController(self!, title: "ERRO", message: "\(error)") } self!.tableView.reloadData() }) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "homeIdentifier"{ let controller = segue.destinationViewController as! RoomViewController controller.homeManager = homeManager let home = homeManager.homes[tableView.indexPathForSelectedRow!.row] controller.home = home } super.prepareForSegue(segue, sender: sender) } }
true
23579a2f794aea3237f4bbf37f148df723aaa1dd
Swift
zhvrnkov/BaseNetworking
/BaseNetworkingLibrary/ParameterEncoders/MultipartFormDataEncoder.swift
UTF-8
1,410
2.71875
3
[]
no_license
// // MultipartFormDataEncoder.swift // AssessmentNetwork // // Created by Vlad Zhavoronkov on 7/10/19. // Copyright © 2019 Bytepace. All rights reserved. // import Foundation public struct MultipartFormDataEncoder { public static func encode(_ urlRequest: inout URLRequest, with parameters: Parameters) throws { var body = Data() let boundary = UUID().uuidString urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters where !(value is Data) { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } let mimetype = "image/jpg" for (key, value) in parameters { if let imageData = value as? Data { let filename = "\(key).jpg" body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n") body.appendString("Content-Type: \(mimetype)\r\n\r\n") body.append(imageData) body.appendString("\r\n") } } body.appendString("--\(boundary)--\r\n") urlRequest.httpBody = body } }
true
ab29b1812ffd9bac1f0317c0baa3d37facc0fe1d
Swift
SandyLudosky/FDJ
/FDJ/DataSources/PlayersDataSource.swift
UTF-8
1,108
2.78125
3
[]
no_license
// // TeamDataSource.swift // FDJ // // Created by Sandy on 2019-07-16. // Copyright © 2019 Sandy. All rights reserved. // import Foundation import UIKit class PlayersDataSource: NSObject { var items: [PlayerViewModel] init(items: [PlayerViewModel]) { self.items = items super.init() } // MARK: - Helper func update(with results: [PlayerViewModel]) { items = results } func result(at indexPath: IndexPath) -> PlayerViewModel { return items[indexPath.row] } } // MARK: - UITableDataSource extension PlayersDataSource: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: PlayerCell.identifier, for: indexPath) as? PlayerCell else { return UITableViewCell() } let player = items[indexPath.row] cell.configure(with: player) return cell } }
true
e54b13b9ee8c223b916ddc64d4f18f1df6b53d7f
Swift
shannoding/sign-in
/signin/DatabaseReference+Location.swift
UTF-8
1,232
2.828125
3
[]
no_license
// // DatabaseReferenceLocation.swift // signin // // Created by Shannon Ding on 7/11/17. // Copyright © 2017 Shannon Ding. All rights reserved. // import Foundation import FirebaseDatabase extension DatabaseReference { enum SignLocation { case root case groups(uid: String) //find groupIDs user has joined case profile(uid: String) //enter the profile of a user case groupMembers(groupID: String) //find all memberUIDs of a group func asDatabaseReference() -> DatabaseReference { let root = Database.database().reference() switch self { case .root: return root case .groups(let uid): return root.child(uid).child("groups") case .profile(let uid): return root.child(uid) case .groupMembers(let groupID): return root.child("groups").child(groupID).child("members") } } } static func toLocation(_ location: SignLocation) -> DatabaseReference { return location.asDatabaseReference() } }
true
2c3910c9cd1b5ba969d861de68a02d8387e014c8
Swift
Mocha1995/immersive-reader-sdk
/iOS/samples/quickstart-swift/quickstart-swiftUITests/quickstart_swiftUITests.swift
UTF-8
3,471
2.53125
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import XCTest class quickstart_swiftUITests: XCTestCase { var app: XCUIApplication! override func setUp() { // Stop immediately when a failure occurs. continueAfterFailure = false app = XCUIApplication() app.launch() } override func tearDown() { } // Tests if the Immersive Reader Launch button is working. func testLaunchButton() { app.buttons["Immersive Reader"].tap() // Ensure the Immersive Reader launched. XCTAssert(immeriveReaderLaunchHelper()) } // Tests if the exit button to exit the Immerive Reader is working. func testExitButton() { let immersiveReaderButton = app.buttons["Immersive Reader"] immersiveReaderButton.tap() let webViewsQuery = app.webViews // Ensure Immersive Reader launched. if(!immeriveReaderLaunchHelper()) { XCTAssert(false) } // Ensure the Immersive Reader launch button does not exist. if (immersiveReaderButton.exists) { XCTAssert(false) } app.navigationBars["immersive_reader_sdk.ImmersiveReaderView"].buttons["Back"].tap() // Ensure Immersive Reader is no longer open. if (webViewsQuery.buttons["Text Preferences"].exists) { XCTAssert(false) } // Ensure the Immersive Reader launch button is available. XCTAssert(app.buttons["Immersive Reader"].isHittable) } // Tests that the Immersive Reader is filling the full screen width. func testWebViewFullScreen() { let appWidth = app.frame.size.width app.buttons["Immersive Reader"].tap() let webViewsQueryWidth = app.webViews.element.frame.size.width // Ensure the WebView's width is equal to the application's width. XCTAssert(Int(appWidth) == Int(webViewsQueryWidth)) } // Tests launching the Immersive Reader, then exiting, and then relaunching the Immersive Reader. func testReopenImmersiveReader() { let immersiveReaderButton = app.buttons["Immersive Reader"] // Launch the Immersive Reader. immersiveReaderButton.tap() // Ensure the Immersive Reader launched. if (!immeriveReaderLaunchHelper()) { XCTAssert(false) } // Exit the Immersive Reader. app.navigationBars["immersive_reader_sdk.ImmersiveReaderView"].buttons["Back"].tap() // Ensure the Immersive Reader exited. if (!immersiveReaderButton.exists) { XCTAssert(false) } // Relaunch the Immersive Reader. immersiveReaderButton.tap() // Ensure the Immersive Reader relaunched. XCTAssert(immeriveReaderLaunchHelper()) } // A helper function which ensures the Immersive Reader lauched successfully. func immeriveReaderLaunchHelper() -> Bool { let webViewsQuery = app.webViews return (webViewsQuery.buttons["Text Preferences"].isHittable && webViewsQuery.buttons["Grammar Options"].isHittable && webViewsQuery.buttons["Reading Preferences"].isHittable && app.webViews.otherElements["The"].staticTexts["The"].exists && app.webViews.staticTexts["often"].exists) } }
true
b58ee74de8759f09f03b5958ee2f81f2db574c6f
Swift
cao903775389/MRCBaseLibrary
/MRCBaseLibrary/Classes/MRCBaseViewModel/MRCBaseViewModel.swift
UTF-8
1,044
2.6875
3
[ "MIT" ]
permissive
// // MRCBaseViewModel.swift // Pods // // Created by 逢阳曹 on 2017/5/27. // // import Foundation import ReactiveSwift //所有ViewModel的基类 open class MRCBaseViewModel: NSObject { public required init(params: [String: Any]? = nil) { param = params title = MutableProperty((params?["title"] as? String) ?? "") } //导航栏标题 public var title: MutableProperty<String> //界面将要消失 deinit { print("\(self)已销毁") } //参数 private var param: [String: Any]? } public protocol MRCViewModel: class { //导航栏标题 var title: MutableProperty<String> { set get } //初始化方法 init(params: [String: Any]?) } extension MRCBaseViewModel: MRCViewModel { } extension SignalProducer { public static func pipe() -> (SignalProducer, ProducedSignal.Observer) { let (signal, observer) = ProducedSignal.pipe() let producer = SignalProducer(signal) return (producer, observer) } }
true
fc8ae6912d45a4998ea33f3b92dcfb2f8acd0aa6
Swift
vargamatyas89/CarViewer
/CarViewer/CarViewer/ViewControllers/MapViewController.swift
UTF-8
1,404
2.59375
3
[]
no_license
// // MapViewController.swift // CarViewer // // Created by Varga, Matyas on 2017. 10. 15.. // Copyright © 2017. MyOrg. All rights reserved. // import Foundation import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! public var position: CLLocationCoordinate2D! public var carName: String! override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self self.navigationItem.hidesBackButton = true } override func viewDidAppear(_ animated: Bool) { self.loadMapView(animated) } @IBAction func doneButtonTapped(_ sender: Any) { self.dismiss(animated: true) } private func loadMapView(_ animated: Bool) { self.mapView.isZoomEnabled = true self.mapView.isRotateEnabled = true self.mapView.isScrollEnabled = true self.mapView.showsScale = true self.mapView.showsCompass = true self.makeAnnotationPoint() self.mapView.showAnnotations(self.mapView.annotations, animated: animated) } private func makeAnnotationPoint() { let annotation = MKPointAnnotation() if let name = carName { annotation.title = name } annotation.coordinate = self.position self.mapView.addAnnotation(annotation) } }
true
6f61f23ad637134b9663054694ece513270441d3
Swift
ecastillo/SwiftSonarr
/Playground.playground/Contents.swift
UTF-8
3,998
2.984375
3
[]
no_license
import SwiftSonarr Sonarr.tag(id: 7) { (result) in print("GET TAG") switch result { case .success(let tag): print("tag found: "+tag.label) case .failure(let error): print("Error: \(error)") print("Error localized description: \(error.localizedDescription)") print("Error code: \(error.code)") print("Error code error description: \(error.code.errorDescription)") print("Error request url: \(error.requestUrl)") print("Error message: \(error.message)") } } Sonarr.createTag(label: "hi there") { (result) in print("CREATE TAG") switch result { case .success: print("tag created") case .failure(let error): print("Error: \(error)") print("Error localized description: \(error.localizedDescription)") print("Error code: \(error.code)") print("Error code error description: \(error.code.errorDescription)") print("Error request url: \(error.requestUrl)") print("Error message: \(error.message)") } } Sonarr.series { (result) in print("GET ALL SERIES") switch result { case .success(var series): print(series[0].title) case .failure(let error): print("Error: \(error)") print("Error localized description: \(error.localizedDescription)") print("Error code: \(error.code)") print("Error code error description: \(error.code.errorDescription)") print("Error request url: \(error.requestUrl)") print("Error message: \(error.message)") } } //Sonarr.queue { (result) in // print("GET QUEUE") // switch result { // case .success(var queue): // print(queue[0].series?.title) // case .failure(let error as NSError): // print("Error: \(error)") // print("Error code: \(error.code)") // print("Error user info: \(error.userInfo)") // } //} //Sonarr.series { (result) in // print("GET ALL SERIES") // switch result { // case .success(var series): // print(series[0].title) // case .failure(let error as NSError): // print(error) // print(error.code) // print(error.userInfo) // } //} //var options = WantedMissing.Options() //options.page = 1 //Sonarr.wantedMissing(options: options) { (result) in // print("WANTED MISSING") // switch result { // case .success(let wantedMissing): // print("first in wanted missing: \(wantedMissing.records?[0].title)") // case .failure(let error as NSError): // print(error.userInfo) // } //} //Sonarr.systemStatus { (result) in // print("GET SYSTEM STATUS") // switch result { // case .success(let systemStatus): // print("Version: "+(systemStatus.version ?? "no version found")) // case .failure(let error as NSError): // print(error.code) // print(error.userInfo) // } //} // //Sonarr.createTag(label: "hi there") { (result) in // print("CREATE TAG") // switch result { // case .success(let tag): // print("tag created: "+tag.label) // case .failure(let error as NSError): // print(error.userInfo) // } //} // //Sonarr.tags { (result) in // print("GET TAGS") // switch result { // case .success(var tags): // tags[0].label = "updated to \(Int.random(in: 1...1000000))" // Sonarr.updateTag(tag: tags[0]) { (result) in // print("UPDATE TAG") // switch result { // case .success(let tag): // print("tag updated: "+tag.label) // case .failure(let error as NSError): // print(error.userInfo) // } // } // case .failure(let error as NSError): // print(error.code) // print(error.userInfo) // } //} // //Sonarr.deleteTag(tagId: 1) { (result) in // print("DELETE TAG") // switch result { // case .success: // print("tag deleted") // case .failure(let error as NSError): // print(error.userInfo) // } //}
true
6ec5a3e6c4829db11ca9f301a11256f76d0f6178
Swift
harutooyama/SwiftApp
/SwiftApp/GestureFlash/GestureFlash/ViewController.swift
UTF-8
1,273
2.625
3
[]
no_license
// // ViewController.swift // GestureFlash // // Created by Owner on 2020/06/05. // Copyright © 2020 Owner. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var highScore1Label: UILabel! @IBOutlet weak var highScore3Label: UILabel! @IBOutlet weak var highScore2Label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool){ let defaults = UserDefaults.standard let highScore1 = defaults.double(forKey: "highScore1") let highScore2 = defaults.double(forKey: "highScore2") let highScore3 = defaults.double(forKey: "highScore3") NSLog("ハイスコア:1位-%f 2位-%f 3位-%f",highScore1,highScore2,highScore3) if highScore1 != 0{ highScore1Label.text = String(format: "%.3f秒",highScore1) } if highScore2 != 0{ highScore2Label.text = String(format: "%.3f秒",highScore2) } if highScore3 != 0{ highScore3Label.text = String(format: "%.3f秒",highScore3) } } @IBAction func backView(segue: UIStoryboardSegue){ } }
true
9426d7711eeda0438f2f2970d097b0aa1eee5835
Swift
BereniceSanlucar/ResumeApp
/ResumeApp/Modules/BasicInformation/Constants/BasicInformationConstants.swift
UTF-8
1,541
2.765625
3
[]
no_license
// // BasicInformationConstants.swift // ResumeApp // // Created by Berenice Sanlúcar on 11/23/19. // Copyright © 2019 Berenice Sanlúcar. All rights reserved. // import CoreGraphics struct BasicInformationConstants { struct DefaultContents { static let notSummary = "Not professional summary available" } struct ImageNames { static let kotlin = "kotlin" static let swift = "swift" static let english = "english" static let french = "french" static let spanish = "spanish" } struct Sizes { static let numberOfItemsPerRow: CGFloat = 3 static let spaceBetweenCells: CGFloat = 8 static let numberOfSpaces: CGFloat = 4 static let spaceForSectionFirst: CGFloat = 0 static let heightForHeader: CGFloat = 20 } struct CVCellHeight { static let forIPhone5S: CGFloat = 121 static let forIPhone6: CGFloat = 144 static let forIPhone7Plus: CGFloat = 170 static let forIPhoneX: CGFloat = 178 static let forIPhoneXR: CGFloat = 197 } enum TitleForBasicInformation: Int { case summmary case languages case programmingLanguages var title: String { switch self { case .summmary: return "Professional Summary" case .languages: return "Speaking Languages" case .programmingLanguages: return "Programming Languages" } } } }
true
2118672cb3d82bd339b1f6fd821ee649d71b8347
Swift
machlows/SmogApp
/SmogApp/ProgresCircleView.swift
UTF-8
967
2.84375
3
[]
no_license
// // ProgresCircleView.swift // SmogApp // // Created by Tomasz Machlowski on 26/09/2017. // Copyright © 2017 Tomasz Machlowski. All rights reserved. // import Foundation import UIKit class ProgresCircleView: UIView { @IBInspectable var mainColor: UIColor! override func draw(_ rect: CGRect) { super.draw(rect) } func drawCircle(center: CGPoint, radius: CGFloat, percentage: CGFloat) { let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2) * percentage , clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = mainColor.cgColor shapeLayer.lineWidth = 4.0 self.layer.addSublayer(shapeLayer) } func clearView() { self.layer.sublayers?.forEach { $0.removeFromSuperlayer() } } }
true
f4cd258798d1dcd2a06f628adda885d17f1292dc
Swift
ingracristin/marketeiros
/Marketeiros/Marketeiros/UI/Scenes/Unused Scenes/Boards/IdeaCell.swift
UTF-8
1,561
2.828125
3
[]
no_license
// // IdeaCell.swift // Marketeiros // // Created by João Guilherme on 17/06/21. // import SwiftUI struct IdeaCell: View { @State var newIdea: String = NSLocalizedString("writeIdea", comment: "") var body: some View { VStack(alignment: .leading, spacing: 0){ HStack{ // Button(action: {}, label: { // Image(systemName: "face.dashed").foregroundColor(Color("iconIdeaColorCell")) // }) Button(action: {}, label: { Image(systemName: "folder").foregroundColor(Color("iconIdeaColorCell")) }) } .padding(.horizontal) .padding(.top) .padding(.bottom,0) ZStack { TextEditor(text: $newIdea) .font(Font.sfProDisplayRegular(sized: 14)) .foregroundColor(Color("IdeaColorText")) .background(Color("ideaColorCell")) .onTapGesture { if newIdea == NSLocalizedString("writeIdea", comment: "") { newIdea = "" } } Text(newIdea).opacity(0).padding(.all,8) } .padding(.vertical,8) .padding(.horizontal) } //.padding(.init(top: 12, leading: 20, bottom: 0, trailing: 20)) .background(Color("ideaColorCell")) } } struct IdeaCell_Previews: PreviewProvider { static var previews: some View { IdeaCell() } }
true
da0ad01c6944c576843467823efcb7fccd84f440
Swift
GeonHyeongKim/AlgoriGym
/Test/e-2.swift
UTF-8
638
3.03125
3
[ "MIT" ]
permissive
// // e-2.swift // // // Created by gunhyeong on 2020/08/29. // import Foundation class Solution { static int answer = Integer.MAX_VALUE; public int solution(int num, int[] cards) { dfs(cards, 0, num, 0, 0); return answer; } public dfs(int[] cards, int start, int target, int sum, int cardCnt){ if sum > target || cardCnt >= answer { return; } if sum == target { answer = cardCnt; return; } for i in start..<cards.count { dfs(cards, i, target, sum+cards[i], cardCnt+1); } } }
true
d80dfa34ad590319a1d35433eb27fa463275c6a4
Swift
baonhan88/Digital-Signage-iOS
/SDSS IOS CLIENT/Category/UIFont+Extension.swift
UTF-8
765
2.640625
3
[]
no_license
// // UIFont+Extension.swift // SDSS IOS CLIENT // // Created by Nhan on 29/05/2017. // Copyright © 2017 SLab. All rights reserved. // import UIKit extension UIFont { func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits)) if descriptor != nil { return UIFont(descriptor: descriptor!, size: 0) } return self } func boldItalic() -> UIFont { return withTraits(traits: .traitBold, .traitItalic) } func bold() -> UIFont { return withTraits(traits: .traitBold) } func italic() -> UIFont { return withTraits(traits: .traitItalic) } }
true
d6d1b55224b94936f310f1daa61453dcb61ffd1e
Swift
sereivoanyong/SwiftKit
/Sources/SwiftKit/UIKit/UICollectionViewFlowLayout.swift
UTF-8
754
2.703125
3
[ "MIT" ]
permissive
// // UICollectionViewFlowLayout.swift // // Created by Sereivoan Yong on 1/27/20. // #if canImport(UIKit) import UIKit extension UICollectionViewFlowLayout { @inlinable public convenience init(scrollDirection: UICollectionView.ScrollDirection, minimumLineSpacing: CGFloat = 10, minimumInteritemSpacing: CGFloat = 10, itemSize: CGSize = CGSize(width: 50, height: 50), sectionInset: UIEdgeInsets = .zero, sectionInsetReference: SectionInsetReference) { self.init() self.scrollDirection = scrollDirection self.minimumLineSpacing = minimumLineSpacing self.minimumInteritemSpacing = minimumInteritemSpacing self.itemSize = itemSize self.sectionInset = sectionInset self.sectionInsetReference = sectionInsetReference } } #endif
true
31c009611c614bfaec346c8313224d68cdbf5216
Swift
n3tr/Basic-iOS-Playground
/iOSTraining.playground/Pages/02-2-for-in-array.xcplaygroundpage/Contents.swift
UTF-8
253
4.5625
5
[]
no_license
//: # For-in Loop (Array) let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { print("Hello, \(name)!") } // For each index for i in 0..<names.count { print("Hello, \(names[i])!") } //: [Previous](@previous) - [Next](@next)
true
51e61c26b09511808dc48c4f1f335202d6af6b0c
Swift
brandonshearin/Cookooree
/Cookooree/Views/Settings.swift
UTF-8
3,405
2.828125
3
[]
no_license
// // Settings.swift // Cookooree // // Created by Brandon Shearin on 11/20/20. // import SwiftUI struct link: Hashable, Identifiable { var id: String var title: String var link: String } struct Settings: View { let links = [link(id: "1", title: "Send feedback", link: "https://unicorndreamfactory.com/cookooree/support/"), link(id: "2", title: "Help", link: "https://unicorndreamfactory.com/cookooree/help/"), link(id: "3", title: "Privacy Policy", link: "https://unicorndreamfactory.com/cookooree/privacy/"), link(id: "4", title: "Terms of Use", link: "https://unicorndreamfactory.com/cookooree/terms/")] @Environment(\.presentationMode) var presentationMode @Binding var screenOn: Bool @State private var showWebView = false @State private var destination: link? var body: some View { NavigationView { VStack(alignment: .leading) { Text("Settings") .font(.custom("Barlow", size: 24, relativeTo: .largeTitle)) .padding(.horizontal) Toggle("Keep screen on", isOn: $screenOn.onChange { UIApplication.shared.isIdleTimerDisabled = screenOn }) .padding() Divider() ForEach(links, id: \.self) { link in LinkView(l: link) .onTapGesture { showWebView.toggle() destination = link } } Text("Cookooree v1.0.0") .padding() .foregroundColor(Color(.secondaryLabel)) Divider() Spacer() } .sheet(item: $destination){ dest in NavigationView { WebView(url: URL(string: dest.link)!) .edgesIgnoringSafeArea(.all) .navigationBarItems(trailing: closeBtn(action: { self.destination = nil })) } } .padding() .navigationBarItems(trailing: closeBtn(action: { self.presentationMode.wrappedValue.dismiss() })) } } } struct Settings_Previews: PreviewProvider { @State static var screenOn = false static var previews: some View { NavigationView{ Settings(screenOn: $screenOn) } } } struct LinkView: View { var l: link var body: some View { VStack(alignment: .leading) { Text(l.title) .foregroundColor(Color(.systemBlue)) .padding() Divider() } .contentShape(Rectangle()) } } struct closeBtn: View { var action: () -> Void var body: some View { Button(action: action){ Image(systemName: "multiply.circle.fill") .imageScale(.large) .foregroundColor(Color(.secondaryLabel)) } } }
true
41d364970a799f5270c4bc2049d0617ab589e989
Swift
IzikLisbon/weather
/weatherTests/Mocks/WeatherAPIMock.swift
UTF-8
492
2.765625
3
[]
no_license
// // WeatherAPIMock.swift // weatherTests // // Created by Izik Lisbon on 12/5/18. // Copyright © 2018 grab. All rights reserved. // import Foundation class MethodMock { var count: Int = 0 } class GetDailyWeatherMock: MethodMock { } class WeatherAPIImp: WeatherAPI { private let getDailyWeatherMock: GetDailyWeatherMock = GetDailyWeatherMock() func getDailyWeather(completion: @escaping (_ Weather: Weather?, _ error: Error?) -> Void) { getDailyWeatherMock.count += 1 } }
true
0fbd8a1feca9348314e8094f5e91ac2d39d9584a
Swift
iron-mental/americano
/Terminal-iOS/MyStudy/StudyDetail/ViewComponent/Notice/NoticeViewComponent/NoticeDetailProtocols.swift
UTF-8
2,617
2.5625
3
[]
no_license
// // NoticeDetailProtocols.swift // Terminal-iOS // // Created by 정재인 on 2020/12/01. // Copyright © 2020 정재인. All rights reserved. // import UIKit protocol NoticeDetailViewProtocol: class { var presenter: NoticeDetailPresenterProtocol? { get set } var notice: Notice? { get set } var parentView: UIViewController? { get set } // PRESENTER -> VIEW func showNoticeDetail(notice: Notice) func showNoticeRemove(message: String) func showError(message: String) func showLoading() func hideLoading() } protocol NoticeDetailPresenterProtocol: class { var view: NoticeDetailViewProtocol? { get set } var interactor: NoticeDetailInteractorInputProtocol? { get set } var wireFrame: NoticeDetailWireFrameProtocol? { get set } // VIEW -> PRESENTER func viewDidLoad(notice: Notice) func removeButtonDidTap(notice: Notice) func modifyButtonDidTap(state: AddNoticeState, notice: Notice, parentView: NoticeDetailViewProtocol) } protocol NoticeDetailInteractorInputProtocol: class { var presenter: NoticeDetailInteractorOutputProtocol? { get set } var remoteDataManager: NoticeDetailRemoteDataManagerInputProtocol? { get set } // PRESENTER -> INTERACTOR func getNoticeDetail(notice: Notice) func postNoticeRemove(notice: Notice) } protocol NoticeDetailInteractorOutputProtocol: class { func getNoticeDetailSuccess(notice: Notice) func getNoticeDetailFailure(message: String) func removeNoticeResult(result: Bool, message: String) func sessionTaskError(message: String) } protocol NoticeDetailRemoteDataManagerInputProtocol: class { var interactor: NoticeDetailRemoteDataManagerOutputProtocol? { get set } func getNoticeDetail(studyID: Int, noticeID: Int) func postNoticeRemove(studyID: Int, noticeID: Int) } protocol NoticeDetailRemoteDataManagerOutputProtocol: class { func getNoticeDetailResult(result: BaseResponse<Notice>) func removeNoticeDetailResult(result: BaseResponse<String>) func sessionTaskError(message: String) } protocol NoticeDetailWireFrameProtocol: class { static func createNoticeDetailModule(notice: Int, studyID: Int?, title: String, parentView: UIViewController?, state: StudyDetailViewState) -> UIViewController func goToNoticeEdit(state: AddNoticeState, notice: Notice, parentView: NoticeDetailViewProtocol) }
true
2eca54b69da7abb8de9c4324463d6ecd912c0018
Swift
seizze/swift-pokergameapp
/CardGameApp/CardGameApp/Models/Players.swift
UTF-8
1,436
3.296875
3
[]
no_license
// // Players.swift // CardGameApp // // Created by Chaewan Park on 2020/02/17. // Copyright © 2020 Chaewan Park. All rights reserved. // import Foundation class Players { enum Number: Int { case two = 2 case three = 3 case four = 4 func invokePerPlayerCount<T>(_ block: () -> T) -> [T] { return (0..<rawValue).map { _ in block() } } } private let players: [Participant] var count: Int { return players.count } init(with number: Number) { self.players = number.invokePerPlayerCount { Participant() } } @discardableResult func repeatForEachPlayer<T>(_ transform: (Participant) -> T) -> [T] { return players.map { transform($0) } } } extension Players { func theHighest(in scores: [Score]) -> (Score, Card) { let highestScore = scores.max() ?? Score.none let highestCard = scores.filter { $0 == highestScore } .map { $0.highestCard } .compactMap { $0 } .max()! return (highestScore, highestCard) } } extension Players.Number: CaseIterable, Comparable { static func < (lhs: Players.Number, rhs: Players.Number) -> Bool { return lhs.rawValue < rhs.rawValue } static func invokePerMaxParticipantNumber(_ block: () -> ()) { return (0..<allCases.max()!.rawValue + 1).forEach { _ in block() } } }
true
01a4841a38425724f7697f01f77f1e0bf00a57e6
Swift
bhupendratrivedi/SampleCustomView
/SampleCustomView/CustomViews/ChangeColorView.swift
UTF-8
1,245
2.90625
3
[]
no_license
// // ChangeColorView.swift // SampleCustomView // // Created by Bhupendra Trivedi on 19/12/19. // Copyright © 2019 Bhupendra Trivedi. All rights reserved. // import UIKit class ChangeColorView: UIView { @IBOutlet var contentView: UIView! @IBOutlet var changeColorButton: UIButton! override init(frame: CGRect) { super.init(frame: frame) customInit() } required init?(coder: NSCoder) { super.init(coder: coder) customInit() } private func customInit() { // Load XIB Bundle.main.loadNibNamed("ChangeColorView", owner: self, options: nil) // contentView intializes as soon as xib is loaded. addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentView.backgroundColor = UIColor.clear self.backgroundColor = UIColor.cyan } @IBAction func changeColorButtonTapped(_ sender: Any) { let colors: [UIColor] = [UIColor.red, UIColor.green, UIColor.yellow, UIColor.orange, UIColor.black, UIColor.purple, UIColor.blue] let randomColorIndex = arc4random() % 6 self.backgroundColor = colors[Int(randomColorIndex)] } }
true
ef0cf78bc66a9a8be17ce92c32e27cdbf40e6cc2
Swift
Mister-Jam/Load-Users
/ChallengeV1/Managers/LoadUsersManager.swift
UTF-8
1,165
2.90625
3
[]
no_license
// // LoadUsersManager.swift // ChallengeV1 // // Created by King Bileygr on 5/3/21. // import Foundation //MARK:- URL Request final class LoadUsersManager { static let shared = LoadUsersManager() let baseUrl = Constants.apiUrl func getUsersData (success: @escaping ([UsersModel]) -> Void, failure: @escaping (String) -> Void) { guard let requestUrl = URL(string: self.baseUrl) else { return } URLSession.shared.dataTask(with: requestUrl) {(data, response, error) in if let httpResponse = response as? HTTPURLResponse { print("API Status: \(httpResponse.statusCode)") } guard let returnedApiData = data, error == nil else { print("The error is \(error?.localizedDescription ?? "There is an error")") return } do { let decodedData = try JSONDecoder().decode([UsersModel].self, from: returnedApiData) success(decodedData) } catch { failure("The decoding\(error)") } }.resume() } }
true
969163da8e76120df8ec1f7a114ed67b2eef2e33
Swift
kurczewski7/przyprawy6
/Przyprawy/Model/Bits.swift
UTF-8
3,436
2.953125
3
[]
no_license
// // Bits.swift // Przyprawy // // Created by Slawek Kurczewski on 12/12/2019. // Copyright © 2019 Slawomir Kurczewski. All rights reserved. // import Foundation import CoreData class Bits { var context: NSManagedObjectContext var product: ProductTable? var bitsArray: [Bool] = [Bool](repeating: false, count: 64) var bitsListCount: [Int] = [Int](repeating: 0, count: 64) var multiCheck: UInt64 = 0x0 init(context: NSManagedObjectContext) { self.context = context } var count: Int { get { return bitsArray.count } } subscript(index: Int) -> Bool { get { return bitsArray[index] } set { bitsArray[index] = newValue } } func clearData() { for i in 0..<bitsArray.count { bitsArray[i] = false bitsListCount[i] = 0 } } // var array: [Bool] { // get { return bitsArray } // set { bitsArray = newValue } // } func setBit(withBitNumber number: Int) -> UInt64 { let val: UInt64 = 0x1 return (number > 0) ? val << number : val } func setProduct(withProduct product: ProductTable?) { self.product = product } func readMultiCheck() { if let prod = self.product { multiCheck = UInt64(prod.multiChecked) for i in 0..<bitsArray.count { bitsArray[i] = (multiCheck & setBit(withBitNumber: i)) == 0 ? false : true } } } func setMultiChick(numberOfBit number: Int, boolValue value: Bool = true) { bitsArray[number] = value } func save() { var value: UInt64 = 0x0 for i in 0..<bitsArray.count { if bitsArray[i] { value = (value | setBit(withBitNumber: i)) } } if let prod = self.product { prod.multiChecked = Int64(value) do { try self.context.save() } catch { print("Error saveing context \(error)") } } print("ret value: \(value)") } func loadListBits() { var multiChecked: UInt64 = 0x0 if database.product.count > 0 { print("W bazie istnieje \(database.product.count) produktów") print("multiChecked: \(multiChecked)") for i in 0..<database.product.count { multiChecked = UInt64(database.product[i].multiChecked) updateBitsListCouut(forMultiChecked: multiChecked) } } } func updateBitsListCouut(forMultiChecked value: UInt64) { for i in 0..<bitsListCount.count { self.bitsListCount[i] += (value & self.setBit(withBitNumber: i)) == 0 ? 0 : 1 } } func isActiveList(withListNumber listNumber: Int) -> Bool { return self.bitsListCount[listNumber] == 0 ? false : true } func printBits() { let b1 = bitsArray[0] let b2 = bitsArray[1] let b3 = bitsArray[2] let b4 = bitsArray[3] let b5 = bitsArray[4] let b6 = bitsArray[5] let b7 = bitsArray[6] let b8 = bitsArray[7] let b9 = bitsArray[8] let b10 = bitsArray[9] let b11 = bitsArray[10] let b12 = bitsArray[11] let res = multiCheck print("val: \(b1),\(b2),\(b3),\(b4),\(b5),\(b6),\(b7),\(b8),\(b9),\(b10),\(b11),\(b12), res:\(res)") print("bitsListCount:\(bitsListCount)") } }
true
65c6fb4bb25d25a112de8e477e17c76f22c16366
Swift
kyle-skyllingstad/Excel-Fencing-Mobile-Application
/Excel Fencing App/Chatbot Starter Project/ViewController3.swift
UTF-8
10,513
3.109375
3
[]
no_license
// // ViewController3.swift // EXCEL FENCING MOBILE APPLICATION // Created by Kyle Skyllingstad // // Import necessary kits/libraries import UIKit import Firebase import FirebaseAuth import FirebaseFirestore import FirebaseDatabase // Class for screen 3, ViewController3 class ViewController3: UIViewController, UITextFieldDelegate { // Set Outlets for buttons, labels, and text fields // Text Fields @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! // Buttons @IBOutlet weak var signUpButton: UIButton! // Labels @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var useridLabel: UILabel! @IBOutlet weak var firstnameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Set up the text fields to allow the keyboard to be able to be hidden after typing has finished self.firstNameTextField.delegate = self self.lastNameTextField.delegate = self self.emailTextField.delegate = self self.passwordTextField.delegate = self // Call function to set up the UI elements setUpElements() } // Functions //////////////////////////////// // Function for stylizing elements func setUpElements() { // Hide the error label errorLabel.alpha = 0 // Style the text fields Utilities.styleTextField(firstNameTextField) Utilities.styleTextField(lastNameTextField) Utilities.styleTextField(emailTextField) Utilities.styleTextField(passwordTextField) } // Hide keyboard when the user touches outside the keyboard override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } // Hide keyboard when the user presses the return key func textFieldShouldReturn(_ textField: UITextField) -> Bool { firstNameTextField.resignFirstResponder() lastNameTextField.resignFirstResponder() emailTextField.resignFirstResponder() passwordTextField.resignFirstResponder() return (true) } // Check the fields and validate that the data is correct. If everything is correct, this method returns nil. Otherwise, it returns the error message as a string. func validateFields() -> String? { // Check that all fields are filled in - if empty, returns error message to fill them all in if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || lastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { // Error message return "Please fill in all fields." } // Make sure entered email address is just letters, numbers, ".", and "@" // Get email from text field let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) // Variable set to just letters, numbers, ".", and "@" let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.@") // If something other than letters, numbers, ".", and "@" is entered, return error informing user to only use letters and/or numbers. if email.rangeOfCharacter(from: characterset.inverted) != nil { return "Email address must contain only letters and/or numbers." } // Make sure email address has the "@" symbol, otherwise tell the user it is invalid guard let emailidx = email.firstIndex(of: "@") else { return "Email address is invalid. Please try a different one." } // Check if the password is secure // Get the password from the text field let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) // If the password turns out to not be valid if Utilities.isPasswordValid(cleanedPassword) == false { // Password isn't secure enough return "Please make sure your password is at least 8 characters long and contains at least one special character and one number." } return nil } // If the signup button is tapped @IBAction func signUpTapped(_ sender: Any) { // Validate the fields let error = validateFields() // See if there is an error if error != nil { // There's something wrong with the fields, show error message showError(error!) } // Otherwise no error else { // Create cleaned versions of the data let firstName = firstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let lastName = lastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) // Find the index of the "@" symbol guard let emailidx = email.firstIndex(of: "@") else { return } // Get User ID from email (characters before the "@" symbol) var userid = String(email.prefix(upTo: emailidx)) // Set text on the User ID label and the name label (both invisible for storage purposes) useridLabel.text = userid firstnameLabel.text = firstName // Create the user in Firestore Auth.auth().createUser(withEmail: email, password: password) { (result, err) in // Check for errors if err != nil { // There was an error creating the user in Firestore self.showError("Error creating user. Please try a different email.") } else { // The user was created successfully, now store the first name and the last name let db = Firestore.firestore() // Create identity document identified by User ID db.collection("users").document(userid).setData(["firstname":firstName, "lastname":lastName, "Score":"0", "Number":"0", "Score Percentage":"0", "Total Score":"0", "Total Number":"0", "Overall Percentage":"0", "Counter":"0"]) // Old code for testing purposes /* // Create backup Firestore identity document with random key db.collection("users").addDocument(data: ["firstname":firstName, "lastname":lastName, "User ID":userid, "uid": result!.user.uid]) { (error) in if error != nil { // Show error message self.showError("User data couldn't be saved due to an error") } } */ // Create the user in the real-time Firebase Database (for backing up, otherwise unused) // Create user reference let ref = Database.database().reference() // Create backup user profile ref.child("users").child(userid).setValue(["firstname":firstName, "lastname":lastName, "Score":"0", "Number":"0", "Score Percentage":"0", "Total Score":"0", "Total Number":"0", "Overall Percentage":"0", "Counter":"0"]) // Transition to the main home screen self.transitionToMain() } } } } // Function for showing error on the label func showError(_ message:String) { // Make error message and make it visible errorLabel.text = message errorLabel.alpha = 1 } // Function for transitioning to VC5, or Main screen func transitionToMain() { // Get User ID and first name from their respective labels let useridString = useridLabel.text let firstnameString = firstnameLabel.text // Create link to VC5 guard let VC = storyboard?.instantiateViewController(identifier: "VC5") as? ViewController5 else { return } // Present (go to) VC5 VC.modalPresentationStyle = .fullScreen VC.modalTransitionStyle = .flipHorizontal present(VC, animated: true) // Post notification of created email-based user ID text, as well as their first name text, to be available to this screen, VC3, as well as the other screens (ViewControllers) NotificationCenter.default.post(name: Notification.Name("useridin"), object: useridString) NotificationCenter.default.post(name: Notification.Name("firstnamein"), object: firstnameString) } // Function for if back button from this screen (VC3) back to the previous one (VC2) is tapped @IBAction func didTapButton3to2() { // Create link to VC2 guard let VC = storyboard?.instantiateViewController(identifier: "VC2") as? ViewController2 else { return } // Present (go to) VC2 VC.modalPresentationStyle = .fullScreen VC.modalTransitionStyle = .crossDissolve present(VC, animated: true) } }
true
d226e05376db826473ac9b21226f266138e2a35e
Swift
Arieandel/ContinuumCompanionApp
/CompanionApp/CompanionApp/PageGroup/PageListScreen.swift
UTF-8
1,664
2.8125
3
[]
no_license
// // PageListScreen.swift // TableView // // Created by Ariel Andelt on 2019-03-27. // Copyright © 2019 Ariel Andelt. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FirebaseDatabase import FirebaseStorage class PageListScreen: UIViewController { @IBOutlet weak var temp: UITableView! var pages: [Page] = [] //an array of Page type objects //var testImage : UIImage! override func viewDidLoad() { super.viewDidLoad() //pages = createArray() //let tableView = UITableView(frame: self.view, style: .normal) temp.delegate = self temp.dataSource = self } } extension PageListScreen: UITableViewDataSource, UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return pages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let page = pages[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "PageCell") as! PageCell cell.setPage(page: page) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "displayContent", sender: pages[indexPath.row]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?){ let cD = segue.destination as! ContentDisplay cD.someString = (sender as! Page).title print(cD.someString) } }
true
cd4af5571c53b68b78937634843f0999ebeaa0fc
Swift
viratStudyData/NewTableViewDataSource
/Phunware/CommonFunctions/Helper/Validation.swift
UTF-8
2,791
2.859375
3
[]
no_license
// // Validation.swift // Phunware // // Created by Gurleen on 20/08/19. // Copyright © 2019 MAC_MINI_6. All rights reserved. // import UIKit //MARK:- Alert Types enum AlertType: String { case success = "SUCCESS" case apiFailure = "API_FAILURE" case validationFailure = "VALIDATION_FAILURE" var title: String { return NSLocalizedString(self.rawValue, comment: "") } var color: UIColor { return Color.buttonBlue.value // switch self { // case .validationFailure: // return Color.buttonBlue.value // case .apiFailure: // return Color.gradient1.value // case .success: // return Color.success.value // } } } //MARK:- Alert messages to be appeared on failure enum AlertMessage: String { case EMPTY_EMAIL_PHONE = "EMPTY_EMAIL_PHONE" case EMPTY_EMAIL = "EMPTY_EMAIL" case INVALID_EMAIL = "INVALID_EMAIL" case INVALID_PHONE = "INVALID_PHONE" case INVALID_EMAIL_PHONE = "INVALID_EMAIL_PHONE" case EMPTY_PASSWORD = "EMPTY_PASSWORD" case EMPTY_PHONE = "EMPTY_PHONE" case INVALID_PASSWORD = "INVALID_PASSWORD" case EMPTY_CONFIRM_PASSWORD = "EMPTY_CONFIRM_PASSWORD" case INVALID_CONFIRM_PASSWORD = "INVALID_CONFIRM_PASSWORD" case PASSWORD_NOT_MATCH = "PASSWORD_NOT_MATCH" case EMPTY_NAME = "EMPTY_NAME" case INVALID_NAME = "INVALID_NAME" case EMPTY_CURRENT_PSW = "EMPTY_CURRENT_PSW" case EMPTY_NEW_PSW = "EMPTY_NEW_PSW" case INVALID_CURRENT_PSW = "INVALID_CURRENT_PSW" case INVALID_NEW_PSW = "INVALID_NEW_PSW" case EMPTY_OTP = "EMPTY_OTP" var localized: String { return NSLocalizedString(self.rawValue, comment: "") } } //MARK:- Check validation failed or not enum Valid { case success case failure(AlertType, AlertMessage) } //MARK:- RegExes used to validate various things enum RegEx: String { case EMAIL = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" // Email case PASSWORD = "^.{6,100}$" // Password length 6-100 case NAME = "^[A-Z]+[a-zA-Z]*$" // SandsHell case PHONE_NO = "(?!0{5,15})^[0-9]{5,15}" // PhoneNo 5-15 Digits case EMAIL_OR_PHONE = "" case All = "ANY_TEXT" } //MARK:- Validation Type Enum to be used with value that is to be validated when calling validate function of this class enum ValidationType { case EMAIL case PHONE case EMAIL_OR_PHONE case NAME case PASSWORD case CONFIRM_PASSWORD case CURRENT_PSW case NEW_PSW case LOGIN_PSW case EMAIL_OR_PHONE_FORGOT_PSW } extension String { public var isNotBlank: Bool { get { let trimmed = trimmingCharacters(in: .whitespacesAndNewlines) return !trimmed.isEmpty } } }
true
d0e7e35c306141139b0ddec51241c8587dd3247e
Swift
wwCondor/Bits
/'Bits/'Bits/Delete?/MenuBar.swift
UTF-8
7,195
2.71875
3
[]
no_license
// // MenuBarController.swift // 'Bits // // Created by Wouter Willebrands on 09/10/2019. // Copyright © 2019 Studio Willebrands. All rights reserved. // import UIKit class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { // To the view we add a collectionView that will hold all the buttons lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = UIColor(named: "GentlemanGray") // MARK: Set Menubar Color collectionView.dataSource = self collectionView.delegate = self return collectionView }() let cellId = "cellId" let menuBarImageNames = ["SortIcon", "AddIcon", "ShareIcon"] // Array that holds the icon stringnames let newEntryLauncher = NewEntryLauncher() // let sortMenu = SortMenuLauncher() // let shareMenu = ShareMenuLauncher() override init(frame: CGRect) { super.init(frame: frame) // backgroundColor = UIColor(named: "WashedWhite") // if we see this it means collectionView is not covering the UIView container // Registers a custom class cell for use in creating new collection view cells. collectionView.register(MenuBarCell.self, forCellWithReuseIdentifier: cellId) // Adds the collectioinView to the subView addSubview(collectionView) // Constraints setup addConstraintsWithFormat("H:|[v0]|", views: collectionView) addConstraintsWithFormat("V:|[v0]|", views: collectionView) // collectionView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap))) // This ensures there is always an intial icon in selected state when app is launched. // Currently set to addIcon as default to draw attention to user when app is opened. User opened app so it's likely they want to add a post let selectedIndexPath = IndexPath(item: 1, section: 0) collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: []) } // MARK: Delegate Methods // This is the amount of buttons inside the collectionView func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return menuBarImageNames.count } // Returns a reusable cell object located by its identifier func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuBarCell cell.imageView.image = UIImage(named: menuBarImageNames[indexPath.item])?.withRenderingMode(.alwaysTemplate) // This uses the images from the array for each button // cell.tintColor = UIColor(named: "SuitUpSilver") // This renders a layer over the icon's original color // this is now rendered in cell instead // cell.backgroundColor = UIColor(named: "WashedWhite") // color of the cells within the container return cell } // This sets the size of the menubar cells that contain the buttons func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // Since we have 3 cells the width of each cell is the screenwidth divided by 3 // We want the cell to fill the collectionView, so height = frame.height return CGSize(width: frame.width / 3, height: frame.height) } // This sets the spacing between the buttons, if spacing > 0, cells will be move to new row func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } @objc func tap(sender: UITapGestureRecognizer) { if let indexPath = self.collectionView.indexPathForItem(at: sender.location(in: self.collectionView)) { // MARK: Sort/Add/Share Methods should be called in here if indexPath.item == 0 { newEntryLauncher.menuItemSelected = .sortEntry // Here we update the selected item print("Sort") } else if indexPath.item == 1 { newEntryLauncher.menuItemSelected = .newEntry // Here we update the selected item newEntryLauncher.presentView() print("Add") } else if indexPath.item == 2 { newEntryLauncher.menuItemSelected = .shareEntry // Here we update the selected item print("Share") } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: MenuBarCell // Since it very closely related to the MenuBar it is inside the MenuBar file class MenuBarCell: BaseCell { let imageView: UIImageView = { let imageView = UIImageView() // imageView.backgroundColor = UIColor(named: "GentlemanGray") imageView.image = UIImage(named: "AddIcon")?.withRenderingMode(.alwaysTemplate) imageView.tintColor = UIColor(named: "WashedWhite") // MARK: Set Button Icon Color return imageView }() // this adds a iconColor change on tap (might not use this as you can't see the menubar when an item is tapped) // override var isSelected: Bool { // didSet { // imageView.tintColor = isSelected ? UIColor(named: "WashedWhite") : UIColor(named: "SuitUpSilver") // } // } // // override var isHighlighted: Bool { // didSet { // imageView.tintColor = isHighlighted ? UIColor(named: "WashedWhite") : UIColor(named: "SuitUpSilver") // } // } override func setupViews() { super.setupViews() // backgroundColor = UIColor.blue addSubview(imageView) // This sets te size of the icon inside the cell let imageViewIconSquareSide = bounds.height * (3/7) // Since it is a square we can set them both up here at the same time imageView.translatesAutoresizingMaskIntoConstraints = false // enabels autoLayout for menuBar imageView.heightAnchor.constraint(equalToConstant: imageViewIconSquareSide).isActive = true imageView.widthAnchor.constraint(equalToConstant: imageViewIconSquareSide).isActive = true // This centers the icon inside the cell addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) } }
true
19fda0417ead2a850327dcb0982e641f54802061
Swift
krgoodnews/PodcastsClone
/CopyPodcasts/Data Sources/TableViewDataSource.swift
UTF-8
959
2.890625
3
[]
no_license
// // TableViewDataSource.swift // HeadlinesApp // // Created by Goodnews on 2018. 7. 10.. // Copyright © 2018년 Mohammad Azam. All rights reserved. // import UIKit class TableViewDataSource<Cell: UITableViewCell, ViewModel>: NSObject, UITableViewDataSource { private var cellID: String! private var items: [ViewModel]! var configureCell: (Cell, ViewModel) -> () init(cellID: String, items: [ViewModel], configureCell: @escaping (Cell, ViewModel) -> ()) { self.cellID = cellID self.items = items self.configureCell = configureCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, for: indexPath) as! Cell let item = self.items[indexPath.row] self.configureCell(cell,item) return cell } }
true
86ae623a9666edc418d12c27f659696689e17938
Swift
Ram-cs/Outside-College-Projects-Swift-Firebase
/mapSearch/mapSearch/ViewController.swift
UTF-8
3,058
2.578125
3
[]
no_license
// // ViewController.swift // mapSearch // // Created by Ram Yadav on 7/30/17. // Copyright © 2017 Ram Yadav. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, UISearchBarDelegate { @IBOutlet weak var myMap: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func searchBar(_ sender: Any) { let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.delegate = self present(searchController, animated: true, completion: nil) } // @IBAction func myLocation(_ sender: Any) { // self.myMap.showsUserLocation = true; // self.myMap.setUserTrackingMode(.follow, animated: true) // } // func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { //ignoring user UIApplication.shared.beginIgnoringInteractionEvents() //Activity Indicators let ActivityIndicator = UIActivityIndicatorView() ActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray ActivityIndicator.center = self.view.center ActivityIndicator.startAnimating() self.view.addSubview(ActivityIndicator) //hidden seach bar searchBar.resignFirstResponder() dismiss(animated: true, completion: nil) //create a search request let searchRequest = MKLocalSearchRequest() searchRequest.naturalLanguageQuery = searchBar.text; let activeSearch = MKLocalSearch(request: searchRequest) ActivityIndicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() activeSearch.start { (result, error) in if error != nil { print("ERROR OCCURED!") } else { //remove original annotation let annotations = self.myMap.annotations self.myMap.removeAnnotations(annotations) //Getting Data let latitue = result?.boundingRegion.center.latitude let longitude = result?.boundingRegion.center.longitude //create annotation let annotation = MKPointAnnotation() annotation.title = searchBar.text annotation.coordinate = CLLocationCoordinate2D(latitude: latitue!, longitude: longitude!) self.myMap.addAnnotation(annotation) //zooming the place let location = CLLocationCoordinate2DMake(latitue!, longitude!) let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegionMake(location, span) self.myMap.setRegion(region, animated: true) } } } }
true
2b3942d9c1fd63ab2e9c83ade7ebd094a5152f6b
Swift
4-x/WaterRowerData-iOS
/Sources/WaterRowerData-BLE/Internal/RowerDataSpecification/RowerDataAveragePaceField.swift
UTF-8
369
2.84375
3
[ "Apache-2.0" ]
permissive
import Foundation let rowerDataAveragePaceField: Field = RowerDataAveragePaceField() private struct RowerDataAveragePaceField: Field { var name = "Average Pace" var format: Format = .UInt16 private let requirement = BitRequirement(bitIndex: 4, bitValue: 1) func isPresent(in data: Data) -> Bool { return requirement.check(in: data) } }
true
64dd55f96510d656bb8bdc8915727617ec5d3604
Swift
hnovais95/iOS-Dev
/SwiftQuiz/SwiftQuiz/Core/Model/Quiz.swift
UTF-8
567
3.375
3
[]
no_license
// // Quiz.swift // SwiftQuiz // // Created by Heitor Novais | Gerencianet on 05/05/21. // struct Quiz: Hashable { private(set) var question: String private(set) var options: [String] private let corretedAnsewer: String init(question: String, options: [String], corretedAnsewer: String) { self.question = question self.options = options self.corretedAnsewer = corretedAnsewer } func isCorrect(optionIndex: Int) -> Bool { let answer = options[optionIndex] return answer == corretedAnsewer } }
true
e36ef159f1353d5697e5b7b33ee506748d292c00
Swift
deayqf/Field-Survey
/Field Survey/Field Survey/Model/FieldSurveyJSONParser.swift
UTF-8
1,688
2.796875
3
[]
no_license
// // FieldSurveyJSONParser.swift // Field Survey // // Created by David Auger on 11/2/17. // Copyright © 2017 David Auger. All rights reserved. // import Foundation class FieldSurveyJSONParser { static let dateFormatter = DateFormatter() class func parse( _ data: Data ) -> [ FieldSurvey ] { var fieldSurveys = [ FieldSurvey ]() dateFormatter.dateFormat = "YYYY-MM-dd HH:mm" if let json = try? JSONSerialization.jsonObject( with: data, options: [] ), let root = json as? [ String: Any ], let status = root[ "status" ] as? String, status == "ok" { if let observations = root[ "observations" ] as? [ Any ] { for observation in observations { if let observation = observation as? [ String: String ] { if let className = observation[ "classification" ], let title = observation[ "title" ], let description = observation[ "description" ], let dateString = observation[ "date" ], let date = dateFormatter.date( from: dateString ) { if let fieldSurvey = FieldSurvey( className: className, title: title, description: description, date: date ) { fieldSurveys.append( fieldSurvey ) } } } } } } return fieldSurveys } }
true
6713f6268ff6493ea97c5b134a3d7564163f490e
Swift
simpleLiYu/SwiftUI-Template-MVVM
/SwiftUI-MVVM-Template/Models/Item.swift
UTF-8
632
3.25
3
[]
no_license
// // Item.swift // SwiftUI-Template-MVVM // // Created by Chris on 3/26/20. // Copyright © 2020 Chris Dlc. All rights reserved. // import Foundation /// This extends the CoreData Managed Object /// Use this to add any custom methods or computed properties to the Item object extension Item { /// Example of custom method func printItem() { if let id = self.id { print("--- #\(id.uuidString)") print("value: \(self.value)") print("--- END ---") } } /// Example of computed method var isValueLowerThanFive: Bool { return value < 5 } }
true
90ccb6588bbe8bf7d56e7a80bf9dc063a342a097
Swift
ipv02/WeatherTestTask
/WeatherTestTask/Helpers/UnixConvertor.swift
UTF-8
2,059
3.421875
3
[]
no_license
import UIKit enum typeUnixConvertor { case time case timeWithTimezone case date case weekDay } func unixConvertor(unixTime: Double, timezone: Int = 0, type: typeUnixConvertor) -> String { let time = NSDate(timeIntervalSince1970: unixTime) let dateFormatter = DateFormatter() switch type { case .date: dateFormatter.dateFormat = "EEEE, MMM d" let dateAsString = dateFormatter.string(from: time as Date) dateFormatter.dateFormat = "EEEE, MMM d" let date = dateFormatter.date(from: dateAsString) dateFormatter.dateFormat = "EEEE, MMM d" let date24 = dateFormatter.string(from: date!) return date24 case .time: dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.system.identifier) as Locale? dateFormatter.dateFormat = "hh:mm a" let dateAsString = dateFormatter.string(from: time as Date) dateFormatter.dateFormat = "h:mm a" let date = dateFormatter.date(from: dateAsString) dateFormatter.dateFormat = "HH:mm" let date24 = dateFormatter.string(from: date!) return date24 case .timeWithTimezone: dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.system.identifier) as Locale? dateFormatter.timeZone = TimeZone(secondsFromGMT: timezone) dateFormatter.dateFormat = "hh:mm a" let dateAsString = dateFormatter.string(from: time as Date) dateFormatter.dateFormat = "h:mm a" let date = dateFormatter.date(from: dateAsString) dateFormatter.dateFormat = "HH:mm" let date24 = dateFormatter.string(from: date!) return date24 case .weekDay: dateFormatter.dateFormat = "EEEE" let dateAsString = dateFormatter.string(from: time as Date) dateFormatter.dateFormat = "EEEE" let date = dateFormatter.date(from: dateAsString) dateFormatter.dateFormat = "EEEE" let date24 = dateFormatter.string(from: date!) return date24 } }
true
99dd917f2763589844a128abfa14960c0f0590b6
Swift
Swoop12/SpiltCoffee
/SpiltCoffee/Resources/Extensions/UIViewController+Extension.swift
UTF-8
5,608
2.71875
3
[]
no_license
// // UIView+Extension.swift // SpiltCoffee // // Created by DevMountain on 10/5/18. // Copyright © 2018 DevMountain. All rights reserved. // import UIKit import AVKit //MARK: - Simple View Presentations extension UIViewController: GenericDataSourceVCDelegate { func presentSimpleAlertWith(title: String, body: String?){ let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert) let okayAction = UIAlertAction(title: "Okay", style: .cancel, handler: nil) alertController.addAction(okayAction) self.present(alertController, animated: true, completion: nil) } func presentAreYouSureAlert(title: String, body: String?, completion: @escaping (UIAlertAction) -> ()){ let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert) let okayAction = UIAlertAction(title: "Yes", style: .default, handler: completion) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(okayAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } func prepareAndPerformSegue<T>(for dataType: DataType, with data: T?){ var viewController: UIViewController! switch dataType { case .roaster: viewController = UIStoryboard(name: "RoasterProfile", bundle: .main).instantiateViewController(withIdentifier: "RoasterProfile") let vc = viewController as? RoasterProfileViewController vc?.roaster = data as? Roaster case .enthusiast: viewController = UIStoryboard(name: "UserProfile", bundle: .main).instantiateViewController(withIdentifier: "UserProfile") let vc = viewController as? BaseUserProfileViewController case .post: viewController = UIStoryboard(name: "RoasterProfile", bundle: .main).instantiateViewController(withIdentifier: "PostViewController") let vc = viewController as? PostDetailViewController vc?.post = data as? Post case .product, .coffeeBean: viewController = UIStoryboard(name: "RoasterProfile", bundle: .main).instantiateViewController(withIdentifier: "ProductDetailVC") let vc = viewController as? ProductDetailViewController vc?.product = data as? Product case .recepie: viewController = UIStoryboard(name: "Recepie", bundle: .main).instantiateInitialViewController() let vc = viewController as? RecepieDetailViewController vc?.recepie = data as? Recepie default: fatalError("Print You cliced on a cell I was not prepared for") } self.navigationController?.pushViewController(viewController, animated: true) } func unwrapTextFields(_ textFields: UITextField...) -> [String]?{ var textArray: [String] = [] for textField in textFields{ if let text = textField.text, !text.isEmpty{ textArray.append(text) }else { return nil } } return textArray } func presentAVPlayerVC(with player: AVPlayer){ let controller = AVPlayerViewController() controller.player = player self.present(controller, animated: true, completion: { player.play() }) } } //MARK: - TextField and TextView Delegates extension UIViewController: UITextFieldDelegate, UITextViewDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } public func textViewShouldEndEditing(_ textView: UITextView) -> Bool { textView.resignFirstResponder() return true } } //MARK: - ImagePicker Extension extension UIViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{ func presentImagePickerWith(alertTitle: String, message: String?){ let imagePicker = UIImagePickerController() imagePicker.delegate = self let alert: UIAlertController! if UIDevice.current.userInterfaceIdiom == .phone{ alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .actionSheet) }else{ alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert) } if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){ alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (_) in imagePicker.sourceType = .photoLibrary UIImagePickerController.availableMediaTypes(for: .photoLibrary) self.present(imagePicker, animated: true, completion: nil) })) } if UIImagePickerController.isSourceTypeAvailable(.camera){ alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (_) in imagePicker.sourceType = .camera imagePicker.cameraCaptureMode = .photo self.present(imagePicker, animated: true, completion: nil) })) } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true) } @objc public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
true
132862e381c82b8a071b4087835f35a8968852ea
Swift
MartyCullen/SwiftPlaygroundWorkspace
/Switch.playground/Contents.swift
UTF-8
366
3.15625
3
[]
no_license
//: Playground - noun: a place where people can play import UIKit // SWITCH stuff (pg7/146) let veg = "red pepper" switch veg { case "celery": print("Ewww") case "cuke": print("ughhh") case let x where x.hasSuffix("pepper"): print("spicy") default: print("other") } // NO BREAK REQUIRED //No implicit fall through but can use explicit fallthrough
true
80f3fc48f8bbd8f46a6f8229c2b81380b5f87366
Swift
CosmosSwift/swift-cosmos
/Sources/Cosmos/Crypto/Keys/KeyError/Keys+Errors.swift
UTF-8
324
2.953125
3
[ "Apache-2.0" ]
permissive
struct KeyNotFoundError: Swift.Error { static let keyNotFoundCode = 1 let code: Int let name: String // NewErrKeyNotFound returns a standardized error reflecting that the specified key doesn't exist init(name: String) { self.code = Self.keyNotFoundCode self.name = name } }
true
992f112413ff9028e96d78ec872e4917de0016d3
Swift
swm93/media-manager
/MediaManager/Controllers/MediaDetailControlsViewController.swift
UTF-8
1,786
2.515625
3
[]
no_license
// // MediaDetailControlsViewController.swift // MediaManager // // Created by Scott Mielcarski on 2017-11-08. // Copyright © 2017 Scott Mielcarski. All rights reserved. // import Foundation import UIKit class MediaDetailControlsViewController : UIViewController { @IBOutlet weak var widthConstraint: NSLayoutConstraint! public var mediaObject: ManagedMedia! private let _buttonSpacing: CGFloat = 8 private var _spotifyUri: String? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let view: UIStackView = widthConstraint.firstItem as! UIStackView let buttonWidth: CGFloat = self.view.frame.height let buttonCount: Int = view.subviews.count self.widthConstraint.constant = (CGFloat(buttonCount) * buttonWidth) + (CGFloat(buttonCount - 1) * self._buttonSpacing) } @IBAction public func playOnSpotify() { if let song: SongManaged = mediaObject as? SongManaged { if let uri: String = self._spotifyUri { Spotify.shared.play(uri: uri) } else { if var query: String = song.name { if let artistName: String = song.album?.artist?.name { query.append(" \(artistName)") } Spotify.shared.search(query: query) { (uri: URL) in self._spotifyUri = uri.absoluteString Spotify.shared.play(uri: uri.absoluteString) } } } } } @IBAction public func findOnLastFM() { } }
true
6e0602ce96dbd79839f2cad7fda1a0f59bb1c7a7
Swift
appteur/wemos_client_ios
/iotKit/Source/Data/Models/IOTDevice.swift
UTF-8
504
2.734375
3
[]
no_license
// // IOTDevice.swift // iotKit // // Created by Seth on 12/30/17. // Copyright © 2017 Seth. All rights reserved. // import Foundation protocol IOTDevice: Codable { var identifier: String { get set } var description: String { get set } var name: String { get set } var status: String { get set } var type: String { get set } } struct Device: IOTDevice { var identifier: String var description: String var name: String var status: String var type: String }
true
c90f4770b60dcb32514db284535d4f25cbda0a95
Swift
BCSwift19-S/weather-gift-richwli
/WeatherGift/WeatherLocation.swift
UTF-8
524
2.875
3
[]
no_license
// // WeatherLocation.swift // WeatherGift // // Created by BC Swift Student Loan 1 on 3/19/19. // Copyright © 2019 Richard Li. All rights reserved. // import Foundation import Alamofire class WeatherLocation{ var name = "" var coordinates = "" func getWeather() { let weatherURL = urlBase + urlAPIKey + coordinates print(weatherURL) Alamofire.request(weatherURL).responseJSON { response in print(response) } } }
true
946a882b02b72530158b36edf5f5eef2957c143f
Swift
MarcJacques/Algorithm-Solutions-In-Swift
/AlgoExpert/Tournament Winner/TournamentWinner.swift
UTF-8
1,166
3.703125
4
[]
no_license
// // TournamentWinner.swift // Algorithms In Swift // // Created by Boudhayan Biswas on 17/07/21. // import Foundation let HOME_TEAM_WON = 1 /** Time Complexity: O(N) Space Complexity: O(k) Note: where n is the number of competitions and k is the number of teams */ func tournamentWinner(_ competitions: [[String]], _ results: [Int]) -> String { var winnerTracker = [String: Int]() var winner: (name: String, count: Int) = ("", 0) for idx in 0..<competitions.count { let competition = competitions[idx] if results[idx] == HOME_TEAM_WON { // home team wins let team = competition[0] winnerTracker[team, default: 0] += 1 if winnerTracker[team]! > winner.count { winner.name = team winner.count = winnerTracker[team]! } } else { //away team wins let team = competition[1] winnerTracker[team, default: 0] += 1 if winnerTracker[team]! > winner.count { winner.name = team winner.count = winnerTracker[team]! } } } return winner.name }
true
f569870ec49154fa6df228ea82904e819c07374b
Swift
MattSHallatt/Plantable
/PlantDiary/Data/Stages/BuddingStage.swift
UTF-8
861
2.6875
3
[]
no_license
// // BuddingStage.swift // PlantDiary // // Created by Matthew Hallatt on 06/06/2020. // Copyright © 2020 Matthew Hallatt. All rights reserved. // import CoreData final class BuddingStage: NSManagedObject { @NSManaged fileprivate(set) var buddingDate: Date @discardableResult static func create( in context: NSManagedObjectContext, at buddingDate: Date ) -> BuddingStage { let entityName = "BuddingStage" guard let object = NSEntityDescription.insertNewObject( forEntityName: entityName, into: context) as? BuddingStage else { fatalError("Failed to create BuddingStage") } object.buddingDate = buddingDate return object } } extension BuddingStage: Stage { var stageStartDate: Date { return buddingDate } }
true
9a5cf48e42a0cbfee5b6d58c680f071f5858b036
Swift
BadChoice/handesk-ios
/handesk/Views/CommentView.swift
UTF-8
883
2.921875
3
[]
no_license
import SwiftUI struct CommentView : View { let comment:TicketComment var body: some View { VStack(alignment: .leading){ HStack{ Gravatar(email: comment.author.email) Text(comment.author.name).foregroundColor(Color.gray).font(.subheadline) Spacer() Text(comment.created_at).font(.caption).foregroundColor(Color.gray) } Text(comment.body).font(.callout).lineLimit(nil) }.padding() .background(comment.isNote ? Color("Note") : Color.white) } } #if DEBUG struct CommentView_Previews : PreviewProvider { static var previews: some View { Group{ CommentView(comment: TicketComment()) CommentView(comment: TicketComment(isPrivate:true)) }.previewLayout(.fixed(width: 300, height: 70)) } } #endif
true
af18ef6aa9be9e411b5657a9e6a5816d3c6d0afd
Swift
manenga/LogInWithEncryption
/LogInWithEncryption/Extensions.swift
UTF-8
1,571
3.28125
3
[]
no_license
// // Extensions.swift // LogInWithEncryption // // Created by Manenga Mungandi on 2019/07/14. // Copyright © 2019 Manenga Mungandi. All rights reserved. // import UIKit import SwiftUI import CryptoSwift prefix operator ⋮ prefix func ⋮(hex:UInt32) -> Color { return Color(hex) } extension Color { init(_ hex: UInt32, opacity:Double = 1.0) { let red = Double((hex & 0xff0000) >> 16) / 255.0 let green = Double((hex & 0xff00) >> 8) / 255.0 let blue = Double((hex & 0xff) >> 0) / 255.0 self.init(.sRGB, red: red, green: green, blue: blue, opacity: opacity) } } let hexColor:(UInt32) -> (Color) = { return Color($0) } extension String { public func encrypt(key: String, iv: String) throws -> String { let encrypted = try AES(key: key, iv: iv, padding: .pkcs7).encrypt([UInt8](self.data(using: .utf8)!)) return Data(encrypted).base64EncodedString() } public func decrypt(key: String, iv: String) throws -> String { guard let data = Data(base64Encoded: self) else { return "" } let decrypted = try AES(key: key, iv: iv, padding: .pkcs7).decrypt([UInt8](data)) return String(bytes: decrypted, encoding: .utf8) ?? self } } extension UIViewController { public func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Oh, okay.", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
true
8a9baf027e2e660032f8633a391f92c4dac10552
Swift
Nizelan/API-App
/API App/Model/TryTooTutorial.swift
UTF-8
553
2.5625
3
[]
no_license
// // TryTooTutorial.swift // API App // // Created by Nizelan on 09.06.2020. // Copyright © 2020 Nizelan. All rights reserved. // import Foundation import MapKit class Tutorial: NSObject, MKAnnotation { let title: String? let placeUa: String? var coordinate: CLLocationCoordinate2D init(title: String?, placeUa: String?, coordinate: CLLocationCoordinate2D) { self.title = title self.placeUa = placeUa self.coordinate = coordinate } var subtitle: String? { return placeUa } }
true
93b71a7977cf747e266f855560383598042777f0
Swift
malekwasim/CrewDemo
/CrewDemo/Code/Application/ViewControllers/Home/Cell/FlightCell.swift
UTF-8
1,354
2.578125
3
[]
no_license
// // FlightCell.swift // CrewDemo // // Created by Wasim on 14/11/19. // Copyright © 2019 Wasim. All rights reserved. // import UIKit class FlightCell: UITableViewCell { @IBOutlet weak var btnIcon: UIButton! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblSubtitle: UILabel! @IBOutlet weak var lblTime: UILabel! @IBOutlet weak var lblTimeStatus: UILabel! 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 } func setupCell(_ item: FlightDetail) { lblTitle.text = "\(item.departure ?? "") - \(item.destination ?? "")" lblTime.text = "\(item.timeDepart ?? "") - \(item.timeArrive ?? "")" let status = Utility.getIconForDutyCode(item) self.btnIcon.setTitle(status.icon, for: .normal) lblSubtitle.text = status.subtitle if let value = status.strTime { lblTime.text = value lblTimeStatus.isHidden = false lblTimeStatus.text = STR_MATCH_CREW // No idea if this has to be static or dynamic, so assumes static } else { lblTimeStatus.isHidden = true } } }
true
9105d79bdd75b9c9c8330831e9483bb68143e0ef
Swift
benedelstein/BodyPoseDetection
/AVSessionTest/BodyPoseViewController.swift
UTF-8
8,358
2.703125
3
[]
no_license
// // BodyPoseViewController.swift // AVSessionTest // // Created by Ben Edelstein on 7/4/20. // /* flow of events 1) frame comes in 2) image request handler runs the detect pose request 3) pose request calls handleVisionResults() when done 4) get bounding box for each person, scale it, draw it 5) draw points for each person 6) update UI all at once, scaling and rotating to get the right orientation */ import UIKit import AVFoundation import Vision @available(iOS 14.0, *) class BodyPoseViewController: CameraViewController { private var poseOverlay: CALayer! = nil private var requests = [VNRequest]() // array of vision requests to process private let bodyPoseDetectionMinConfidence: VNConfidence = 0.6 private let bodyPoseRecognizedPointMinConfidence: VNConfidence = 0.1 // why is this so low? override func viewDidLoad() { super.viewDidLoad() // sets up the AVSession setupLayers() setupVision() // register detect body pose request startCaptureSession() } /// setup method to be able to display body points later on func setupLayers() { poseOverlay = CALayer() // container layer that has all the renderings of the observations poseOverlay.name = "PoseOverlay" print(bufferSize) poseOverlay.bounds = CGRect(x: 0.0, y: 0.0, width: bufferSize.width, height: bufferSize.height) // set the layer to cover the whole video buffer size // poseOverlay.position = CGPoint(x: previewLayer.bounds.midX, y: previewLayer.bounds.midY) view.layer.insertSublayer(poseOverlay, above: previewLayer) // insert this on top of the camera layer } /// register detect body pose request func setupVision() { // declare the request with a callback when its done let poseRequest = VNDetectHumanBodyPoseRequest { (request, error) in guard error == nil else { print(error!.localizedDescription) return } DispatchQueue.main.async { // update UI on main thread if let results = request.results { self.handleVisionResults(results) // parse out body parts } } } // poseRequest.regionOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1) // setting a normalized region of interest gives better results // BUT we would need to update this every frame, not just at setup, bc person can move in frame self.requests = [poseRequest] } /// processes the results from a body pose detection request func handleVisionResults(_ results: [Any]) { guard let observations = results as? [VNRecognizedPointsObservation] else {return} CATransaction.begin() // update UI atomically CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) poseOverlay.sublayers = nil // remove all the old recognized objects // 1 observation = 1 body. Process each body in the frame. for observation in observations { let boundingBox = self.humanBoundingBox(for: observation) let viewRect = VNImageRectForNormalizedRect(boundingBox, Int(bufferSize.width), Int(bufferSize.height)) let boxLayer = self.drawBoundingBox(viewRect.insetBy(dx: -50, dy: -50)) // give some padding around the bounding box (x and y are reversed here) let joints = getBodyJointsFor(observation: observation) let jointsLayer = self.drawJoints(joints) poseOverlay.addSublayer(boxLayer) poseOverlay.addSublayer(jointsLayer) } self.updateLayerGeometry() CATransaction.commit() } /// creates a normalized bounding box enclosing a person func humanBoundingBox(for observation: VNRecognizedPointsObservation) -> CGRect { var box = CGRect.zero var normalizedBoundingBox = CGRect.null // Process body points only if the confidence is high. guard observation.confidence > bodyPoseDetectionMinConfidence, var points = try? observation.recognizedPoints(forGroupKey: .all) else { return box } points = points.filter { (key, point) in point.confidence > bodyPoseRecognizedPointMinConfidence // only get high confidence points } // points is a dictionary of key-values // key = type of joint (elbow, nose, etc) // value = VNRecognizedPoint for (_, point) in points { normalizedBoundingBox = normalizedBoundingBox.union(CGRect(origin: point.location, size: .zero)) // create a box that barely encloses all the points } if !normalizedBoundingBox.isNull { box = normalizedBoundingBox } return box // returns a normalized bounding box of the body; if nothing was found then returns zero size } func updateLayerGeometry() { let bounds = previewLayer.bounds var scale: CGFloat let xScale: CGFloat = bounds.size.width / bufferSize.height let yScale: CGFloat = bounds.size.height / bufferSize.width scale = fmax(xScale, yScale) if scale.isInfinite { scale = 1.0 } // i'm not sure what this scaling does print(xScale,yScale) CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) // we need to do some manipulation to get the UI to show up correctly // rotate the layer 90 degrees into screen orientation and scale and mirror poseOverlay.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(.pi / 2.0)).scaledBy(x: scale, y: -scale)) // center the layer poseOverlay.position = CGPoint(x: bounds.midX, y: bounds.midY) CATransaction.commit() } /// creates a CALayer bounding box from a CGRect enclosing a person func drawBoundingBox(_ bounds: CGRect) -> CALayer { let boxLayer = CALayer() boxLayer.bounds = bounds boxLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) boxLayer.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 0.3566727312) boxLayer.cornerRadius = 10 return boxLayer } /// returns a CAShapeLayer with dots for every joint of interest on the recognized body func drawJoints(_ joints: [String: CGPoint]) -> CAShapeLayer { var imagePoints: [CGPoint] = [] for (joint, location) in joints { // only pick the joints of interest if jointsOfInterest.contains(VNHumanBodyPoseObservation.JointName(rawValue: VNRecognizedPointKey(rawValue: joint))) { let imagePoint = VNImagePointForNormalizedPoint(location, Int(bufferSize.width), Int(bufferSize.height)) // scale coordinate to image coordinate system imagePoints.append(imagePoint) } } let jointPath = UIBezierPath() let jointsLayer = CAShapeLayer() jointsLayer.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) for point in imagePoints { // draw a little circle at each point let nextJointPath = UIBezierPath(arcCenter: point, radius: 10, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) jointPath.append(nextJointPath) } jointsLayer.path = jointPath.cgPath return jointsLayer } // MARK: - Video buffer /// this method is called any time a video frame is received (delegate method inherited from parent) override func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) // processes the requests do { try imageRequestHandler.perform(self.requests) } catch { print(error.localizedDescription) } } }
true
244fd0e726be7469bd312c2d32d9fae9182de56f
Swift
StevenWorrall/Coffee_Foursquare
/Coffee_Finder/Coffee_Finder/Service.swift
UTF-8
926
2.96875
3
[]
no_license
// // Service.swift // Coffee_Finder // // Created by Steven Worrall on 6/9/20. // Copyright © 2020 Steven Worrall. All rights reserved. // import Foundation class Service { public func fetchGenericData<T: Decodable>(urlString: String, completion: @escaping ((Result<T, Error>) -> () )) { guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url) { (data, resp, err) in if let err = err { completion(.failure(err)) return } guard let data = data else { return } // print("JSON String: \(String(data: data, encoding: .utf8))") do { let dataResponse = try JSONDecoder().decode(T.self, from: data) completion(.success(dataResponse)) } catch let jsonError { completion(.failure(jsonError)) } }.resume() } }
true
ef57dad21e7ea007796f4c9b76f4dbcb4c518866
Swift
swmbuildserver/swm-ios-challenge
/m-login-app/App/View/ViewController/Lobby/AccountCreation/8-Address/AccountCreationAddressViewModel.swift
UTF-8
1,105
2.78125
3
[]
no_license
// // AccountCreationAddressViewModel.swift // m-login-app // // Created by Normann Joseph on 24.07.20. // Copyright © 2020 SWM Services GmbH. All rights reserved. // import Combine import Foundation class AccountCreationAddressViewModel { let streetTextFieldLabelText = String.localized(key: "StreetLabel") let numberTextFieldLabelText = String.localized(key: "NumberLabel") let additionalTextFieldLabelText = String.localized(key: "AdditionalAddressLabel") private struct Constants { static let minimumLength: Int = 1 } var street = "" { didSet { streetValidator.send(isValidInput(street)) } } var streetNumber = "" { didSet { streetNumberValidator.send(isValidInput(streetNumber)) } } var additionalAddress: String? = nil let streetValidator = CurrentValueSubject<Bool, Never>(false) let streetNumberValidator = CurrentValueSubject<Bool, Never>(false) //min 2 charachters private func isValidInput(_ input: String) -> Bool { return input.count >= Constants.minimumLength } }
true
1b04d7348edd9f96e76f2920da3a4c38e26fe88a
Swift
nguyencuong2510/TableViewDropCEll
/TableViewDropCEll/ViewController.swift
UTF-8
1,810
2.796875
3
[]
no_license
// // ViewController.swift // TableViewDropCEll // // Created by admin on 10/24/18. // Copyright © 2018 cuongnv. All rights reserved. // import UIKit extension NSObject { class var className: String { return String(describing: self) } } class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tbTableView: UITableView! var index = [IndexPath]() override func viewDidLoad() { super.viewDidLoad() tbTableView.delegate = self tbTableView.dataSource = self tbTableView.register(UINib(nibName: TableViewCell.className, bundle: nibBundle), forCellReuseIdentifier: TableViewCell.className) tbTableView.estimatedRowHeight = 100 tbTableView.rowHeight = UITableView.automaticDimension } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.className, for: indexPath) as! TableViewCell cell.isShow = index.contains(indexPath) ? true : false return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell1 = tableView.cellForRow(at: indexPath) as? TableViewCell else { return } tableView.beginUpdates() cell1.isShow = cell1.isShow ? false : true tableView.endUpdates() if index.contains(indexPath) { print(index.firstIndex(of: indexPath) ?? 0) index.remove(at: index.firstIndex(of: indexPath) ?? 0) } else { index.append(indexPath) } } }
true
03e34227288492bd2b40139670d639e34446c8a1
Swift
kyleroyse/kyleroyse.github.io
/Kyle Royse Temp Agreement_encrypted_ (1).playground/Contents.swift
UTF-8
10,268
4.53125
5
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) print (5 + 5) print("Hello World!") let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble: Double = 70 let numberExperiment: Float = 4 let label = "The width is " let width = 94 let widthLabel = label + String(width) let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples" let fruitSummary = "I have \(apples + oranges) pieces of fruit." // Multi-line strings let quotation = """ Even though there's whitespace to the left, the actual lines aren't indented. Except for this line. Double quotes (") can appear without being escaped. I still have /(apples + oranges) pieces of fruit. """ print(quotation) // Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets. A comma is allowed after the last element. var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" print(shoppingList) var occupations = [ "Malcom": "Captiain", "Kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" print(occupations) // To create an empty array or dictionary, use the initializer syntax let emptyArray = [String]() let emptyDictionary = [String: Float]() print (emptyArray) print (emptyDictionary) // If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:] -for example, when you set a new value for a variable or pass an argument to a function shoppingList = [] occupations = [:] // CONTROL FLOW - Use if and switch to make conditionals, and use for-in, while, and repeat-while to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required. let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore) // In an if statement, the conditional must be a Boolean expression - this means that code such as if score {...} is an error, not an implicit comparison to zero // You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional. var optionalString: String? = "Hello" print(optionalString == nil) var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } // If the ooptional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code. // Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead. let nickName: String? = nil let fullName: String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)" print(informalGreeting) // Switches support any kind of data and a wide variety of comparison operations - they aren't limited to integers and tests for equality. let vegetable = "red pepper" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber", "watercress": print("That would make a good tea sandwhich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup.") } // Notice how let can be used in a pattern to assign the value that matched the pattern to a constant // After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn't continue to the next case, so there is no need to explicitly break out of the switch at the end of each case's code. // You use for-in to iterate over times in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unoredered collection, so their keys and values are iterated over in an arbitrary order. let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25, 36], ] var largest = 0 for (_, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } print(largest) // Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run atleast once. var n = 2 while n < 100 { n *= 2 } print(n) var m = 2 repeat { m *= 2 } while m < 100 print(m) // You can keep an index in a loop by using ..< to make a range of indexes var total = 0 for i in 0..<4 { total += i } print(total) // Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values. // FUNCTIONS AND CLOSURES // Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to seperate the parameter names and types from the functions's return type. func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } greet(person: "Bob", day: "Tuesday") func date(month: String, day: Int) -> String { return "Today's date is \(month), the \(day)." } date(month: "September", day: 21) print(date(month: "September", day: 23)) // By default, functions use their parameteer names as labels for their arguments. Write a custom argument label before the parameter name, or write _ to use no argument label. func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." } greet("John", on: "Wednesday") // Use a tuple to make a compound value - for example, to return multiple values from a function. The elements of a tuple can ba referred to either by name or by number. func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5,3,100,3,9]) print(statistics.sum) print(statistics.2) // Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex. func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() // Functions are a first-class type. This means that a function can return another function as its value. func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) // A function can take another function as one of its arguments func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(list: numbers, condition: lessThanTen) // Functions are actually a secial case of closures: blocks of code that can be called later. The code in a closure has access to things like variables and functions that were available in the scope where the closure was created, even if the closure is in a different scope when it is executed-you saw an example of this already with nested functions. You can write a closure without a name y surrounding the code with vraces({}). Use in to seperate the arguements and return type from the body. numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) // test print("hello world") // You have several options for writing closures more concisely. When a closure's type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement closures implicitly return the value of their only statement. let mappedNumbers = numbers.map({ number in 3 * number }) print(mappedNumbers) // You can refer to parameters by number intead of name-this approach is especially useful in very short closures. A closure passed as the last arguement to a function can appear immediately after the parenteses. When a closure is the only argument to a function, you can omit the parentheses entirely. let sortedNumbers = numbers.sorted { $0 > $1} print(sortedNumbers) // OBJECTS and CLASSES //Use class followed by the class's name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it is in the context of a class. Likewise, method and functions declarations are written the same way. class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } // Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance. var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() // This version of the Shape class is missiong something important: an initializer to set up the class when an instance is created. Use init to create one. class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } // Notice how self is used to distinguish the name property from the name arguement to the initializer. The arguements to the initializer are passed like a function call when you create an
true
8ce627aa8392664bf5c69e2b33af6a9b2361993d
Swift
rosaliadupont/Radar-iOS-App
/RADAR/UserService.swift
UTF-8
3,656
2.578125
3
[]
no_license
// // UserService.swift // RADAR // // Created by Rosalia Dupont on 7/29/17. // Copyright © 2017 Make School. All rights reserved. // import Foundation import UIKit import FirebaseAuth.FIRUser import FirebaseDatabase import CoreLocation import MapKit import FBSDKCoreKit //this struct contains all of the user-related networking //code here struct UserService { static func show( forUID uid: String, completion: @escaping (User?) -> Void) { let ref = Database.database().reference().child("users").child(uid) ref.observeSingleEvent(of: .value, with: { (snapshot) in guard let user = User(snapshot: snapshot) else { return completion(nil) } completion(user) }) } /*static func create(_ firUser: FIRUser, username: String, completion: @escaping (User?) -> Void) { let userAttrs = ["username": username] let ref = Database.database().reference().child("users").child(firUser.uid) ref.setValue(userAttrs) { (error, ref) in if let error = error { assertionFailure(error.localizedDescription) return completion(nil) } ref.observeSingleEvent(of: .value, with: { (snapshot) in let user = User(snapshot: snapshot) completion(user) }) } }*/ static func create(_ firUser: FIRUser, username: String, completion: @escaping (User?) -> Void) { //create new user FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email"]).start( completionHandler: { (connection, result, error) -> Void in if (error == nil){ if let email = (result as! NSDictionary).object(forKey: "email") as? String{ Auth.auth().createUser(withEmail: email, password: FBSDKAccessToken.current().userID, completion: {(result) in //new user created in firebase. Email used is FB email, and password is App-Scoped FB ID let userAttrs = ["username": username, "uid": firUser.uid, "email": email] let ref = Database.database().reference().child("users").child(FBSDKAccessToken.current().userID) ref.setValue(userAttrs) { (error, ref) in if let error = error { assertionFailure(error.localizedDescription) return completion(nil) } ref.observeSingleEvent(of: .value, with: { (snapshot) in let user = User(snapshot: snapshot) completion(user) }) } }) } }}) } static func getFBUser(forFBID fbid: String, completion: @escaping (User?) -> Void){ Auth.auth().signInAnonymously(completion: {(result) in Database.database().reference().child("users").child(fbid).observeSingleEvent(of: .value, with: { (snapshot) in // not a new user let user = User(snapshot: snapshot) completion(user) }) { (error) in // new user NSLog(error.localizedDescription) completion(nil) } }) } }
true