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
51733e7500b540c905a21af48568db382a8b901f
Swift
xNUTs/iOS-1
/Core/ContentBlocker.swift
UTF-8
3,115
2.640625
3
[ "Apache-2.0" ]
permissive
// // ContentBlocker.swift // DuckDuckGo // // Copyright © 2017 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public class ContentBlocker { private struct FileConstants { static let name = "disconnectmetrackers" static let ext = "json" } private let configuration = ContentBlockerConfigurationUserDefaults() private let parser = DisconnectMeContentBlockerParser() private var categorizedEntries = CategorizedContentBlockerEntries() public init() { do { categorizedEntries = try loadContentBlockerEntries() } catch { Logger.log(text: "Could not load content blocker entries \(error)") } } public var blockingEnabled: Bool { return configuration.blockingEnabled } public var blockedEntries: [ContentBlockerEntry] { var entries = [ContentBlockerEntry]() for (categoryKey, categoryEntries) in categorizedEntries { let category = ContentBlockerCategory.forKey(categoryKey) if category == .advertising && configuration.blockAdvertisers { entries.append(contentsOf: categoryEntries) } if category == .analytics && configuration.blockAnalytics { entries.append(contentsOf: categoryEntries) } if category == .social && configuration.blockSocial { entries.append(contentsOf: categoryEntries) } } return entries } private func loadContentBlockerEntries() throws -> CategorizedContentBlockerEntries { let fileLoader = FileLoader() let data = try fileLoader.load(name: FileConstants.name, ext: FileConstants.ext) return try parser.convert(fromJsonData: data) } /** Checks if a url for a specific document should be blocked. - parameter url: the url to check - parameter documentUrl: the document requesting the url - returns: entry if the item matches a third party url in the block list otherwise nil */ public func block(url: URL, forDocument documentUrl: URL) -> ContentBlockerEntry? { for entry in blockedEntries { if url.absoluteString.contains(entry.url) && documentUrl.host != url.host { Logger.log(text: "Content blocker BLOCKED \(url.absoluteString)") return entry } } Logger.log(text: "Content blocker did NOT block \(url.absoluteString)") return nil } }
true
3c33a8013cea228aa34b9df12445f4bc7ebb49a3
Swift
swoosh1337/Fit
/Fit/View/Alert/AlertDisplayer.swift
UTF-8
3,582
2.53125
3
[]
no_license
import UIKit public class AlertDisplayer { public static let instance = AlertDisplayer() public var alertTextField: UITextField? public func showMessageAlert(vc: UIViewController, title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertAction.Style.default, handler: nil)) vc.present(alert, animated: true, completion: nil) } public func showCancelAlert(vc: UIViewController, title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in NotificationCenter.default.post(name: Notification.Name("canceledAction\(vc)"), object: nil) })) alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil)) vc.present(alert, animated: true, completion: nil) } public func showOneTextFieldAlert(vc: UIViewController, title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addTextField() alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in self.alertTextField = alert.textFields![0] NotificationCenter.default.post(name: Notification.Name("oneFieldAlertAction\(vc)"), object: nil) })) vc.present(alert, animated: true, completion: nil) } public func showNewPhotoActionSheet(vc: UIViewController, title: String, message: String) { let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in NotificationCenter.default.post(name: Notification.Name("cameraAction"), object: nil) })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in NotificationCenter.default.post(name: Notification.Name("photoLibraryAction"), object: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) vc.present(actionSheet, animated: true, completion: nil) } public func showEditPhoto(vc: UIViewController, title: String, message: String) { let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Update", style: .default, handler: { (action:UIAlertAction) in NotificationCenter.default.post(name: Notification.Name("updateAction"), object: nil) })) actionSheet.addAction(UIAlertAction(title: "Share", style: .default, handler: { (action:UIAlertAction) in NotificationCenter.default.post(name: Notification.Name("shareAction"), object: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) vc.present(actionSheet, animated: true, completion: nil) } }
true
1f31d958e7e9b0d41a435b58c85b15165814e880
Swift
filipetamota/GHKaban
/GHKabanApp/ExploreViewController.swift
UTF-8
4,448
2.625
3
[]
no_license
// // FirstViewController.swift // GHKabanApp // // Created by Filipe on 14/10/18. // Copyright © 2018 mota. All rights reserved. // // ViewController that will be the initial one and will show a list of repositories import UIKit class ExploreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var repos: [Repo] = [Repo]() var kanbanRepos: [Repo] = [Repo]() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self self.tableView.addSubview(self.refreshControl) getRepos() } override func viewDidAppear(_ animated: Bool) { navigationController?.visibleViewController?.title = "GH Kanban" self.tableView.reloadData() } //TODO: create loading indicators func getRepos() { //TODO: allow the user to insert the user name var request = URLRequest(url: URL(string: "https://api.github.com/users/inqbarna/repos")!) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in do { let json = try JSONSerialization.jsonObject(with: data!) let jsonArray = json as! [[String:Any]] self.repos.removeAll() for jsonElement: [String: Any] in jsonArray { self.repos.append(Repo(name: jsonElement["name"] as? String ?? "", owner: (jsonElement["owner"] as! [String: Any])["login"] as? String ?? "", repo_id: jsonElement["id"] as? Int ?? 0)) } self.updateLocalRepos() DispatchQueue.main.async { self.tableView.reloadData() self.refreshControl.endRefreshing() } } catch { //TODO: analyze the different types of error and show alert views print("error") } }) task.resume() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.repos.count } //TODO: hide tableView and show message when there is no data to put in the table func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: RepoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RepoCell") as! RepoTableViewCell cell.nameLabel?.text = self.repos[indexPath.row].name cell.ownerLabel?.text = self.repos[indexPath.row].owner cell.selectionStyle = UITableViewCell.SelectionStyle.none cell.addButton.tag = indexPath.row cell.addButton.addTarget(self, action: #selector(addKabanRepo), for: .touchUpInside) if (self.kanbanRepos.contains(repos[indexPath.row])) { cell.addButton.setImage(UIImage(named: "ic_remove"), for: .normal) } else { cell.addButton.setImage(UIImage(named: "ic_add"), for: .normal) } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } @objc func addKabanRepo(sender: UIButton!) { if (kanbanRepos.contains(repos[sender.tag])) { if let index = kanbanRepos.index(of:repos[sender.tag]) { kanbanRepos.remove(at: index) } } else { kanbanRepos.append(repos[sender.tag]) } updateLocalRepos() self.tableView.reloadData() } //TODO: save on NSUserDefaults the local repos so next time the same ones will be loaded func updateLocalRepos() { let barViewControllers = self.tabBarController?.viewControllers let lvc = barViewControllers![1] as! LocalViewController lvc.repos = self.kanbanRepos } lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action:#selector(handleRefresh),for: UIControl.Event.valueChanged) refreshControl.tintColor = UIColor.blue return refreshControl }() @objc func handleRefresh() { self.getRepos() } }
true
35b4d872cbbf2f9bb2976e8cca32d8a5a8fdd5e4
Swift
willhamilton24/SynapseWallet
/Synapse/Manual Log-In/Login Page Buttons/LoginButton.swift
UTF-8
4,019
2.8125
3
[]
no_license
// // LoginButton.swift // Synapse // // Created by Will Hamilton on 12/17/19. // Copyright © 2019 Comitatus Capital. All rights reserved. // import SwiftUI struct LoginButton: View { @EnvironmentObject var viewRouter: ViewRouter @State private var showAlert: Bool = false @State private var alertTitle: String = "" @State private var alertText: String = "" var body: some View { ZStack { Button(action: { self.viewRouter.handle = self.viewRouter.handle NetworkingClient().login(username: self.viewRouter.handle, password: self.viewRouter.password) { (json, error) in if json != nil { if json == "invalid username/password" { print("INVALID") self.alertTitle = "Invalid Handle or Password" self.alertText = "The Handle or Password was either incorrect or misspelled. Please Try Again." self.showAlert = true } else if json == "email not verified" { print("NOT VERIFIED") self.alertTitle = "Email not Verified" self.alertText = "You must verify your email before logging in." self.showAlert = true } else { self.viewRouter.token = json! self.viewRouter.currentPage = "loading" // Save Credentials NetworkingClient().getBalances(username: self.viewRouter.handle, token: self.viewRouter.token) { (json2, error) in if json2 != nil { if let btc = json2!["btc"] as? Double { self.viewRouter.balances.btc = btc } if let eth = json2!["eth"] as? Double { self.viewRouter.balances.eth = eth } if let ltc = json2!["ltc"] as? Double { self.viewRouter.balances.ltc = ltc } self.viewRouter.currentPage = "main" } else { self.viewRouter.currentPage = "main" } } } } else { self.alertTitle = "Server Error" self.alertText = "Noah screwed up, try again in a few minutes" self.showAlert = true if error != nil { print(error!) } } } }) { ZStack { Text("") .frame(minWidth: 0, maxWidth: 350, minHeight: 65) .background(CustomColors().dark) .opacity(0.2) .cornerRadius(15) Text("Sign In") .font(Font.custom("Roboto-Light", size:26)) .foregroundColor(.white) .padding(.horizontal, 10) .padding(.vertical, 8) } } .frame(minWidth: 350, maxWidth: 350, minHeight: 65) .alert(isPresented: $showAlert) { Alert(title: Text(self.alertTitle), message: Text(self.alertText), dismissButton: .default(Text("Got it!"))) } } } } struct LoginButton_Previews: PreviewProvider { static var previews: some View { LoginButton().environmentObject(ViewRouter()) } }
true
985dc60b7a17f89e829c1e3dcf8d27bb52e8a6ea
Swift
jonnymbaird/GoTCombine
/GoTCombine/Modules/Books/BooksTableViewCell.swift
UTF-8
2,621
2.84375
3
[]
no_license
// // BooksTableViewCell.swift // GoTCombine // // Created by Jonathan Baird on 26/03/2021. // import UIKit class BooksTableViewCell: UITableViewCell { private let titleLabel: UILabel = { let temp: UILabel = UILabel() temp.textColor = UIColor(redInt: 255, greenInt: 255, blueInt: 255, alpha: 1) temp.font = UIFont.systemFont(ofSize: 18, weight: .regular) return temp }() private let dateLabel: UILabel = { let temp: UILabel = UILabel() temp.textColor = UIColor(redInt: 195, greenInt: 202, blueInt: 206, alpha: 0.84) temp.font = UIFont.systemFont(ofSize: 14, weight: .regular) return temp }() private let pagesLabel: UILabel = { let temp: UILabel = UILabel() temp.textColor = UIColor(redInt: 189, greenInt: 189, blueInt: 189, alpha: 0.8) temp.font = UIFont.italicSystemFont(ofSize: 12) temp.textAlignment = .right return temp }() private let divider: UIView = { let temp: UIView = UIView() temp.backgroundColor = UIColor(redInt: 228, greenInt: 228, blueInt: 228, alpha: 0.13) temp.height(1) return temp }() // MARK: - Initialisation init() { super.init(style: .default, reuseIdentifier: BooksTableViewCell.reuseIdentifier) privateInit() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) privateInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func privateInit() { backgroundColor = .clear selectionStyle = .none setConstraints() } private func setConstraints() { addSubviews([titleLabel, dateLabel, pagesLabel, divider]) titleLabel.leftToSuperview(offset: 16, usingSafeArea: true) titleLabel.topToSuperview(offset: 12) dateLabel.topToBottom(of: titleLabel, offset: 4) dateLabel.left(to: titleLabel) pagesLabel.centerY(to: titleLabel) pagesLabel.rightToSuperview(offset: -16) pagesLabel.width(110) titleLabel.rightToLeft(of: pagesLabel, priority: .defaultLow) divider.edgesToSuperview(excluding: .top) divider.topToBottom(of: dateLabel, offset: 20) } func build(with book: BookDisplayModel) { titleLabel.text = book.name dateLabel.text = book.date pagesLabel.text = book.numberofPages } }
true
b8b8ae93e230734f19421678192d9b1d8d5111b9
Swift
dun198/SwiftAudioPlayer
/SwiftAudioPlayer/Track/Track.swift
UTF-8
878
2.953125
3
[ "MIT" ]
permissive
// // Model.swift // NSTableViewGroupRows // // Created by Tobias Dunkel on 17.11.17. // Copyright © 2017 Tobias Dunkel. All rights reserved. // import Foundation /** this is the model which represents a track in the playlist */ struct Track: Equatable { static func == (lhs: Track, rhs: Track) -> Bool { return lhs.file == rhs.file } let file: URL let filename: String let duration: TimeInterval // optional data let title: String? let artist: String? let genre: String? let album: String? init(_ file: URL) { self.file = file self.filename = file.deletingPathExtension().lastPathComponent let metadata = TrackMetadataHandler.getBasicMetadata(for: file) self.title = metadata.title self.artist = metadata.artist self.duration = metadata.duration self.genre = metadata.genre self.album = metadata.album } }
true
ca8a37ee6943f7b7c8f59d569e7287bd173ae73d
Swift
ArunaElangovan/21North_iOS
/21North/HistoryCustomCell.swift
UTF-8
2,378
2.671875
3
[ "Apache-2.0" ]
permissive
// // HistoryCustomCell.swift // 21North // // Created by Aruna Elangovan on 29/01/18. // Copyright © 2018 Sachin Tomar. All rights reserved. // import UIKit class HistoryCustomCell: UITableViewCell { let typeLabel = UILabel() let dateLabel = UILabelWithPadding() let style = Style() var date: String! = ""{ didSet{ dateLabel.text = date } } var serviceType: String! = ""{ didSet{ typeLabel.text = serviceType } } // MARK: - Inits override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Initialization code setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - Custom UI setup private func setupUI() { selectionStyle = .none backgroundColor = UIColor.clear dateLabel.font = style.thirdLineInAFont dateLabel.textColor = UIColor.darkGray dateLabel.textAlignment = .center typeLabel.font = style.thirdLineAFont typeLabel.textColor = UIColor.gray contentView.addSubview(typeLabel) typeLabel.translatesAutoresizingMaskIntoConstraints = false typeLabel.numberOfLines = 0 typeLabel.lineBreakMode = .byWordWrapping typeLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(10, 20, 0, 20), excludingEdge: .bottom) typeLabel.autoSetDimension(.height, toSize: 10, relation: .greaterThanOrEqual) contentView.addSubview(dateLabel) dateLabel.translatesAutoresizingMaskIntoConstraints = false dateLabel.numberOfLines = 0 dateLabel.layer.borderWidth = 1 dateLabel.layer.borderColor = style.borderColor dateLabel.lineBreakMode = .byWordWrapping dateLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(0, 20, 10, 20), excludingEdge: .top) dateLabel.autoSetDimension(.height, toSize: 20, relation: .greaterThanOrEqual) dateLabel.autoPinEdge(.top, to: .bottom, of: typeLabel, withOffset: 10) } }
true
be5b340fad7ca4045d0b954bfc682476bac80b48
Swift
neil-wu/SwiftDump
/SwiftDump/SwiftDump/MachO/Load Commands/Section64.swift
UTF-8
896
2.59375
3
[ "MIT", "Apache-2.0" ]
permissive
// // Section64.swift // SwiftDump // // Created by neilwu on 2020/6/26. // Copyright © 2020 nw. All rights reserved. // import Foundation import MachO public struct Section64 { private(set) var sectname: String private(set) var segname: String private(set) var info:section_64 var align: UInt32 { return UInt32(pow(Double(2), Double(info.align))) } var fileOffset: UInt32 { return info.offset; } var num:Int { let num: Int = Int(info.size) / Int(align); return num; } init(section: section_64) { segname = String(section.segname); var strSect = String(section.sectname); // max len is 16 if (strSect.count > 16) { strSect = String(strSect.prefix(16)); } sectname = strSect; self.info = section; } }
true
f85abe3f3f29eff29d582b83837e0e82bad22716
Swift
hutuyingxiong/DTCamera
/DTCamera/iOS/PhotoBrowser/PreviewPhotoViewController.swift
UTF-8
3,274
2.75
3
[ "MIT" ]
permissive
// // PreviewPhotoViewController.swift // DTCamera // // Created by Dan Jiang on 2019/8/20. // Copyright © 2019 Dan Thought Studio. All rights reserved. // import UIKit class PreviewPhotoViewController: UIViewController { var page = 0 private let scrollView = UIScrollView() private let imageView = UIImageView() private let photo: UIImage private var fitScale: CGFloat = 1 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(photo: UIImage) { self.photo = photo super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black setupScrollView() imageView.image = photo imageView.frame = CGRect(x: 0, y: 0, width: photo.size.width, height: photo.size.height) scrollView.contentSize = photo.size caculateZoomScale() centerContents() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) scrollView.zoomScale = fitScale } private func setupScrollView() { scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.delegate = self if #available(iOS 11, *) { scrollView.contentInsetAdjustmentBehavior = .never } scrollView.addSubview(imageView) view.addSubview(scrollView) scrollView.snp.makeConstraints { make in make.edges.equalToSuperview() } } private func centerContents() { let maxFrame = view.bounds var contentsFrame = imageView.frame if contentsFrame.size.width < maxFrame.size.width { contentsFrame.origin.x = maxFrame.minX + (maxFrame.size.width - contentsFrame.size.width) / 2 } else { contentsFrame.origin.x = maxFrame.minX } if contentsFrame.size.height < maxFrame.size.height { contentsFrame.origin.y = maxFrame.minY + (maxFrame.size.height - contentsFrame.size.height) / 2 } else { contentsFrame.origin.y = maxFrame.minY } imageView.frame = contentsFrame } private func caculateZoomScale() { let scaleWidth = view.bounds.size.width / photo.size.width let scaleHeight = view.bounds.size.height / photo.size.height fitScale = min(scaleWidth, scaleHeight) if fitScale < 1 { scrollView.minimumZoomScale = fitScale scrollView.maximumZoomScale = 1 } else { scrollView.minimumZoomScale = fitScale scrollView.maximumZoomScale = fitScale * 1.5 } if scrollView.zoomScale != fitScale { scrollView.zoomScale = fitScale } } } extension PreviewPhotoViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { centerContents() } }
true
580ceae8aff8669505eeb92c244487d98f510451
Swift
kylepapili/ScholarliRepository
/iOSAppFiles/Scholarly/AdminClassEditorViewController.swift
UTF-8
6,421
2.578125
3
[]
no_license
// // AdminClassEditorViewController.swift // Scholarli // // Created by Kyle Papili on 9/14/17. // Copyright © 2017 Scholarly. All rights reserved. // import UIKit import Firebase class AdminClassEditorViewController: UIViewController , UITableViewDataSource , UITableViewDelegate , UISearchBarDelegate { //Properties var classes = [[String : Any]]() var filteredData = [[String : Any]]() var isSearching = false var SelectedCellID : String = "" //Outlets @IBOutlet var TableView: UITableView! @IBOutlet var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() startObserver() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //Create Cell let cell = tableView.dequeueReusableCell(withIdentifier: "classCell", for: indexPath) as! ClassSelectorTableViewCell if isSearching { //If searching, populate cells from filteredData if let course = ((filteredData[indexPath.row]) as Dictionary?) { cell.AdminClassLabel.text = course["course"] as? String } if let period = ((filteredData[indexPath.row]) as Dictionary?) { cell.AdminPeriodLabel.text = "Period \(period["period"] as? String ?? "N/A")" } if let teacher = ((filteredData[indexPath.row]) as Dictionary?) { let teacherTitle = teacher["teacherTitle"] as? String let teacherLastName = teacher["teacherLastName"] as? String cell.AdminTeacherLabel.text = "\(teacherTitle ?? "") \(teacherLastName ?? "teacher")" } if let courseID = ((filteredData[indexPath.row]) as Dictionary?) { cell.AdminClassIDLabel.text = courseID["classID"] as? String } } else { //If NOT searching, populate cells from classes if let course = ((classes[indexPath.row]) as Dictionary?) { cell.AdminClassLabel.text = course["course"] as? String } if let period = ((classes[indexPath.row]) as Dictionary?) { cell.AdminPeriodLabel.text = "Period \(period["period"] as? String ?? "N/A")" } if let teacher = ((classes[indexPath.row]) as Dictionary?) { let teacherTitle = teacher["teacherTitle"] as? String let teacherLastName = teacher["teacherLastName"] as? String cell.AdminTeacherLabel.text = "\(teacherTitle ?? "") \(teacherLastName ?? "teacher")" } if let courseID = ((classes[indexPath.row]) as Dictionary?) { cell.AdminClassIDLabel.text = courseID["classID"] as? String } } //Return Cell return (cell) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isSearching { return self.filteredData.count } else { return self.classes.count } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //Do something if isSearching { guard let idToPass = self.filteredData[indexPath.row]["classID"] as? String else { return } self.SelectedCellID = idToPass } else { guard let idToPass = self.classes[indexPath.row]["classID"] as? String else { return } self.SelectedCellID = idToPass } self.performSegue(withIdentifier: "AdminClassEditSegueToAddClassVC", sender: self) } func startObserver() { let classesRef = Database.database().reference().child("SchoolData").child(UserDefaults.standard.value(forKey: String(describing: UserDefaultKeys.School)) as! String).child("classes") classesRef.observe(.value, with: { (FIRDataSnapshot) in guard let dataDict = FIRDataSnapshot.value as? [String : [String : Any]] else { print("Error in startObserver") return } guard let dataArray = Array(dataDict.values) as? [[String : Any]] else { print("Error in startObserver 2") return } self.classes = dataArray self.classes = sortByCourse(classesArray: dataArray) self.TableView.reloadData() }) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AdminClassEditSegueToAddClassVC" { let destinationVC = segue.destination as? AddClassViewController destinationVC?.classToDisplay = self.SelectedCellID destinationVC?.sender = "ADMIN" } } ////////// //searchBar(textDidChange) ////////// func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { //If nothing is typed in searchBar, just show the normal tableView isSearching = false view.endEditing(true) TableView.reloadData() } else { //When something is typed in search bar, populate filteredData array with the appropriate results if let searchText = searchBar.text { isSearching = true filteredData = classes.filter({ (dict) -> Bool in if let course = dict["course"] as? String { return course.lowercased().contains(searchText.lowercased()) } if let teacher = dict["teacherLastName"] as? String { return teacher.lowercased().contains(searchText.lowercased()) } if let period = dict["period"] as? String { return period.lowercased().contains(searchText.lowercased()) } return false }) //nfilteredData = classes.filter({($0 as AnyObject) as! String == searchBar.text}) as NSArray filteredData = sortByCourse(classesArray: filteredData) TableView.reloadData() } } } }
true
192b17f976260f11009c964f9fc8a2300f81227a
Swift
quintonwall/ARKit-Trailblazers
/Trailblazers/Backpack/WelcomeTourPageViewController.swift
UTF-8
4,245
2.671875
3
[]
no_license
// // WelcomeTourPageViewController.swift // Backpack // // Created by QUINTON WALL on 9/9/16. // Copyright © 2016 QUINTON WALL. All rights reserved. // import UIKit class WelcomeTourPageViewController: UIPageViewController, UIPageViewControllerDataSource { var arrPageTitle: NSArray = NSArray() var arrPagePhoto: NSArray = NSArray() override func viewWillAppear(animated: Bool) { } override func viewDidLoad() { super.viewDidLoad() arrPageTitle = ["Backpack helps you stay up to date on the latest trails, modules, and more.", "Save trails and modules to your todo list, and pick up on the web when you are ready.", "Never miss out on new trails or special badges ever again with push notifications.", "Show your Trailhead pride through emojis with the Trailhead custom keyboard.", "To get started, simply log into your Salesforce account and the trails with Backpack"]; arrPagePhoto = ["astro_floating_head", "astro_clipboard_2", "astro_trailblazer", "astro_new_sash", "astro_holding_badges"]; self.dataSource = self self.setViewControllers([getViewControllerAtIndex(0)] as [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil) } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index: Int if(viewController.isKindOfClass(WelcomeContentPageOne)) { let pageContent: WelcomeContentPageOne = viewController as! WelcomeContentPageOne index = pageContent.pageIndex } else { let pageContent: WelcomeContentViewController = viewController as! WelcomeContentViewController index = pageContent.pageIndex } if ((index == 0) || (index == NSNotFound)) { return nil } index -= 1 return getViewControllerAtIndex(index) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index: Int if(viewController.isKindOfClass(WelcomeContentPageOne)) { let pageContent: WelcomeContentPageOne = viewController as! WelcomeContentPageOne index = pageContent.pageIndex } else { let pageContent: WelcomeContentViewController = viewController as! WelcomeContentViewController index = pageContent.pageIndex } if (index == NSNotFound) { return nil; } index += 1; if (index == arrPageTitle.count) { return nil; } return getViewControllerAtIndex(index) } func getViewControllerAtIndex(index: NSInteger) -> UIViewController { //first page is different if(index == 0) { let p1Controller = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeContentPageOne") as! WelcomeContentPageOne p1Controller.pageIndex = index p1Controller.strTitle = "\(arrPageTitle[index])" p1Controller.strPhotoName = "\(arrPagePhoto[index])" return p1Controller } else { // Create a new view controller and pass suitable data. let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeContent") as! WelcomeContentViewController pageContentViewController.strTitle = "\(arrPageTitle[index])" pageContentViewController.strPhotoName = "\(arrPagePhoto[index])" pageContentViewController.pageIndex = index //if we are at the last page of the tour show the get started button. if(index == arrPageTitle.count-1) { pageContentViewController.hideGetStartedButton = false } else { pageContentViewController.hideGetStartedButton = true } return pageContentViewController } } }
true
93374a62ad58a262996b92ef8419dc84482db366
Swift
SOPT-28th-loveSU/SwiftUI-KakaoClone-YoonAh
/SwiftUI-KakaoClone/SwiftUI-KakaoClone/Sources/Views/Screens/ChatView.swift
UTF-8
461
2.84375
3
[]
no_license
// // ChatView.swift // SwiftUI-KakaoClone // // Created by SHIN YOON AH on 2021/06/15. // import SwiftUI struct ChatView: View { let name: String let image: String let chat: String var body: some View { List { Text(chat) } } } struct ChatView_Previews: PreviewProvider { static var previews: some View { ChatView(name: "최솝트", image: "friendtabProfileImg", chat:"안녕") } }
true
b5d43b407a1026cb28d77e2c344806b7483d3961
Swift
EuroFifa2016/sourcecode
/NewsDetailViewController.swift
UTF-8
2,510
2.515625
3
[]
no_license
// // NewsDetailViewController.swift // Euro2016App // // Created by Khushboo Kochhar on 10/02/16. // Copyright © 2016 TrigmaSolutionsPvtLtd. All rights reserved. // import UIKit class NewsDetailViewController: UIViewController { //MARK: Properties @IBOutlet weak var tableView: UITableView! //MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() let headerView: ParallaxHeaderView = ParallaxHeaderView.parallaxHeaderViewWithImage(UIImage(named: "news-img3"), forSize: CGSizeMake(self.view.frame.size.width, 160)) as! ParallaxHeaderView self.tableView.tableHeaderView = headerView // Do any additional setup after loading the view. } func scrollViewDidScroll(scrollView: UIScrollView) { let header: ParallaxHeaderView = self.tableView.tableHeaderView as! ParallaxHeaderView header.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset) self.tableView.tableHeaderView = header } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier. let cellIdentifier = "NewsDetailCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NewsDetailCell return cell } // MARK: Navigation // This method lets you configure a view controller before it's presented. override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // let name = nameTextFeld.text ?? "" // let photo = photoImageView.image // let rating = ratingControl.rating // // Set the meal to be passed to MealTableViewController after the unwind segue. // meal = Meal(name: name, photo: photo, rating: rating) } // In a storyboard-based application, you will often want to do a little preparation before navigation }
true
d1852d34de1a97b98de466527c6f4f2e59315278
Swift
EurekaCommunity/ColorPickerRow
/Example/ViewController.swift
UTF-8
22,382
2.96875
3
[ "MIT" ]
permissive
// // ViewController.swift // EurekaColorPicker // // Created by Mark Alldritt on 2016-12-05. // Copyright © 2017 Late Night Software Ltd. All rights reserved. // import UIKit import Eureka class ViewController: FormViewController { override func viewDidLoad() { // Present the form in a insetGrouped styled table if #available(iOS 13.0, *) { tableView = UITableView(frame: view.bounds, style: .insetGrouped) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.cellLayoutMarginsFollowReadableWidth = false } super.viewDidLoad() form // Build-in color palette example +++ Section("Color Picker Demo I") <<< ColorPickerRow("colors1") { (row) in row.title = "Color Picker" row.isCircular = false row.showsCurrentSwatch = true row.value = UIColor.green } .onChange { (picker) in print("color1: \(picker.value!)") if let swatchRow = self.form.rowBy(tag: "swatch1") as? ColorRow { swatchRow.value = picker.value swatchRow.updateCell() } if let nameRow = self.form.rowBy(tag: "name1") as? LabelRow { nameRow.value = picker.cell.colorSpec(forColor: picker.value)?.color.name if let colorSpec = picker.cell.colorSpec(forColor: picker.value)?.color { nameRow.value = "\(colorSpec.name) (\(colorSpec.hex))" } else { nameRow.value = nil } nameRow.updateCell() } } <<< ColorRow("swatch1") { (row) in row.title = "Chosen Color" } .cellSetup { (cell, row) in if let colorsRow = self.form.rowBy(tag: "colors1") as? ColorPickerRow { row.value = colorsRow.value } } <<< LabelRow("name1") { (row) in row.title = "Chosen Color Name" } .cellSetup { (cell, row) in if let colorsRow = self.form.rowBy(tag: "colors1") as? ColorPickerRow { if let colorSpec = colorsRow.cell.colorSpec(forColor: colorsRow.value)?.color { row.value = "\(colorSpec.name) (\(colorSpec.hex))" } else { row.value = nil } } } <<< SwitchRow { (row) in row.title = "Circular Swatches" row.value = false } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors1") as? ColorPickerRow { colorsRow.isCircular = row.value! } } <<< SwitchRow { (row) in row.title = "Show Current Color Swatch" row.value = true } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors1") as? ColorPickerRow { colorsRow.showsCurrentSwatch = row.value! } } <<< SwitchRow { (row) in row.title = "Show Palette Names" row.value = true } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors1") as? ColorPickerRow { colorsRow.showsPaletteNames = row.value! } } +++ Section("Color Picker Demo II") <<< InlineColorPickerRow("colors3") { (row) in row.title = "Inline Color Picker" row.value = UIColor.white } // Custom color palette example +++ Section("Color Picker Demo III") <<< ColorPickerRow("colors2") { (row) in row.title = "Color Picker" row.isCircular = true row.showsCurrentSwatch = false row.showsPaletteNames = false row.value = UIColor.white } .cellSetup { (cell, row) in cell.titleLabel.textColor = .blue let palette = ColorPalette(name: "All", palette: [ColorSpec(hex: "#ffffff", name: ""), ColorSpec(hex: "#e2e2e2", name: ""), ColorSpec(hex: "#c6c6c6", name: ""), ColorSpec(hex: "#aaaaaa", name: ""), ColorSpec(hex: "#8e8e8e", name: ""), ColorSpec(hex: "#707070", name: ""), ColorSpec(hex: "#545454", name: ""), ColorSpec(hex: "#383838", name: ""), ColorSpec(hex: "#1c1c1c", name: ""), ColorSpec(hex: "#000000", name: ""), ColorSpec(hex: "#d8fff8", name: ""), ColorSpec(hex: "#91ffec", name: ""), ColorSpec(hex: "#49ffe0", name: ""), ColorSpec(hex: "#00ffd4", name: ""), ColorSpec(hex: "#00d8b4", name: ""), ColorSpec(hex: "#00b799", name: ""), ColorSpec(hex: "#00967d", name: ""), ColorSpec(hex: "#007561", name: ""), ColorSpec(hex: "#005446", name: ""), ColorSpec(hex: "#00332a", name: ""), ColorSpec(hex: "#d8ffeb", name: ""), ColorSpec(hex: "#a3ffd1", name: ""), ColorSpec(hex: "#6dffb6", name: ""), ColorSpec(hex: "#38ff9b", name: ""), ColorSpec(hex: "#00ff7f", name: ""), ColorSpec(hex: "#00d369", name: ""), ColorSpec(hex: "#00a854", name: ""), ColorSpec(hex: "#007c3e", name: ""), ColorSpec(hex: "#005446", name: ""), ColorSpec(hex: "#002613", name: ""), ColorSpec(hex: "#d8ffd8", name: ""), ColorSpec(hex: "#a3ffa3", name: ""), ColorSpec(hex: "#6dff6d", name: ""), ColorSpec(hex: "#38ff38", name: ""), ColorSpec(hex: "#00ff00", name: ""), ColorSpec(hex: "#00d600", name: ""), ColorSpec(hex: "#00ad00", name: ""), ColorSpec(hex: "#008400", name: ""), ColorSpec(hex: "#005b00", name: ""), ColorSpec(hex: "#003300", name: ""), ColorSpec(hex: "#ebffd8", name: ""), ColorSpec(hex: "#d1ffa3", name: ""), ColorSpec(hex: "#b6ff6d", name: ""), ColorSpec(hex: "#9bff38", name: ""), ColorSpec(hex: "#7fff00", name: ""), ColorSpec(hex: "#6cd800", name: ""), ColorSpec(hex: "#59b200", name: ""), ColorSpec(hex: "#468c00", name: ""), ColorSpec(hex: "#336600", name: ""), ColorSpec(hex: "#1f3f00", name: ""), ColorSpec(hex: "#ffffd8", name: ""), ColorSpec(hex: "#ffff91", name: ""), ColorSpec(hex: "#ffff49", name: ""), ColorSpec(hex: "#ffff00", name: ""), ColorSpec(hex: "#d8d800", name: ""), ColorSpec(hex: "#b7b700", name: ""), ColorSpec(hex: "#969600", name: ""), ColorSpec(hex: "#757500", name: ""), ColorSpec(hex: "#545400", name: ""), ColorSpec(hex: "#333300", name: ""), ColorSpec(hex: "#fff5d8", name: ""), ColorSpec(hex: "#ffeaad", name: ""), ColorSpec(hex: "#ffdf82", name: ""), ColorSpec(hex: "#ffd456", name: ""), ColorSpec(hex: "#ffca2b", name: ""), ColorSpec(hex: "#ffbf00", name: ""), ColorSpec(hex: "#cc9900", name: ""), ColorSpec(hex: "#997200", name: ""), ColorSpec(hex: "#664c00", name: ""), ColorSpec(hex: "#332600", name: ""), ColorSpec(hex: "#ffebd8", name: ""), ColorSpec(hex: "#ffd6ad", name: ""), ColorSpec(hex: "#ffc082", name: ""), ColorSpec(hex: "#ffaa56", name: ""), ColorSpec(hex: "#ff952b", name: ""), ColorSpec(hex: "#ff7f00", name: ""), ColorSpec(hex: "#d16800", name: ""), ColorSpec(hex: "#a05000", name: ""), ColorSpec(hex: "#703800", name: ""), ColorSpec(hex: "#3f1f00", name: ""), ColorSpec(hex: "#ffe2d8", name: ""), ColorSpec(hex: "#ffc1ad", name: ""), ColorSpec(hex: "#ffa182", name: ""), ColorSpec(hex: "#ff8056", name: ""), ColorSpec(hex: "#ff602b", name: ""), ColorSpec(hex: "#ff3f00", name: ""), ColorSpec(hex: "#d63500", name: ""), ColorSpec(hex: "#a82a00", name: ""), ColorSpec(hex: "#7a1e00", name: ""), ColorSpec(hex: "#4c1300", name: ""), ColorSpec(hex: "#ffd8d8", name: ""), ColorSpec(hex: "#ffadad", name: ""), ColorSpec(hex: "#ff8282", name: ""), ColorSpec(hex: "#ff5656", name: ""), ColorSpec(hex: "#ff2b2b", name: ""), ColorSpec(hex: "#ff0000", name: ""), ColorSpec(hex: "#d10000", name: ""), ColorSpec(hex: "#a00000", name: ""), ColorSpec(hex: "#700000", name: ""), ColorSpec(hex: "#3f0000", name: ""), ColorSpec(hex: "#ffd8eb", name: ""), ColorSpec(hex: "#ffadd6", name: ""), ColorSpec(hex: "#ff82c0", name: ""), ColorSpec(hex: "#ff56aa", name: ""), ColorSpec(hex: "#ff2b95", name: ""), ColorSpec(hex: "#ff007f", name: ""), ColorSpec(hex: "#cc0066", name: ""), ColorSpec(hex: "#99004c", name: ""), ColorSpec(hex: "#660033", name: ""), ColorSpec(hex: "#330019", name: ""), ColorSpec(hex: "#ffd8ff", name: ""), ColorSpec(hex: "#ffa3ff", name: ""), ColorSpec(hex: "#ff6dff", name: ""), ColorSpec(hex: "#ff38ff", name: ""), ColorSpec(hex: "#ff00ff", name: ""), ColorSpec(hex: "#d600d6", name: ""), ColorSpec(hex: "#ad00ad", name: ""), ColorSpec(hex: "#840084", name: ""), ColorSpec(hex: "#5b005b", name: ""), ColorSpec(hex: "#330033", name: ""), ColorSpec(hex: "#ebd8ff", name: ""), ColorSpec(hex: "#d6adff", name: ""), ColorSpec(hex: "#c082ff", name: ""), ColorSpec(hex: "#aa56ff", name: ""), ColorSpec(hex: "#952bff", name: ""), ColorSpec(hex: "#7f00ff", name: ""), ColorSpec(hex: "#6600cc", name: ""), ColorSpec(hex: "#4c0099", name: ""), ColorSpec(hex: "#330066", name: ""), ColorSpec(hex: "#190033", name: ""), ColorSpec(hex: "#d8d8ff", name: ""), ColorSpec(hex: "#adadff", name: ""), ColorSpec(hex: "#8282ff", name: ""), ColorSpec(hex: "#5656ff", name: ""), ColorSpec(hex: "#2b2bff", name: ""), ColorSpec(hex: "#0000ff", name: ""), ColorSpec(hex: "#0000d1", name: ""), ColorSpec(hex: "#0000a0", name: ""), ColorSpec(hex: "#000070", name: ""), ColorSpec(hex: "#00003f", name: ""), ColorSpec(hex: "#d8e5ff", name: ""), ColorSpec(hex: "#adc8ff", name: ""), ColorSpec(hex: "#82abff", name: ""), ColorSpec(hex: "#568eff", name: ""), ColorSpec(hex: "#2b71ff", name: ""), ColorSpec(hex: "#0055ff", name: ""), ColorSpec(hex: "#0044cc", name: ""), ColorSpec(hex: "#003399", name: ""), ColorSpec(hex: "#002266", name: ""), ColorSpec(hex: "#001133", name: ""), ColorSpec(hex: "#d8f2ff", name: ""), ColorSpec(hex: "#a3e0ff", name: ""), ColorSpec(hex: "#6dceff", name: ""), ColorSpec(hex: "#38bcff", name: ""), ColorSpec(hex: "#00a9ff", name: ""), ColorSpec(hex: "#008ed6", name: ""), ColorSpec(hex: "#0073ad", name: ""), ColorSpec(hex: "#005884", name: ""), ColorSpec(hex: "#003d5b", name: ""), ColorSpec(hex: "#002133", name: "")]) cell.palettes = [palette] } .onChange { (picker) in print("color2: \(picker.value!)") if let swatchRow = self.form.rowBy(tag: "swatch2") as? ColorRow { swatchRow.value = picker.value swatchRow.updateCell() } if let nameRow = self.form.rowBy(tag: "name2") as? LabelRow { nameRow.value = picker.cell.colorSpec(forColor: picker.value)?.color.hex nameRow.updateCell() } } <<< ColorRow("swatch2") { (row) in row.title = "Chosen Color" } .cellSetup { (cell, row) in if let colorsRow = self.form.rowBy(tag: "colors2") as? ColorPickerRow { row.value = colorsRow.value } } <<< LabelRow("name2") { (row) in row.title = "Chosen Color Name" } .cellSetup { (cell, row) in if let colorsRow = self.form.rowBy(tag: "colors2") as? ColorPickerRow { row.value = colorsRow.cell.colorSpec(forColor: colorsRow.value)?.color.hex } } <<< SwitchRow { (row) in row.title = "Circular Swatches" row.value = true } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors2") as? ColorPickerRow { colorsRow.isCircular = row.value! } } <<< SwitchRow { (row) in row.title = "Show Current Color Swatch" row.value = false } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors2") as? ColorPickerRow { colorsRow.showsCurrentSwatch = row.value! } } <<< SwitchRow { (row) in row.title = "Show Palette Names" row.value = false } .onChange { (row) in if let colorsRow = self.form.rowBy(tag: "colors2") as? ColorPickerRow { colorsRow.showsPaletteNames = row.value! } } } }
true
aaa89a868ba3b0c209fef9f767847042000afe6f
Swift
MannarElkady/Currency-Simple-IOS-Application-Using-Alamofire-with-Codable
/Concurrency/EuroAllData/ViewController.swift
UTF-8
1,129
2.59375
3
[]
no_license
// // ViewController.swift // Concurrency // // Created by MagoSpark on 4/24/20. // Copyright © 2020 ManarOrg. All rights reserved. // import UIKit import RxCocoa import RxSwift class ViewController: UIViewController , EuroControllerProtocol{ private var observableForConcurrencyArray : Observable<Array<CurrencyDisplayed>>? private var presenter: EuroPresenterProtocol? private let disposeBag = DisposeBag() func displayEuroCurrency(CurrencyList list: Array<CurrencyDisplayed>) { observableForConcurrencyArray = Observable.from(list) observableForConcurrencyArray?.bind(to: collectionView.rx.items(cellIdentifier: "cell", cellType: CollectionViewCell.self)){ index,currency,cell in cell.currencyDetails = currency } } @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. presenter = EuroPresenter() (presenter as! EuroPresenter).controller = self presenter?.getAllCurrency() } }
true
e6f968a825867ba7ec3a479422cf483ec77aceb6
Swift
seanlim/epoch
/portfolio-spectrogram/Firebase/DatabaseManager.swift
UTF-8
5,179
2.546875
3
[]
no_license
// // DB.swift // portfolio-spectrogram // // Created by Sean Lim on 20/1/18. // Copyright © 2018 cool. All rights reserved. // import Foundation import FirebaseCore import FirebaseDatabase import FirebaseAuth import FirebaseMessaging import SwiftClient final class DatabaseManager { static let shared = DatabaseManager() let databaseUserRef = Database.database().reference().child("user_profile") func databaseFeedRef() -> DatabaseReference { return Database.database().reference().child(channel!).child(Date().formatDay()) } // Makes new post in DB func makeNewPost(url: String?, callback: @escaping (_ succ: Bool) -> Void) { databaseFeedRef().child("\(user!.uid)").childByAutoId().setValue([ "user_name": user_name!, "audio_url": url!, "time": Date().stringFromDate() ], andPriority: nil) { (e, dref) in print(e) // Sends push notification self.broadcastActivity() callback(e == nil) } } // Retrieves all posts func getPosts(completion: @escaping (_ succ: Bool,_ grams: Grams?) -> Void) { let seenLinks: [String] = (UserDefaults.standard.array(forKey: "seen") ?? []) as! [String] var fetchQueue = subscribed fetchQueue?.append(user!.uid) getFeed(forUsers: fetchQueue!) { (s, d) in // Transforms fetched data in main thread to improve responsiveness DispatchQueue.main.async { let sortedGrams = d?.map({ gram -> Gram in var n = gram n["time"] = (gram["time"] as! String).dateFromString() return n }).filter({ (gram) -> Bool in if seenLinks.contains(gram["audio_url"] as! String) { return false } else { return true } }).sorted(by: {($0["time"] as! Date).compare($1["time"] as! Date) == .orderedDescending}) completion(s,sortedGrams) } } } // Recursive get for all following private func getFeed(forUsers: [String], _ gramStack: Grams = [], completion: @escaping (_ succ: Bool, _ data: Grams?) -> Void){ var users = forUsers var grams: Grams = gramStack if users.count >= 1 { databaseFeedRef().child(users.popLast()!).observe(.value, with: { data in print("Fetched \(data.childrenCount) posts") data.children.forEach{ grams.append(($0 as! DataSnapshot).value as! Gram) } self.getFeed(forUsers: users, grams, completion: completion) }) { (e) in print(e) self.getFeed(forUsers: users, grams, completion: completion) } } else{ print(grams) completion(true, grams) } } // Temp not going to implement callbacks func setPostSeen(withURL: String) { var seen = UserDefaults.standard.array(forKey: "seen") ?? [] seen.append(withURL) UserDefaults.standard.setValue(seen, forKey: "seen") } // MARK: - For Current User func getUser(withId: String, callback: @escaping (_ exists: Bool, _ userData: [String: Any]?) -> Void){ databaseUserRef.child(withId).observe(.value, with: { d in callback(true, d.value as! NSDictionary as! [String : Any]) }) { e in print(e) callback(false, nil) } } func updateCurrentUserProfile(username: String = user_name!, uid: String = (user?.uid)!, callback: @escaping (_ succ: Bool) -> Void) { databaseUserRef.child(uid).setValue([ "user_name": username ]) { e, dref in // handles callback(e == nil) } } func getCurrentUserProfile(callback: @escaping (_ succ: Bool) -> Void) { databaseUserRef.child(user!.uid).observeSingleEvent(of: .value, with: { d in let val = d.value let data = val as? NSDictionary let n = data?["user_name"] as? String user_name = n if data?["subscribed"] != nil { subscribed = ((data?["subscribed"] as! [String: Bool]).map{$0.0} as [String]) subscribed!.forEach{ Messaging.messaging().subscribe(toTopic: $0) print("Subscribed to \($0)") } } else { subscribed = [] } print("Loaded Username: \(n)") callback(true) }) } func subscribeToUser(uid: String, callback: @escaping (_ succ: Bool) -> Void ) { databaseUserRef.child("\(user!.uid)/subscribed").child(uid).setValue(true) { (err, dbRef) in if err != nil { print(err) } else { callback(true) } } } func unsuscribeFromUser(uid: String, callback: @escaping (_ succ: Bool) -> Void) { databaseUserRef.child("\(user!.uid)/subscribed/\(uid)").removeValue { (err, dbRef) in if err != nil { print(err) } else { callback(true) } } } // Broadcast activity to all followers func broadcastActivity() -> Void { let client = Client() .baseUrl(url: "https://fcm.googleapis.com") .onError { (e) in print(e) } client.post(url: "/fcm/send") .set(headers: [ "Authorization": "key=\(fcm_key!)", "Content-Type": "application/json" ]) .send(data: [ "to" : "/topics/\(user!.uid)", "priority" : "high", "notification" : [ "body" : "\(user_name!) just posted on \(channel!)", "title" : "New post on \(channel!)" ] ]) .end( done:{ (res) in if res.basicStatus == Response.BasicResponseType.ok { // status of 2xx print("Broadcast POST: \(res.basicStatus)") } else { print(res.basicStatus) } }) } }
true
eace360beb8088964f738cb0f09220e249d9c081
Swift
apple/swift
/test/decl/protocol/req/missing_conformance.swift
UTF-8
6,932
3.078125
3
[ "Apache-2.0", "Swift-exception" ]
permissive
// RUN: %target-typecheck-verify-swift // Test candidates for witnesses that are missing conformances // in various ways. protocol LikeSetAlgebra { func onion(_ other: Self) -> Self // expected-note {{protocol requires function 'onion' with type '(X) -> X'; do you want to add a stub?}} func indifference(_ other: Self) -> Self // expected-note {{protocol requires function 'indifference' with type '(X) -> X'; do you want to add a stub?}} } protocol LikeOptionSet : LikeSetAlgebra, RawRepresentable {} extension LikeOptionSet where RawValue : FixedWidthInteger { func onion(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}} func indifference(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}} } struct X : LikeOptionSet {} // expected-error@-1 {{type 'X' does not conform to protocol 'LikeSetAlgebra'}} // expected-error@-2 {{type 'X' does not conform to protocol 'RawRepresentable'}} protocol IterProtocol {} protocol LikeSequence { associatedtype Iter : IterProtocol // expected-note {{unable to infer associated type 'Iter' for protocol 'LikeSequence'}} func makeIter() -> Iter } extension LikeSequence where Self == Self.Iter { func makeIter() -> Self { return self } // expected-note {{candidate would match and infer 'Iter' = 'Y' if 'Y' conformed to 'IterProtocol'}} } struct Y : LikeSequence {} // expected-error {{type 'Y' does not conform to protocol 'LikeSequence'}} protocol P1 { associatedtype Result func get() -> Result // expected-note {{protocol requires function 'get()' with type '() -> Result'; do you want to add a stub?}} func got() // expected-note {{protocol requires function 'got()' with type '() -> ()'; do you want to add a stub?}} } protocol P2 { static var singularThing: Self { get } } extension P1 where Result : P2 { func get() -> Result { return Result.singularThing } // expected-note {{candidate would match if 'Result' conformed to 'P2'}} } protocol P3 {} extension P1 where Self : P3 { func got() {} // expected-note {{candidate would match if 'Z<T1, T2, T3, Result, T4>' conformed to 'P3'}} } struct Z<T1, T2, T3, Result, T4> : P1 {} // expected-error {{type 'Z<T1, T2, T3, Result, T4>' does not conform to protocol 'P1'}} protocol P4 { func this() // expected-note 2 {{protocol requires function 'this()' with type '() -> ()'; do you want to add a stub?}} } protocol P5 {} extension P4 where Self : P5 { func this() {} // expected-note {{candidate would match if 'W' conformed to 'P5'}} //// expected-note@-1 {{candidate would match if 'S<T>.SS' conformed to 'P5'}} } struct W : P4 {} // expected-error {{type 'W' does not conform to protocol 'P4'}} struct S<T> { struct SS : P4 {} // expected-error {{type 'S<T>.SS' does not conform to protocol 'P4'}} } class C {} protocol P6 { associatedtype T : C // expected-note {{unable to infer associated type 'T' for protocol 'P6'}} func f(t: T) } struct A : P6 { // expected-error {{type 'A' does not conform to protocol 'P6'}} func f(t: Int) {} // expected-note {{candidate can not infer 'T' = 'Int' because 'Int' is not a class type and so can't inherit from 'C'}} } protocol P7 {} protocol P8 { associatedtype T : P7 // expected-note {{unable to infer associated type 'T' for protocol 'P8'}} func g(t: T) } struct B : P8 { // expected-error {{type 'B' does not conform to protocol 'P8'}} func g(t: (Int, String)) {} // expected-note {{candidate can not infer 'T' = '(Int, String)' because '(Int, String)' is not a nominal type and so can't conform to 'P7'}} } protocol P9 { func foo() // expected-note {{protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub?}} } class C2 {} extension P9 where Self : C2 { func foo() {} // expected-note {{candidate would match if 'C3' subclassed 'C2'}} } class C3 : P9 {} // expected-error {{type 'C3' does not conform to protocol 'P9'}} protocol P10 { associatedtype A func bar() // expected-note {{protocol requires function 'bar()' with type '() -> ()'; do you want to add a stub?}} } extension P10 where A == Int { func bar() {} // expected-note {{candidate would match if 'A' was the same type as 'Int'}} } struct S2<A> : P10 {} // expected-error {{type 'S2<A>' does not conform to protocol 'P10'}} protocol P11 {} protocol P12 { associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P12'}} func bar() -> A } extension Int : P11 {} struct S3 : P12 { // expected-error {{type 'S3' does not conform to protocol 'P12'}} func bar() -> P11 { return 0 } // expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{19-19=some }} } protocol P13 { associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P13'}} var bar: A { get } } struct S4: P13 { // expected-error {{type 'S4' does not conform to protocol 'P13'}} var bar: P11 { return 0 } // expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{12-12=some }} } protocol P14 { associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P14'}} subscript(i: Int) -> A { get } } struct S5: P14 { // expected-error {{type 'S5' does not conform to protocol 'P14'}} subscript(i: Int) -> P11 { return i } // expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{24-24=some }} } // https://github.com/apple/swift/issues/55204 // Note: the conformance to collection should succeed struct CountSteps1<T> : Collection { init(count: Int) { self.count = count } var count: Int var startIndex: Int { 0 } var endIndex: Int { count } func index(after i: Int) -> Int { totalSteps += 1 // expected-error {{cannot find 'totalSteps' in scope}} return i + 1 } subscript(i: Int) -> Int { return i } } extension CountSteps1 // expected-error {{type 'CountSteps1<T>' does not conform to protocol 'RandomAccessCollection'}} // expected-error@-1 {{conditional conformance of type 'CountSteps1<T>' to protocol 'RandomAccessCollection' does not imply conformance to inherited protocol 'BidirectionalCollection'}} // expected-note@-2 {{did you mean to explicitly state the conformance like 'extension CountSteps1: BidirectionalCollection where ...'?}} // expected-error@-3 {{type 'CountSteps1<T>' does not conform to protocol 'BidirectionalCollection'}} : RandomAccessCollection where T : Equatable { typealias Index = Int func index(_ i: Index, offsetBy d: Int) -> Index { return i + d } }
true
079a8bf9be5e949238e67cab0be894cf91ddbf71
Swift
Gilbertat/Account
/Account/Class/Tools/SQLiteManager.swift
UTF-8
2,559
2.890625
3
[]
no_license
// // SQLiteManager.swift // Account // // Created by shiyue on 16/4/9. // Copyright © 2016年 shiyue. All rights reserved. // import Foundation class SQLiteManager { // 单例 static let sharedManager = SQLiteManager() // 数据库句柄:COpaquePointer(含糊的指针)通常是一个结构体指针 fileprivate var db:OpaquePointer? = nil /** 打开数据库 - parameter dbName: 数据库名称 */ func openDB(_ dbName:String) { // 获取沙盒路径 let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString // 获取数据库完整路径 let path = documentPath.appendingPathComponent(dbName) /* 参数: 1.fileName: 数据库完整路径 2.数据库句柄 返回值: Int,SQLITE_OK表示打开数据库成功 注意: 1:如果数据库不存在,会创建数据库在打开。 2:如果存在,直接打开 */ if sqlite3_open(path, &db) != SQLITE_OK { print("打开数据库失败,请重试") return } print("打开数据库成功") } /** 执行sql语句 - parameter sql: sql语句 - returns: sql语句是否执行成功 */ internal func execSql(_ sql: String) -> Bool { /** sqlite执行语句 参数: * 1.COpaquePointer: 数据库句柄 * 2.sql: 要执行的sql语句 * 3.callback: sql执行完后的回调,通常为nil * 4.UnsafeMutablePointer<Void>: 回调函数第一个参数地址,通常为nil * 5.错误信息的指针,通常为nil 返回值: Int: SQLite_OK表示执行成功 */ return (sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK) } internal func createTable() -> Bool { let sql = "CREATE TABLE IF NOT EXISTS AC_USERS( \n" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" + "userNames TEXT, \n" + "buyNums INTEGER, \n" + "n_integral INTEGER, \n" + "in_integral INTEGER, \n" + "de_integral INTEGER, \n" + "history INTEGER, \n" + "r_time INTEGER, \n" + "u_time INTEGER \n" + ")" print("sql:\(sql)") // 执行sql return execSql(sql) } }
true
1adfdeae89c6ba14deac511b876a01f489103a56
Swift
oliver3/advent-2020-swift
/Advent.playground/Pages/2020-02.xcplaygroundpage/Contents.swift
UTF-8
1,496
3.734375
4
[]
no_license
import Foundation //let passwords = [ // "1-3 a: abcde", // "1-3 b: cdefg", // "2-9 c: ccccccccc" //] let passwords = readLines("input.txt") let regexp = RegExp(#"^(\d+)-(\d+) (\w): (\w+)$"#) func parser(s: String) -> (Int, Int, Character, String)? { guard let matches = regexp.exec(s), matches.count == 5, let i = Int(matches[1]), let j = Int(matches[2]), let c = matches[3].first else { print("Could not parse \(s)") return nil } let s = matches[4] return (i, j, c, s) } func minMaxCheck(format: (min: Int, max: Int, char: Character, password: String)) -> Bool { var count = 0 for char in format.password { if char == format.char { count += 1 } } return format.min ... format.max ~= count } let passwordsCorrect1 = passwords .compactMap(parser) .filter(minMaxCheck) .count print("Passwords correct part 1: \(passwordsCorrect1)") func eitherOrCheck(format: (pos1: Int, pos2: Int, char: Character, password: String)) -> Bool { let chars = Array(format.password) let char1: Bool = chars[format.pos1 - 1] == format.char let char2: Bool = chars[format.pos2 - 1] == format.char // print(format, char1, char2, char1 != char2) return char1 != char2 } let passwordsCorrect2 = passwords .compactMap(parser) .filter(eitherOrCheck) .count print("Passwords correct part 2: \(passwordsCorrect2)")
true
90707d0fff239613faaa0f8ca681ae9a0483bcb4
Swift
btabaska/Moonshot
/Moonshot/AstronautView.swift
UTF-8
2,182
3
3
[]
no_license
// // AstronautView.swift // Moonshot // // Created by Brandon Tabaska on 6/25/20. // Copyright © 2020 Brandon Tabaska. All rights reserved. // import SwiftUI struct AstronautView: View { let astronaut: Astronaut struct CrewMission { let displayname: String let mission: Mission } let missions: [CrewMission] var body: some View { GeometryReader { geometry in ScrollView(.vertical) { VStack { Image(self.astronaut.id) .resizable() .scaledToFit() .frame(width: geometry.size.width) Text(self.astronaut.description) .padding() .layoutPriority(1) ForEach(self.missions, id: \.displayname ) { CrewMission in VStack { Text(CrewMission.mission.displayName) } } } } } .navigationBarTitle(Text(astronaut.name), displayMode: .inline) } init(astronaut: Astronaut, missions: [Mission]) { self.astronaut = astronaut print(self.astronaut.id) var matches = [CrewMission]() for mission in missions { for crew in mission.crew { if self.astronaut.id == crew.name { print(mission.displayName) matches.append(CrewMission(displayname: mission.displayName, mission: mission)) } } } for match in matches { print(match) print("\n") } self.missions = matches } } struct AstronautView_Previews: PreviewProvider { static let astronauts: [Astronaut] = Bundle.main.decode("astronauts.json") static let mission: [Mission] = Bundle.main.decode("missions.json") static var previews: some View { AstronautView(astronaut: astronauts[0], missions: mission) } }
true
31951202e0bfca60695c46585c571271a3d47a6f
Swift
keenkim1202/TeachersIdea
/TeachersIdea/Sources/Service/FirebaseStorageService.swift
UTF-8
1,853
2.9375
3
[ "MIT" ]
permissive
// // FirebaseStorageService.swift // TeachersIdea // // Created by 김혜진's MAC on 2020/04/23. // Copyright © 2020 homurahomu. All rights reserved. // import UIKit import Foundation import Firebase import Kingfisher protocol FirebaseStorageServiceType { typealias VoidHandler = (Result<Void, AppError>) -> Void typealias UrlHandler = (Result<URL, AppError>) -> Void typealias ImageHandler = (Result<UIImage, AppError>) -> Void func upload(path: String, data: Data, completion: UrlHandler?) func toUrl(path: String, completion: UrlHandler?) func downloadImage(with url: URL, completion: ImageHandler?) } final class FirebaseStorageService: FirebaseStorageServiceType { let ref = Storage.storage().reference() func upload(path: String, data: Data, completion: UrlHandler?) { let imageRef = ref.child(path) imageRef.putData(data, metadata: nil) { (meta, err) in guard err == nil else { completion?(.failure(.uploadFail)); return } self.toUrl(path: path) { result in switch result { case .success(let url): completion?(.success(url)) break case .failure(let error): completion?(.failure(error)) } } } } func toUrl(path: String, completion: UrlHandler?) { let imageRef = ref.child(path) imageRef.downloadURL { (url, err) in guard err == nil, let url = url else { completion?(.failure(.downloadUrlFail)); return } completion?(.success(url)) } } func downloadImage(with url: URL, completion: ImageHandler?) { KingfisherManager.shared.retrieveImage(with: url) { (result) in switch result { case .success(let res): completion?(.success(res.image)); case .failure: completion?(.failure(.downloadImageFail)); } } } }
true
b61bae10a0e72a9d471040eea5eb3b62650ca588
Swift
lopsae/rxSwiftPlaygrounds
/Playgrounds.playground/Pages/SyncronousShare.xcplaygroundpage/Contents.swift
UTF-8
2,453
3.4375
3
[]
no_license
import PlaygroundSupport import RxSwift import RxSwiftPlaygrounds let dishes = ["🍕", "🥗", "🍣", "🌮", "🌯", "🍜"] Binder.root % """ The 👩🏽‍🍳 Chef observable will emit upon subscription three random dishes Elements are emmited immediately and syncronously Possible dishes are: \(dishes) """ Binder.root < "⚙️ Creating 👩🏽‍🍳 Chef observable" var chef: Observable<String>! Binder.indent { p in chef = Observable<String>.create { observer in p < "👩🏽‍🍳 Chef ⚡️ subscribed, cooking!" for _ in 0...2 { let serving = dishes.randomElement()! observer.onNext(serving) } observer.onCompleted() return Disposables.create { p < "👩🏽‍🍳 Chef 🗑 subscription disposed" } } } Binder.newLine() Binder.example("⭕️*️⃣ While-connected Sharing") { p in p % """ Share with defaults has zero replays and a `.whileConnected` lifetime This example will behave the same with any amount of `replay` """ let sharedChef = chef.share(replay: 0, scope: .whileConnected) // same as share() .do(onDispose: { p < "🗑 Share disposed" }) p / "First subscription will receive all elements" sharedChef.subscribe(onNext: { p < "❇️ First: \($0)" }) p % """ The first subscription completes immediately because `chef` is synchronous The share resets after the completed subscription since `.whileConnected` is used When the share resets all elements to replay are also removed """ p / "Second subscription will receive all new elements" sharedChef.subscribe(onNext: { p < "✴️ Second: \($0)" }) } Binder.example("⭕️🎦 Forever & Replay Sharing") { p in p % """ Share with replays and a `.forever` lifetime Second subscription will receive elements depending on `replay` """ let sharedChef = chef.share(replay: 2, scope: .forever) .do(onDispose: { p < "🗑 Share disposed" }) p / "First subscription will receive all elements" sharedChef.subscribe(onNext: { p < "❇️ First: \($0)" }) p % """ The share does not reset after the subscription completes since `.forever` is used The share will neither connect again to 👩🏽‍🍳 Chef when reconnected """ p / "Second subscription receives as many elements as configured in `replay`" sharedChef.subscribe(onNext: { p < "✴️ Second: \($0)" }) } Binder.done👑()
true
3521b0f4ac2669657eb127186c7f8ed3d7648532
Swift
amjadqadomi/OneStepDemo
/OneStepDemo/MainViewCells/WalkSummaryTableViewCell.swift
UTF-8
2,182
2.84375
3
[]
no_license
// // WalkSummaryTableViewCell.swift // OneStepDemo // // Created by Amjad on 11/22/20. // import Foundation import UIKit struct WalkSummaryUIObject { var seconds: Int? var steps: Int? } class WalkSummaryTableViewCell: UITableViewCell { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var stepsLabel: UILabel! @IBOutlet weak var seperatorView: UIView! var walkSummaryUIObject: WalkSummaryUIObject? { didSet { guard let walkSummaryUIObject = walkSummaryUIObject else {return} let stepsString = String(format: "%d", walkSummaryUIObject.steps ?? 0) let secondsString = String(format: "%d", walkSummaryUIObject.seconds ?? 0) let stepsUnit = "Steps" let secondsUnit = "sec" let stepsAttributedString = NSMutableAttributedString(string: stepsString + " " + stepsUnit , attributes: [ .font: UIFont.boldSystemFont(ofSize: 30), .foregroundColor: UIColor.black ]) stepsAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: NSRange(location: stepsString.count + 1, length: stepsUnit.count)) let secondsAttributedString = NSMutableAttributedString(string: secondsString + " " + secondsUnit , attributes: [ .font: UIFont.boldSystemFont(ofSize: 30), .foregroundColor: UIColor.black ]) secondsAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: NSRange(location: secondsString.count + 1, length: secondsUnit.count)) timeLabel.attributedText = secondsAttributedString stepsLabel.attributedText = stepsAttributedString } } override func awakeFromNib() { super.awakeFromNib() initCell() } func initCell() { backgroundColor = .clear timeLabel.textAlignment = .center stepsLabel.textAlignment = .center seperatorView.backgroundColor = UIColor(red: 216.0/255.0, green: 216.0/255.0, blue: 216.0/255.0, alpha: 216.0/255.0) } }
true
b30d8bd39ce56f2a60f90f6685c584ca0b37abdc
Swift
stellentsoftware/LearnMath-iOS
/LearnMath/Supporting Files/Sound Files/SoundFileObject.swift
UTF-8
3,657
2.578125
3
[]
no_license
// // SoundFileObject.swift // LearnMath // // Created by varmabhupatiraju on 16/05/17. // Copyright © 2017 StellentSoft. All rights reserved. // import UIKit import Foundation import AudioToolbox class SoundFileObject: NSObject { var soundFileURLRef:CFURL! // Audio var soundFileObject:SystemSoundID = SystemSoundID() var dingsoundFileURLRef:CFURL! var dingsoundFileObject:SystemSoundID = SystemSoundID() var clicksoundFileURLRef:CFURL! var clicksoundFileObject:SystemSoundID = SystemSoundID() var bangsoundFileURLRef:CFURL! var bangsoundFileObject:SystemSoundID = SystemSoundID() var victorysoundFileURLRef:CFURL! var victorysoundFileObject:SystemSoundID = SystemSoundID() var wooshsoundFileURLRef:CFURL! var wooshsoundFileObject:SystemSoundID = SystemSoundID() var ffftsoundFileURLRef:CFURL! var ffftsoundFileObject:SystemSoundID = SystemSoundID() // Create the URL for the source audio file. func audioSoundsFilesData() { // Create the URL for the source audio file. let bundle = Bundle.main // let quackSound:URL = bundle.url(forResource: "Quack", withExtension: "wav")! let quackSound:URL = bundle.url(forResource: "ohuh", withExtension: "wav")! // let dingSound:URL = bundle.url(forResource: "Ding", withExtension: "aif")! let dingSound:URL = bundle.url(forResource: "Girl Voice- yay", withExtension: "wav")! let clickSound:URL = bundle.url(forResource: "tap", withExtension: "wav")! let bangSound:URL = bundle.url(forResource: "Explosion3", withExtension: "wav")! let victorySound:URL = bundle.url(forResource: "small_crowd_cheering_and_clapping", withExtension: "wav")! let wooshSound:URL = bundle.url(forResource: "swoosh", withExtension: "wav")! let ffftSound:URL = bundle.url(forResource: "ffft", withExtension: "wav")! //Store the urls for the audio files soundFileURLRef = quackSound as CFURL! dingsoundFileURLRef = dingSound as CFURL! clicksoundFileURLRef = clickSound as CFURL! bangsoundFileURLRef = bangSound as CFURL! victorysoundFileURLRef = victorySound as CFURL! wooshsoundFileURLRef = wooshSound as CFURL! ffftsoundFileURLRef = ffftSound as CFURL! // create the sound object for the sound files AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject) AudioServicesCreateSystemSoundID(dingsoundFileURLRef, &dingsoundFileObject) AudioServicesCreateSystemSoundID(clicksoundFileURLRef, &clicksoundFileObject) AudioServicesCreateSystemSoundID(bangsoundFileURLRef, &bangsoundFileObject) AudioServicesCreateSystemSoundID(victorysoundFileURLRef, &victorysoundFileObject) AudioServicesCreateSystemSoundID(wooshsoundFileURLRef, &wooshsoundFileObject) AudioServicesCreateSystemSoundID(ffftsoundFileURLRef, &ffftsoundFileObject) } //Custom function used to remove the sounds func disposeAudioSoundsFilesData() { AudioServicesDisposeSystemSoundID(soundFileObject) AudioServicesDisposeSystemSoundID(dingsoundFileObject) AudioServicesDisposeSystemSoundID(clicksoundFileObject) AudioServicesDisposeSystemSoundID(bangsoundFileObject) AudioServicesDisposeSystemSoundID(victorysoundFileObject) AudioServicesDisposeSystemSoundID(wooshsoundFileObject) AudioServicesDisposeSystemSoundID(ffftsoundFileObject) } }
true
1f263ff9da706c95eed3556cf6e6b0dfa9af4473
Swift
WaqarAhmedBajwa/Cart
/Source/Database/PersistanceService.swift
UTF-8
4,037
2.765625
3
[ "MIT" ]
permissive
// // File.swift // CoreData_Manually // // Created by Waqar Ahmed on 17/05/2018. // Copyright © 2018 MilanConsult GmbH. All rights reserved. // import Foundation import CoreData struct Framework { static let name = "ShoppingCartDB" //Model name static let databaseName = String(format: "%@.sqlite", Framework.name) static let identifier: String = "org.cocoapods.Cart" //Framework bundle ID } class PersistanceService{ public static let shared = PersistanceService() var completionHanler : (() -> ())? var backgroundContext: NSManagedObjectContext! private init(){ let newbackgroundContext = persistentContainer.newBackgroundContext() newbackgroundContext.name = "ShoppingCartDBBackgroundContext" newbackgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy newbackgroundContext.automaticallyMergesChangesFromParent = true backgroundContext = newbackgroundContext NotificationCenter.default.addObserver(self, selector: #selector(contextDidSave(_:)), name: Notification.Name.NSManagedObjectContextDidSave, object: nil) } var context : NSManagedObjectContext{ return persistentContainer.viewContext } lazy var persistentContainer: NSPersistentContainer = { let bundle = Bundle(identifier: Framework.identifier) let modelURL = bundle!.url(forResource: Framework.name, withExtension: "mom")! let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) let container = NSPersistentContainer(name: Framework.name, managedObjectModel: managedObjectModel!) let storeURL = try! FileManager .default .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(Framework.databaseName) print(storeURL) let description = NSPersistentStoreDescription(url: storeURL) description.shouldMigrateStoreAutomatically = true description.shouldInferMappingModelAutomatically = true container.persistentStoreDescriptions = [description] container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { print("PersistanceService: Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext (completion : @escaping () -> ()) { self.completionHanler = completion // DispatchQueue.main.async { let context = self.persistentContainer.viewContext if context.hasChanges { do { try context.save() print("PersistanceService: Data saved successfully!") } catch { let nserror = error as NSError print("Unresolved error \(nserror), \(nserror.userInfo)") } } // } } func saveBackgroundContext(completion : @escaping () -> ()) { self.completionHanler = completion let backgroundContext = PersistanceService.shared.backgroundContext if backgroundContext!.hasChanges { do { try backgroundContext!.save() print("PersistanceService: In background context Data saved successfully!") } catch { let nserror = error as NSError print("PersistanceService: In background context Unresolved error \(nserror), \(nserror.userInfo)") } } } @objc func contextDidSave(_ notification: Notification) { if let handler = self.completionHanler { handler() } } }
true
e7919e0678497e842c13749750b4cc8d6f4d01c6
Swift
kcprs/path-sequencer
/pathSequencer/Sequencing/PitchManager.swift
UTF-8
1,664
2.703125
3
[]
no_license
// // PitchManager.swift // pathSequencer // // Created by Kacper Sagnowski on 11/13/18. // Copyright © 2018 Kacper Sagnowski. All rights reserved. // import SpriteKit import AudioKit class PitchManager { static var staticSelf: PitchManager? = nil static var pitchManagerNode: PitchManagerNode! static var topNote = 108 // MIDI pitch static var bottomNote = 21 // MIDI pitch static let yGap: Int = 40 init() { if PitchManager.staticSelf != nil { fatalError("There can only be one PitchManager") } PitchManager.staticSelf = self } static func getUnquantisedMIDINoteAt(node: SKNode) -> Double { let position = SceneManager.scene!.convert(node.position, from: node.parent!) let proportion = Double(position.y)/Float(yGap * (topNote - bottomNote)) let note = proportion * Double(topNote - bottomNote) + Float(bottomNote) return note } static func getMIDINoteAt(node: SKNode) -> MIDINoteNumber { let note = getUnquantisedMIDINoteAt(node: node) return MIDINoteNumber(note) } static func getFreqAt(node: SKNode) -> Double { let note = getUnquantisedMIDINoteAt(node: node) return MidiUtil.noteToFreq(midiPitch: note) } static func getModAt(node: SKNode) -> Double { let position = SceneManager.scene!.convert(node.position, from: node.parent!) let width = Double(SceneManager.scene!.size.width) return (Double(position.x) + 0.5 * width) / width } static func getCentreY() -> CGFloat { return CGFloat(yGap * (topNote - bottomNote) / 2) } }
true
5311a9e059fdf809152e91a24f84a8e2eb31c23b
Swift
mostafaasf/Weather
/Weather/Resources/SavedCity.swift
UTF-8
318
2.796875
3
[]
no_license
// // SavedCity.swift // Weather // // Created by Mostafa Shawky on 10/17/20. // import Foundation enum SavedCity: String { static let all: [SavedCity] = [.cairo, .munich] case cairo = "Cairo" case munich = "Munich" var weather: [Weather] { Service.shared.getWeatherDataFor(city: self) } }
true
3b8bac43393ddb1625bce9ba3622f96cbe639006
Swift
Jay2113/100DaysOfSwiftUI
/Day2.playground/Contents.swift
UTF-8
1,186
4.375
4
[]
no_license
import Cocoa // Booleans let filename = "paris.jpg" print(filename.hasSuffix(".jpg")) let goodDogs = true //let gameOver = false let isMultiple = 120.isMultiple(of: 3) // ! not operator var isAuthenticated = false isAuthenticated = !isAuthenticated print(isAuthenticated) isAuthenticated = !isAuthenticated print(isAuthenticated) // toggle method var gameOver = false gameOver.toggle() print(gameOver) // Joining strings together via + operator also known as operator overloading - Less Efficient let firstPart = "Hello, " let secondPart = "World!" let greeting = firstPart + secondPart let people = "Haters" let action = "hate" let lyric = people + " gonna " + action print(lyric) let luggageCode = "1" + "2" + "3" + "4" + "5" let quote = "Then he tapped a sign saying \"Believe\" and walked away." // String Interpolation - More Efficient let name = "Jay" let age = 26 let message = "Hello, my name is \(name) and I'm \(age) years old." print(message) let number = 11 //let missionMessage = "Apollo " + String(number) + " landed on the moon." let missionMessage = "Apollo \(number) landed on the moon." // Calculation inside string interpolation print("5 x 5 is \(5*5)")
true
3f74ad4ce430c78b06c4b6144d4d3470d31d7c14
Swift
BlaineBeltran/FoodPin
/FoodPin/Controller/ReviewViewController.swift
UTF-8
4,570
3.046875
3
[]
no_license
// // ReviewViewController.swift // FoodPin // // Created by Blaine Beltran on 11/16/20. // Copyright © 2020 Blaine Beltran. All rights reserved. // import UIKit class ReviewViewController: UIViewController { @IBOutlet var backgroundImageView: UIImageView! // Create a Outlet Collections variable to store multiple similar outlets @IBOutlet var rateButtons: [UIButton]! @IBOutlet var closeButton: UIButton! var restaurant: RestaurantMO! // MARK: - View Controller life cycle override func viewDidLoad() { super.viewDidLoad() // Set the background image on the review controller if let restaurantImage = restaurant.image { backgroundImageView.image = UIImage(data: restaurantImage as Data) } // Applying the blur effect to the background image let blurEffect = UIBlurEffect(style: .dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds backgroundImageView.addSubview(blurEffectView) // Create a Transform object for the rate buttons and close button let moveRightTransform = CGAffineTransform.init(translationX: 600, y: 0) let scaleUpTransform = CGAffineTransform.init(scaleX: 5.0, y: 5.0) let moveScaleTransform = scaleUpTransform.concatenating(moveRightTransform) let moveUpTransform = CGAffineTransform(translationX: 0, y: -600) // Make the buttons invisible and move them off the screen for rateButton in rateButtons { rateButton.transform = moveScaleTransform rateButton.alpha = 0 } closeButton.transform = moveUpTransform } // Create fade in effect for the buttons override func viewWillAppear(_ animated: Bool) { // Animating the rating buttons using a for in loop for index in 0...4 { UIView.animate(withDuration: 0.4, delay: (0.1 + 0.05 * Double(index)), options: [], animations: { self.rateButtons[index].alpha = 1.0 self.rateButtons[index].transform = .identity }, completion: nil) } // This is the first way to animate //UIView.animate(withDuration: 2.0) { // Remember when creating outlet collections they are stored in an array of UIButtoon // So we access the button as a noraml array by indexing -> [0] = first button // We just need to define the start and end states. iOS will handle the rest // self.rateButtons[0].alpha = 1.0 // self.rateButtons[1].alpha = 1.0 // self.rateButtons[2].alpha = 1.0 // self.rateButtons[3].alpha = 1.0 // self.rateButtons[4].alpha = 1.0 // // Second way to animate the buttons /* UIView.animate(withDuration: 0.4, delay: 0.1, options: [], animations: { self.rateButtons[0].alpha = 1.0 self.rateButtons[0].transform = .identity }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.15, options: [], animations: { self.rateButtons[1].alpha = 1.0 self.rateButtons[1].transform = .identity }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.2, options: [], animations: { self.rateButtons[2].alpha = 1.0 self.rateButtons[2].transform = .identity }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.25, options: [], animations: { self.rateButtons[3].alpha = 1.0 self.rateButtons[3].transform = .identity }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.3, options: [], animations: { self.rateButtons[4].alpha = 1.0 self.rateButtons[4].transform = .identity }, completion: nil) */ // Animate the close button UIView.animate(withDuration: 0.4, delay: 0.1, options: [], animations: { self.closeButton.transform = .identity }, completion: nil) } }
true
cb2fa46ea7ed98a71f9d61a42ba05bdb9cc89268
Swift
davidevincenzi/FlowExample
/FlowExample/UserTableViewCell.swift
UTF-8
312
2.671875
3
[]
no_license
// // UserTableViewCell.swift // FlowExample // // Created by Davide Vincenzi on 15.09.17. // import UIKit class UserTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! } extension UserTableViewCell { func configure(with user: UserType) { nameLabel.text = user.name } }
true
f2fa4968682990a9feda653f5b694686d09f5562
Swift
apzcn6/iOSFinal
/apzcn6FinalProject/Conersions.swift
UTF-8
437
2.71875
3
[]
no_license
// // Conversions.swift // ConversionCalculator // // Created by Andrew Ziber on 12/6/19. // Copyright © 2019 Andrew Ziber. All rights reserved. // import Foundation struct Conversions { var labelCon: String var inputCon: String var outputCon: String init(labelCon: String, inputCon: String, outputCon: String) { self.labelCon = labelCon self.inputCon = inputCon self.outputCon = outputCon } }
true
2b7863e45a716b7a94bcd4f4d285959c2193d43d
Swift
fgengine/quickly
/Quickly/QMetatype.swift
UTF-8
578
2.859375
3
[ "MIT" ]
permissive
// // Quickly // public struct QMetatype : Hashable { public let base: AnyClass public init(_ base: AnyClass) { self.base = base } public init(_ base: Any) { self.base = type(of: base) as! AnyClass } public var hashValue: Int { get { return ObjectIdentifier(self.base).hashValue } } public func hash(into hasher: inout Hasher) { ObjectIdentifier(self.base).hash(into: &hasher) } public static func == (lhs: QMetatype, rhs: QMetatype) -> Bool { return lhs.base == rhs.base } }
true
dbcf65c32dd38ddbf17f6d962ecefdd58683b8de
Swift
fnxpt/OpenWeatherTest
/OpenWeatherTests/Model/LocationTest.swift
UTF-8
622
2.640625
3
[]
no_license
import XCTest @testable import OpenWeather class ForecastTest: XCTestCase { func testCSVInit() { let csv = "1519225200.0;8.36;overcast clouds;804;" do { let item = try Forecast(csv: csv) let date = Date(timeIntervalSince1970: 1519225200.0) XCTAssertEqual(item.code, 804) XCTAssertEqual(item.date, date) XCTAssertEqual(item.weather, "overcast clouds") XCTAssertEqual(item.temp, 8.36) } catch { XCTFail(error.localizedDescription) } } }
true
835fa46233d5913c88f022b957d763a6ec174637
Swift
arekt/Convertible
/ConvertibleTests/Cocoa Extensions/NSDictionary+Convertible.swift
UTF-8
909
2.671875
3
[ "MIT" ]
permissive
// // NSDictionary+Convertible.swift // Convertible // // Created by Bradley Hilton on 6/24/15. // Copyright © 2015 Skyvive. All rights reserved. // import XCTest import Convertible class NSDictionary_Convertible: XCTestCase { func testDataConvertible() { do { let result = try NSDictionary.initializeWithData(Data.dictionaryData) let data = try result.serializeToData() XCTAssert(Data.dictionaryData == data) } catch { XCTFail() } } func testJsonConvertible() { do { let dictionary: NSDictionary = ["Hello" : "World"] let result = try NSDictionary.initializeWithJson(JsonValue(object: dictionary)) let object = try result.serializeToJson().object as! NSDictionary XCTAssert(dictionary == object) } catch { XCTFail() } } }
true
87f1ef21a9c797c622a914b0eaf06c8de7933b75
Swift
jamesrochabrun/MemoryTunes
/MemoryTunes/ReSwift/State/RoutingState.swift
UTF-8
419
2.78125
3
[]
no_license
/** * Copyright (c) 2017 Razeware LLC */ import ReSwift ///Because it’s good practice, you’ll group state variables into sub-state structures struct RoutingState: StateType { var navigationState: RoutingDestination init(navState: RoutingDestination = .menu) { self.navigationState = navState } } // RoutingState contains navigationState, which represents the current destination on screen.
true
a975ab6dd0d6443ea9111bf353e977b4b35430f7
Swift
jisudong555/swift
/weibo/weibo/Classes/Home/Popover/PopoverAnimator.swift
UTF-8
3,903
2.640625
3
[ "MIT" ]
permissive
// // PopoverAnimator.swift // weibo // // Created by jisudong on 16/4/15. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit // 定义常量保存通知名称 let PopoverAnimatorWillDismiss = "PopoverAnimatorWillDismiss" class PopoverAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { /// 记录当前是否打开 var isPresent = false /// 保存菜单的大小 var presentFrame = CGRectZero // 实现代理方法, 告诉系统谁来负责转场动画 // UIPresentationController iOS8推出的专门用于负责转场动画的 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let popver = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting) popver.presentFrame = presentFrame return popver } /** 返回动画时长 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 - returns: 动画时长 */ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /** 告诉系统如何动画,无论是展示还是消失都会调用这个方法 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 */ func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if isPresent { let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! toView.transform = CGAffineTransformMakeScale(1.0, 0.0) // 注意:一定要将视图添加到容器上 transitionContext.containerView()?.addSubview(toView) toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0) UIView.animateWithDuration(0.5, animations: { // 清空transform toView.transform = CGAffineTransformIdentity }) { (_) -> Void in // 执行完动画一定要告诉系统,不然可能会出现未知错误 transitionContext.completeTransition(true) } } else { let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) UIView.animateWithDuration(0.2, animations: { fromView?.transform = CGAffineTransformMakeScale(1.0, 0.000001) }, completion: { (_) in transitionContext.completeTransition(true) }) } } // MRRK: - 只要实现了这个方法,那么系统自带的默认动画就没了,“所有”东西都需要自己来实现 /** 告诉系统谁来负责Modal的展现动画 - parameter presented: 被展现视图 - parameter presenting: 发起的视图 - parameter source: - returns: 谁来负责 */ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true return self } /** 告诉系统谁来负责Modal的消失动画 - parameter dismissed: 被关闭的视图 - returns: 谁来负责 */ func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false NSNotificationCenter.defaultCenter().postNotificationName(PopoverAnimatorWillDismiss, object: self) return self } }
true
8ea7f5b2f0e7103160248ab14f62ef6071f88099
Swift
JennyShalai/whiteboarding-practice
/task-8-print-string-loop-and-recursion.playground/Contents.swift
UTF-8
1,543
4.09375
4
[]
no_license
// print string with loop and recursion /////////////////// print with loop ////////////////////// /////////////////// if can not modify input ////////////////////// func printString(str: String) { for i in 0..<str.characters.count { print("\(str[str.index(str.startIndex, offsetBy: i)])") } } /////////////////// print with loop ////////////////////// /////////////////// if can modify input ////////////////////// func printStr(str: String) { var string = str for _ in 0..<str.characters.count { print(string.characters.popFirst()!) } } /////////////////// print with recursion ////////////////////// /////////////////// if can not modify input ////////////////////// func printStringWithRecursion(str: String) { if str.characters.count > 0 { print(str.characters.first!) } else { return } // substring, range of chars from 2d to last let stringWithoutPrintedChar = str[str.characters.index(after: str.characters.startIndex)..<str.characters.endIndex] printStringWithRecursion(str: stringWithoutPrintedChar) } /////////////////// print with recursion ////////////////////// /////////////////// if can modify input ////////////////////// func printStrWithRecursion(str: String) { var string = str if str.characters.count > 0 { print(string.characters.popFirst()!) printStrWithRecursion(str: string) } else { return } }
true
51f797aae92f7b0dc14a4c81186f38fa81bc146e
Swift
tinotusa/hacking-with-swift
/Moonshot/Moonshot/Views/Mission/MissionDetail.swift
UTF-8
2,043
2.9375
3
[]
no_license
// // MissionDetail.swift // Moonshot // // Created by Tino on 23/4/21. // import SwiftUI struct MissionDetail: View { let mission: Mission @Environment(\.presentationMode) var presentationMode var body: some View { ZStack { background ScrollView { backButton VStack(alignment: .center) { Text(mission.displayName) .font(.largeTitle) .underline() Spacer() Text(mission.description) Divider() Text("Astronauts") .font(.title) ForEach(mission.crew) { crewMember in NavigationLink(destination: AstronautDetail(named: crewMember.name)) { AstronautRow(named: crewMember.name) } } } .foregroundColor(.white) .padding(.horizontal) } } .navigationBarHidden(true) } var background: some View { ZStack { Color.black Image("moon") .resizable() .scaledToFit() .offset(x: 280) } .ignoresSafeArea() } var backButton: some View { HStack { Button(action: dismiss) { HStack { Image(systemName: "chevron.left") Text("Back") } .foregroundColor(.blue) } Spacer() } .padding(.horizontal) } func dismiss() { presentationMode.wrappedValue.dismiss() } } struct MissionDetail_Previews: PreviewProvider { static var previews: some View { MissionDetail(mission: Constants.missions[1]) } }
true
d3a3781fbf7ae59048b616a410bcdf15494ad1ee
Swift
Nicki9300/TestMoviesDataBase
/TestMoviesDataBase/TestMoviesDataBase/View/CustomTabBar/CustomSliderView.swift
UTF-8
5,929
2.515625
3
[]
no_license
// // SliderView.swift // TestMoviesDataBase // // Created by Коля Мамчур on 27.04.2021. // import UIKit protocol SliderViewProtocol: class { func selectItem(_ item: SliderItem) } enum SliderItem: Int, CaseIterable { case stories = 0 case video case favourites } class SelectedSliderItem { static let shared = SelectedSliderItem() private init() {} var selectedSlideItem: SliderItem = .stories } class CustomSliderView: UIView { // MARK: - IBOutlets @IBOutlet weak var storiesLabel: UILabel! @IBOutlet weak var storiesView: UIView! @IBOutlet weak var videoLabel: UILabel! @IBOutlet weak var videoView: UIView! @IBOutlet weak var favoritesView: UIView! @IBOutlet weak var favoritesLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! // MARK: - Properties private var sliderItem: SliderItem = SelectedSliderItem.shared.selectedSlideItem private var sliderItemCount = CGFloat(SliderItem.allCases.count) // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() resetContent() setupView() configurateCollectionView() } // MARK: - UI private func resetContent() { } private func setupView() { configurateStoriesItem() configurateVideoItem() configurateFavoritesItem() } private func configurateCollectionView() { collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib(nibName: TabBarCollectionViewCell.identifier, bundle: nil), forCellWithReuseIdentifier: TabBarCollectionViewCell.identifier) } private func configurateStoriesItem() { storiesLabel.text = "Stories".uppercased() if sliderItem == .stories { storiesLabel.font = UIFont(name: "Malayalam Sangam MN Bold", size: 20) storiesLabel.textColor = .white storiesView.isHidden = false } else { storiesLabel.textColor = .lightGray storiesLabel.font = UIFont(name: "Malayalam Sangam MN", size: 20) storiesView.isHidden = true } } private func configurateVideoItem() { videoLabel.text = "Video".uppercased() if sliderItem == .video { videoLabel.font = UIFont(name: "Malayalam Sangam MN Bold", size: 20) videoLabel.textColor = .white videoView.isHidden = false } else { videoLabel.textColor = .lightGray videoLabel.font = UIFont(name: "Malayalam Sangam MN", size: 20) videoView.isHidden = true } } private func configurateFavoritesItem() { favoritesLabel.text = "favorites".uppercased() if sliderItem == .favourites { favoritesLabel.font = UIFont(name: "Malayalam Sangam MN Bold", size: 20) favoritesLabel.textColor = .white favoritesView.isHidden = false } else { favoritesLabel.textColor = .lightGray favoritesLabel.font = UIFont(name: "Malayalam Sangam MN", size: 20) favoritesView.isHidden = true } } } extension CustomSliderView: UICollectionViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { var itemNumber = Int(round((scrollView.contentOffset.x) / (scrollView.frame.width))) switch sliderItem { case .stories : itemNumber = sliderItem.rawValue + 1 case .video: itemNumber = scrollView.contentOffset.x > 0 ? sliderItem.rawValue + 1 : sliderItem.rawValue - 1 case .favourites: itemNumber = sliderItem.rawValue - 1 } switch itemNumber { case 0: SelectedSliderItem.shared.selectedSlideItem = .stories setupView() if let parent = self.parentViewController { let vc = StoriesViewController.instance(.stories) vc.presenter = StoriesPresenter(view: vc) parent.pushToVC(vc, animated: false) } case 1: SelectedSliderItem.shared.selectedSlideItem = .video setupView() if let parent = self.parentViewController { let vc = VideoViewController.instance(.video) vc.presenter = VideoPresenter(view: vc) parent.pushToVC(vc, animated: false) } case 2: SelectedSliderItem.shared.selectedSlideItem = .favourites setupView() if let parent = self.parentViewController { let vc = FavouritesViewController.instance(.favourites) vc.presenter = FavouritesPresenter(view: vc) parent.pushToVC(vc, animated: false) } default: return } } } extension CustomSliderView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return SliderItem.allCases.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TabBarCollectionViewCell.identifier, for: indexPath) as! TabBarCollectionViewCell return cell } } extension CustomSliderView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: UIScreen.main.bounds.width, height: 50) } } extension CustomSliderView: SliderViewProtocol { func selectItem(_ item: SliderItem) { sliderItem = item setupView() } }
true
4b1fddd33a4f219be77bc4f746205aa8f6052972
Swift
Benny-iPhone/hackeruJul2018
/OODPatterns.playground/Sources/VehicleFactory.swift
UTF-8
388
3.109375
3
[]
no_license
import Foundation public class VehicleFactory{ public static func createVehicle(_ type: String)->Vehicle?{ switch type.lowercased() { case "car", "private": return PrivateCar(); case "bus": return Bus(); case "bike", "motorcycle": return Bike(); default: return nil; } } }
true
07eeadacdba6008d4dc19385e14f256b35260808
Swift
sanengineer/microservices-api-gateway-with-swift-on-server
/Sources/App/Controllers/UserController.swift
UTF-8
2,851
2.828125
3
[]
no_license
import Vapor struct UserController: RouteCollection { let userServiceUrl: String init(userServiceHostname: String, userServicePort: String) { userServiceUrl = "http://\(userServiceHostname):\(userServicePort)" } func boot(routes: RoutesBuilder) throws { let routeGroup = routes.grouped("api", "v1", "superuser") routeGroup.get(use: getAllHandler) routeGroup.get("count", use: getUsersNumber) routeGroup.get(":id", use: getOneHandler) routeGroup.post("auth","register",use: createHandler) routeGroup.post("auth","login", use: loginHandler) routeGroup.put(":id", use: updateBioUser) } func getAllHandler(_ req: Request) -> EventLoopFuture<ClientResponse> { return req.client.get("\(userServiceUrl)/user") } func getUsersNumber(_ req: Request) -> EventLoopFuture<ClientResponse> { return req.client.get("\(userServiceUrl)/user/count") } func getOneHandler(_ req: Request) throws -> EventLoopFuture<ClientResponse> { let id = try req.parameters.require("id", as: UUID.self) return req.client.get("\(userServiceUrl)/user/\(id)"){ get in guard let authHeader = req.headers[.authorization].first else { throw Abort(.unauthorized) } // print("\n","TOKENNN", authHeader, "\n") get.headers.add(name: .authorization, value: authHeader) } } func createHandler(_ req: Request) -> EventLoopFuture<ClientResponse> { return req.client.post("\(userServiceUrl)/user/auth/register") { createRequest in try createRequest.content.encode(req.content.decode(CreateUserData.self)) } } func updateBioUser(_ req: Request) throws -> EventLoopFuture<ClientResponse> { let id = try req.parameters.require("id", as: UUID.self) return req.client.put("\(userServiceUrl)/user/\(id)"){ put in guard let authHeader = req.headers[.authorization].first else { throw Abort(.unauthorized) } put.headers.add(name: .authorization, value: authHeader) try put.content.encode(req.content.decode(UpdateUserBio.self)) } } func loginHandler(_ req: Request) -> EventLoopFuture<ClientResponse> { return req.client.post("\(userServiceUrl)/superuser/auth/login") { loginRequst in guard let authHeader = req.headers[.authorization].first else { throw Abort(.unauthorized) } loginRequst.headers.add(name: .authorization, value: authHeader) } } }
true
a50a345bdb058bfa488e95cb090553c68dc79545
Swift
alexnaldo/aozora-ios
/ANParseKit/Vendor/Tribute/Tribute.swift
UTF-8
14,227
2.953125
3
[ "MIT" ]
permissive
// // Tribute.swift // Tribute // // Created by Sash Zats on 11/26/15. // Copyright © 2015 Sash Zats. All rights reserved. // import UIKit public struct Attributes { typealias RawAttributes = [String: AnyObject] public enum TextEffect { case Letterpress } public enum GlyphDirection { case Vertical case Horizontal } public enum Stroke { case NotFilled(width: Float) case Filled(width: Float) } public var alignment: NSTextAlignment? public var backgroundColor: UIColor? public var baseline: Float? public var color: UIColor? public var direction: GlyphDirection? public var expansion: Float? public var font: UIFont? public var kern: Float? public var leading: Float? public var ligature: Bool? public var obliqueness: Float? public var strikethrough: NSUnderlineStyle? public var strikethroughColor: UIColor? public var stroke: Stroke? public var strokeColor: UIColor? public var textEffect: TextEffect? public var underline: NSUnderlineStyle? public var underlineColor: UIColor? public var URL: NSURL? public var lineBreakMode: NSLineBreakMode? public var lineHeightMultiplier: Float? public var paragraphSpacingAfter: Float? public var paragraphSpacingBefore: Float? public var headIndent: Float? public var tailIndent: Float? public var firstLineHeadIndent: Float? public var minimumLineHeight: Float? public var maximumLineHeight: Float? public var hyphenationFactor: Float? public var allowsTighteningForTruncation: Bool? } private extension Attributes.TextEffect { init?(stringValue: String) { if stringValue == NSTextEffectLetterpressStyle { self = .Letterpress } else { return nil } } var stringValue: String { switch self { case .Letterpress: return NSTextEffectLetterpressStyle } } } private extension Attributes.Stroke { init(floatValue: Float) { if floatValue < 0 { self = .Filled(width: -floatValue) } else { self = .NotFilled(width: floatValue) } } var floatValue: Float { switch self { case let .NotFilled(width): return width case let .Filled(width): return -width } } } private extension Attributes.GlyphDirection { init?(intValue: Int) { switch intValue { case 0: self = .Horizontal case 1: self = .Vertical default: return nil } } var intValue: Int { switch self { case .Horizontal: return 0 case .Vertical: return 1 } } } extension Attributes { init(rawAttributes attributes: RawAttributes) { self.backgroundColor = attributes[NSBackgroundColorAttributeName] as? UIColor self.baseline = attributes[NSBaselineOffsetAttributeName] as? Float self.color = attributes[NSForegroundColorAttributeName] as? UIColor if let direction = attributes[NSVerticalGlyphFormAttributeName] as? Int { self.direction = GlyphDirection(intValue: direction) } self.expansion = attributes[NSExpansionAttributeName] as? Float self.font = attributes[NSFontAttributeName] as? UIFont if let ligature = attributes[NSLigatureAttributeName] as? Int { self.ligature = (ligature == 1) } self.kern = attributes[NSKernAttributeName] as? Float self.obliqueness = attributes[NSObliquenessAttributeName] as? Float if let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle { self.alignment = paraStyleCompare(paragraph) { $0.alignment } self.leading = paraStyleCompare(paragraph) { Float($0.lineSpacing) } self.lineHeightMultiplier = paraStyleCompare(paragraph) { Float($0.lineHeightMultiple) } self.paragraphSpacingAfter = paraStyleCompare(paragraph) { Float($0.paragraphSpacing) } self.paragraphSpacingBefore = paraStyleCompare(paragraph) { Float($0.paragraphSpacingBefore) } self.headIndent = paraStyleCompare(paragraph) { Float($0.headIndent) } self.tailIndent = paraStyleCompare(paragraph) { Float($0.tailIndent) } self.firstLineHeadIndent = paraStyleCompare(paragraph) { Float($0.firstLineHeadIndent) } self.minimumLineHeight = paraStyleCompare(paragraph) { Float($0.minimumLineHeight) } self.maximumLineHeight = paraStyleCompare(paragraph) { Float($0.maximumLineHeight) } self.hyphenationFactor = paraStyleCompare(paragraph) { Float($0.hyphenationFactor) } if #available(iOS 9.0, *) { self.allowsTighteningForTruncation = paraStyleCompare(paragraph) { $0.allowsDefaultTighteningForTruncation } } } if let strikethrough = attributes[NSStrikethroughStyleAttributeName] as? Int { self.strikethrough = NSUnderlineStyle(rawValue: strikethrough) } self.strikethroughColor = attributes[NSStrikethroughColorAttributeName] as? UIColor if let strokeWidth = attributes[NSStrokeWidthAttributeName] as? Float { self.stroke = Stroke(floatValue: strokeWidth) } self.strokeColor = attributes[NSStrokeColorAttributeName] as? UIColor if let textEffect = attributes[NSTextEffectAttributeName] as? String { self.textEffect = TextEffect(stringValue: textEffect) } if let underline = attributes[NSUnderlineStyleAttributeName] as? Int { self.underline = NSUnderlineStyle(rawValue: underline) } self.underlineColor = attributes[NSUnderlineColorAttributeName] as? UIColor self.URL = attributes[NSLinkAttributeName] as? NSURL } /// convenience method for comparing attributes on `paragraph` vs `defaultParagrah` private func paraStyleCompare<U: Equatable>(paragraph: NSParagraphStyle, trans: NSParagraphStyle -> U) -> U? { let x = trans(paragraph) let y = trans(NSParagraphStyle.defaultParagraphStyle()) return (x == y) ? nil : x } } // MARK: Convenience methods extension Attributes { public var fontSize: Float? { set { if let newValue = newValue { self.font = currentFont.fontWithSize(CGFloat(newValue)) } else { self.font = nil } } get { return Float(currentFont.pointSize) } } public var bold: Bool { set { setTrait(.TraitBold, enabled: newValue) } get { return currentFont.fontDescriptor().symbolicTraits.contains(.TraitBold) } } public var italic: Bool { set { setTrait(.TraitItalic, enabled: newValue) } get { return currentFont.fontDescriptor().symbolicTraits.contains(.TraitItalic) } } private mutating func setTrait(trait: UIFontDescriptorSymbolicTraits, enabled: Bool) { let font = currentFont let descriptor = font.fontDescriptor() var traits = descriptor.symbolicTraits if enabled { traits.insert(trait) } else { traits.remove(trait) } let newDescriptor = descriptor.fontDescriptorWithSymbolicTraits(traits) self.font = UIFont(descriptor: newDescriptor, size: font.pointSize) } private static let defaultFont = UIFont.systemFontOfSize(12) private var currentFont: UIFont { if let font = self.font { return font } else { return Attributes.defaultFont } } } extension Attributes { mutating public func reset() { backgroundColor = nil baseline = nil color = nil direction = nil expansion = nil font = nil ligature = nil kern = nil obliqueness = nil alignment = nil leading = nil strikethrough = nil strikethroughColor = nil stroke = nil strokeColor = nil textEffect = nil underline = nil underlineColor = nil URL = nil lineBreakMode = nil lineHeightMultiplier = nil paragraphSpacingAfter = nil paragraphSpacingBefore = nil headIndent = nil tailIndent = nil firstLineHeadIndent = nil minimumLineHeight = nil maximumLineHeight = nil hyphenationFactor = nil allowsTighteningForTruncation = nil } } extension Attributes { var rawAttributes: RawAttributes { var result: RawAttributes = [:] result[NSBackgroundColorAttributeName] = backgroundColor result[NSBaselineOffsetAttributeName] = baseline result[NSForegroundColorAttributeName] = color result[NSVerticalGlyphFormAttributeName] = direction?.intValue result[NSExpansionAttributeName] = expansion result[NSFontAttributeName] = font result[NSKernAttributeName] = kern if let ligature = ligature { result[NSLigatureAttributeName] = ligature ? 1 : 0 } if let paragraph = retrieveParagraph() { result[NSParagraphStyleAttributeName] = paragraph } result[NSStrikethroughStyleAttributeName] = strikethrough?.rawValue result[NSStrikethroughColorAttributeName] = strikethroughColor result[NSStrokeWidthAttributeName] = stroke?.floatValue result[NSStrokeColorAttributeName] = strokeColor result[NSObliquenessAttributeName] = obliqueness result[NSTextEffectAttributeName] = textEffect?.stringValue result[NSUnderlineStyleAttributeName] = underline?.rawValue result[NSUnderlineColorAttributeName] = underlineColor result[NSLinkAttributeName] = URL return result } private func isAnyNotNil(objects: Any? ...) -> Bool { for object in objects { if object != nil { return true } } return false } private func retrieveParagraph() -> NSMutableParagraphStyle? { if !isAnyNotNil(leading, alignment, lineBreakMode, lineHeightMultiplier, paragraphSpacingAfter, paragraphSpacingBefore, headIndent, tailIndent, firstLineHeadIndent, minimumLineHeight, maximumLineHeight, hyphenationFactor, allowsTighteningForTruncation) { return nil } let paragraph = NSMutableParagraphStyle() if let leading = leading { paragraph.lineSpacing = CGFloat(leading) } if let leading = leading { paragraph.lineSpacing = CGFloat(leading) } if let alignment = alignment { paragraph.alignment = alignment } if let lineBreakMode = lineBreakMode { paragraph.lineBreakMode = lineBreakMode } if let lineHeightMultiplier = lineHeightMultiplier { paragraph.lineHeightMultiple = CGFloat(lineHeightMultiplier) } if let paragraphSpacingAfter = paragraphSpacingAfter { paragraph.paragraphSpacing = CGFloat(paragraphSpacingAfter) } if let paragraphSpacingBefore = paragraphSpacingBefore { paragraph.paragraphSpacingBefore = CGFloat(paragraphSpacingBefore) } if let headIndent = headIndent { paragraph.headIndent = CGFloat(headIndent) } if let tailIndent = tailIndent { paragraph.tailIndent = CGFloat(tailIndent) } if let firstLineHeadIndent = firstLineHeadIndent { paragraph.firstLineHeadIndent = CGFloat(firstLineHeadIndent) } if let minimumLineHeight = minimumLineHeight { paragraph.minimumLineHeight = CGFloat(minimumLineHeight) } if let maximumLineHeight = maximumLineHeight { paragraph.maximumLineHeight = CGFloat(maximumLineHeight) } if let hyphenationFactor = hyphenationFactor { paragraph.hyphenationFactor = hyphenationFactor } if #available(iOS 9.0, *) { if let allowsTighteningForTruncation = allowsTighteningForTruncation { paragraph.allowsDefaultTighteningForTruncation = allowsTighteningForTruncation } } return paragraph } } extension NSAttributedString { var runningAttributes: [String: AnyObject]? { guard length > 0 else { return nil } return attributesAtIndex(length - 1, effectiveRange: nil) } private var fullRange: NSRange { return NSRange(location: 0, length: length) } } public extension NSMutableAttributedString { public typealias AttributeSetter = (inout attributes: Attributes) -> Void public func add(text: String, setter: AttributeSetter? = nil) -> NSMutableAttributedString { var attributes = runningOrNewAttributes setter?(attributes: &attributes) return add(text, attributes: attributes) } var runningOrNewAttributes: Attributes { if let runningAttributes = self.runningAttributes { return Attributes(rawAttributes: runningAttributes) } else { return Attributes() } } func add(text: String, attributes: Attributes) -> NSMutableAttributedString { let attributedString = NSAttributedString(string: text, attributes: attributes.rawAttributes) appendAttributedString(attributedString) return self } } public extension NSMutableAttributedString { public func add(image: UIImage, bounds: CGRect? = nil, setter: AttributeSetter? = nil) -> NSMutableAttributedString { var attributes = runningOrNewAttributes setter?(attributes: &attributes) let attachment = NSTextAttachment() attachment.image = image if let bounds = bounds { attachment.bounds = bounds } let string = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) string.addAttributes(attributes.rawAttributes, range: string.fullRange) appendAttributedString(string) return self } }
true
471b9be4eb067d2bab33b241bee3c5270e40042d
Swift
slabgorb/Tiler
/Tiler/ImageItem.swift
UTF-8
469
2.8125
3
[ "MIT" ]
permissive
// // ImageItem.swift // Tiler // // Created by Keith Avery on 4/1/16. // Copyright © 2016 Keith Avery. All rights reserved. // import Foundation class ImageItem { var name: String init(key:String, dataDictionary:Dictionary<String,String>) { self.name = dataDictionary[key]! } class func newImageItem(key: String, dataDictionary:Dictionary<String,String>) -> ImageItem { return ImageItem(key: key, dataDictionary: dataDictionary) } }
true
2d58258133a09f84f117dff7ee16791e1629f29c
Swift
hvnwnd/Weather
/Weather/Model/DayInfo.swift
UTF-8
688
2.953125
3
[]
no_license
// // DayInfo.swift // Weather // // Created by Bin CHEN on 12/27/16. // Copyright © 2016 Fantestech. All rights reserved. // import Foundation struct DayInfo { var date : Date? var tempMax : Int? var tempMin : Int? var icon : String? var weatherLabel : String? } extension DayInfo { init(_ list : [WeatherInfo]) { self.date = list.first?.updatedDate self.tempMax = list.reduce(Int.min){ max($0, $1.tempMax!) } self.tempMin = list.reduce(Int.max){ min($0, $1.tempMin!) } self.icon = (list.map{ $0.icon} as! [String] ).mode self.weatherLabel = (list.map{ $0.weatherLabel! }).mode } }
true
7bb6589a1b1978e57af1b4268a4b5721c2fefe74
Swift
surjitC/MoviesApp
/MoviesApp/ViewControllers/MovieViewController.swift
UTF-8
2,752
2.765625
3
[]
no_license
// // MovieViewController.swift // MoviesApp // // Created by Surjit on 13/03/21. // import UIKit class MovieViewController: UIViewController { @IBOutlet var moviesTableView: UITableView! var movieViewModel: MovieViewModel? class func initializeVC() -> MovieViewController { guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MovieViewController") as? MovieViewController else { return MovieViewController() } return vc } var imageDownloader = ImageDownloader() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Movies" self.moviesTableView.tableFooterView = UIView() self.moviesTableView.register(UINib(nibName: "MovieTableViewCell", bundle: nil), forCellReuseIdentifier: "MovieTableViewCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.imageDownloader.urlResquest?.invalidateAndCancel() } } extension MovieViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.movieViewModel?.getMoviesCount() ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieTableViewCell", for: indexPath) as? MovieTableViewCell else { preconditionFailure("Failed to load movie cell") } let movie = self.movieViewModel?.getMovie(from: indexPath.row) cell.configureCell(for: movie) self.imageDownloader.loadImage(from: movie?.poster, completionHandler: { (image) in if let updateCell = tableView.cellForRow(at: indexPath) as? MovieTableViewCell { updateCell.posterImageView.contentMode = image == #imageLiteral(resourceName: "imagePlaceholder") ? .scaleAspectFit : .scaleAspectFill updateCell.posterImageView.image = image } }) return cell } } extension MovieViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = MovieDetailsViewController.initializeVC() vc.movie = self.movieViewModel?.getMovie(from: indexPath.row) self.navigationController?.pushViewController(vc, animated: true) } }
true
3bf237ee34c8686f98720be8fdfada6676f05191
Swift
possel/chomp-ios
/Chomp/Classes/General/Entity/UserEntity.swift
UTF-8
793
2.984375
3
[ "ISC" ]
permissive
// // User.swift // Chomp // // Created by Sky Welch on 07/10/2015. // Copyright © 2015 Sky Welch. All rights reserved. // import Foundation import SwiftyJSON struct UserEntity: JsonDecodable { let id: Int let nick: String let username: String? let host: String? let server: Int let realname: String? let current: Bool static func decode(json: JSON) -> UserEntity? { if let id = json["id"].int, let nick = json["nick"].string, let server = json["server"].int, let current = json["current"].bool { return UserEntity(id: id, nick: nick, username: json["username"].string, host: json["host"].string, server: server, realname: json["realname"].string, current: current) } return nil } }
true
3f33ccf396040ca6bc12ed05274cf0ebe67f33f6
Swift
LaytaKhon/Day7Assignment
/Day7Assignment/BeerViewController.swift
UTF-8
5,948
2.59375
3
[]
no_license
// // BeerViewController.swift // Day7Assignment // // Created by MIT App Dev on 11/16/18. // Copyright © 2018 PADC. All rights reserved. // import UIKit class BeerViewController: UIViewController { @IBOutlet weak var mainCollectionView: UICollectionView! var data = Beer() var ingrediant = ingerdiant() var array : [DataObj] = [] var array1 : [DataObj] = [] override func viewDidLoad() { super.viewDidLoad() self.mainCollectionView.dataSource = self self.mainCollectionView.delegate = self cellRegister() let obj1 = DataObj() obj1.name = "Brewers_tips : " obj1.value = data.brewers_tips ?? "" array1.append(obj1) let obj2 = DataObj() obj2.name = "Contributed_by : " obj2.value = data.contributed_by ?? "" array1.append(obj2) } func cellRegister(){ CellRegisterUtil.cellRegister(nibName: "ImageCollectionViewCell", collectionView: self.mainCollectionView) CellRegisterUtil.cellRegister(nibName: "DetailCollectionViewCell", collectionView: self.mainCollectionView) CellRegisterUtil.cellRegister(nibName: "IngrediantCollectionViewCell", collectionView: self.mainCollectionView) CellRegisterUtil.cellRegister(nibName: "DecThingsCollectionViewCell", collectionView: self.mainCollectionView) CellRegisterUtil.cellRegister(nibName: "brewTipCollectionViewCell", collectionView: self.mainCollectionView) } @IBAction func back(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } /* // 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. } */ } extension BeerViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 1 } else if section == 2{ return array.count } else if section == 3 { return data.food_pairing!.count } else if section == 4 { return array1.count } return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell cell.ivImage.sd_setImage(with: URL(string: data.image_url ?? "icons8-champagne_bottle_filled"), placeholderImage: UIImage(named: "icons8-champagne_bottle_filled")) // print("image=>\(data.image_url)") return cell }else if indexPath.section == 1{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DetailCollectionViewCell", for: indexPath) as! DetailCollectionViewCell cell.name.text = data.name cell.tagLine.text = data.tagline cell.firstBrewed.text = data.first_brewed cell.descText.text = data.desc return cell }else if indexPath.section == 2{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "IngrediantCollectionViewCell", for: indexPath) as! IngrediantCollectionViewCell let obj = array[indexPath.row] print("obj=>\(obj)") var st = obj.name st += " ("+obj.value+" "+obj.unit+")" print("st=>\(st)") cell.name.text = st return cell } else if indexPath.section == 3{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DecThingsCollectionViewCell", for: indexPath) as! DecThingsCollectionViewCell cell.name.text = data.food_pairing![indexPath.row] print("food paring=>\(data.food_pairing![indexPath.row])") return cell } else{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "brewTipCollectionViewCell", for: indexPath) as! brewTipCollectionViewCell cell.lbText.text = array1[indexPath.row].name cell.brewerText.text = array1[indexPath.row].value return cell } } } extension BeerViewController : UICollectionViewDelegate , UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 0 { return CGSize(width: self.view.frame.width, height: 200) } else if indexPath.section == 1{ return CGSize(width: self.view.frame.width, height: 250) } else if indexPath.section == 2{ return CGSize(width: self.view.frame.width, height: 30) } else{ return CGSize(width: self.view.frame.width, height: 30) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.section == 0{ let nav = self.storyboard?.instantiateViewController(withIdentifier: "PhotoViewController") as! UINavigationController let cv = nav.viewControllers[0] as! PhotoViewController cv.image = data.image_url ?? "icons8-champagne_bottle_filled" self.present(nav, animated: true, completion: nil) } } }
true
aa09a6a501b73c673b06543d03105c390b57664a
Swift
NovoselovSergey/GitHubTravel
/Travel/ManagerData.swift
UTF-8
7,506
2.625
3
[]
no_license
// // ManagerData.swift // Travel // // Created by Sergey Novoselov on 09.07.17. // Copyright © 2017 Sergey Novoselov. All rights reserved. // import Foundation import Alamofire import RealmSwift import SwiftyJSON private let _sharedManager = ManagerData() class ManagerData { //-------------------------------------------- // singltone class var sharedManager: ManagerData { return _sharedManager } //-------------------------------------------- //-------------------------------------------- private var _tickets: [Tickets] = [] var tickets: [Tickets] { var ticketsCopy: [Tickets]! concurrentQueue.sync { ticketsCopy = self._tickets } return ticketsCopy } //-------------------------------------------- // data from DB func getTicketsFromDB() { let realm = try! Realm() self._tickets = Array(realm.objects(Tickets.self)) } //-------------------------------------------- func loadJSON(_ cityFrom: String, _ cityWhere: String) { // let realm = try! Realm() let url = "http://api.travelpayouts.com/v2/prices/latest?origin=\(cityFrom)&currency=rub&destination=\(cityWhere)&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0&token=" Alamofire.request(url, method: .get).validate().responseJSON(queue: concurrentQueue) { response in print("1. startQuene \(Thread.current)") switch response.result { case .success(let value): let jsonTicket = JSON(value) // print("City: \(json["data"]["destination"].stringValue)") for (_, subJson) in jsonTicket["data"] { let ticket = Tickets() ticket.codeFrom = subJson["origin"].stringValue ticket.codeWhere = subJson["destination"].stringValue ticket.value = subJson["value"].intValue print(ticket) print("2. load \(Thread.current)") self.TicketWriteDB(data: ticket) // try! realm.write { // realm.add(ticket) // } } case .failure(let error): print(error) } } } func TicketWriteDB(data: Tickets) { let realm = try! Realm() // realm.beginWrite() try! realm.write { realm.add(data) } // try! realm.commitWrite() print("3. write \(Thread.current)") NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil) } func loadCountries() { // let realm = try! Realm() let url = "http://api.travelpayouts.com/data/countries.json" Alamofire.request(url, method: .get).validate().responseJSON(queue: concurrentQueue) { response in print("4. startQuene \(Thread.current)") switch response.result { case .success(let value): let jsonCountries = JSON(value) // print("JSON: \(jsonCountries)") concurrentQueue.async { for (_, subJson) in jsonCountries { let country = Countries() country.code = subJson["code"].stringValue country.name = subJson["name"].stringValue country.currency = subJson["currency"].stringValue country.nameRu = subJson["name_translations"]["ru"].stringValue print(country) print("5. load \(Thread.current)") self.countriesWriteDB(data: country) } // try! realm.write { // realm.add(country) // } } case .failure(let error): print(error) } } } func countriesWriteDB(data: Countries) { let realm = try! Realm() // realm.beginWrite() try! realm.write { realm.add(data) } // try! realm.commitWrite() print("6. write \(Thread.current)") // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "color"), object: nil) } func loadCities() { let url = "http://api.travelpayouts.com/data/cities.json" Alamofire.request(url, method: .get).validate().responseJSON { response in print("7. startQuene \(Thread.current)") switch response.result { case .success(let value): let jsonCities = JSON(value) // print("JSON: \(json)") concurrentQueue.async { for (_, subJson) in jsonCities { let city = Cities() city.code = subJson["code"].stringValue city.name = subJson["name"].stringValue city.time_zone = subJson["time_zone"].stringValue city.nameRu = subJson["name_translations"]["ru"].stringValue city.country_code = subJson["country_code"].stringValue print(city) print("8. load \(Thread.current)") self.citiesWriteDB(data: city) // try! realm.write { // realm.add(country) // } } } case .failure(let error): print(error) } } } func citiesWriteDB(data: Cities) { let realm = try! Realm() // realm.beginWrite() try! realm.write { realm.add(data) } // try! realm.commitWrite() print("9. write \(Thread.current)") } func loadAirports() { let url = "http://api.travelpayouts.com/data/airports.json" Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) print("JSON: \(json)") case .failure(let error): print(error) } } } } var semaphore = DispatchSemaphore(value: 0) // создаем семафор let playGrp = DispatchGroup() // создаем группу //let queue = DispatchQueue(label: "com.dispatchgroup", attributes: .initiallyInactive, target: .main) var item: DispatchWorkItem? // создаем блок // создание параллельной очереди let concurrentQueue = DispatchQueue(label: "concurrent_queue", attributes: .concurrent) // создание последовательной очереди let serialQueue = DispatchQueue(label: "serial_queue")
true
192c50c8c241efe89c08cd8bc55176c9ddc3cb97
Swift
dmaulikr/RecipeBuilder
/RecipeBuilder/ContainerViewController.swift
UTF-8
3,005
2.609375
3
[]
no_license
// // ContainerViewController.swift // RecipeBuilder // // Created by Anjani Bhargava on 3/6/16. // Copyright © 2016 Cheeeese. All rights reserved. // import UIKit class ContainerViewController: UIViewController { //outlets @IBOutlet weak var contentView: UIView! @IBOutlet var buttons: [UIButton]! //variables var selectedIndex: Int = 0 var myRecipesViewController: UIViewController! var shoppingListViewController: UIViewController! var timersViewController: UIViewController! var viewControllers: [UIViewController]! override func viewDidLoad() { super.viewDidLoad() // create storyboard and VCs let storyboard = UIStoryboard(name: "Main", bundle: nil) myRecipesViewController = storyboard.instantiateViewControllerWithIdentifier("MyRecipesViewController") shoppingListViewController = storyboard.instantiateViewControllerWithIdentifier("ShoppingListViewController") timersViewController = storyboard.instantiateViewControllerWithIdentifier("TimersViewController") // create array of VCs viewControllers = [myRecipesViewController, shoppingListViewController, timersViewController] // make default view the My Recipes VC didTapNavItem(buttons[selectedIndex]) buttons[selectedIndex].selected = true } //function to change contentView based on button selected @IBAction func didTapNavItem(sender: UIButton) { let previousIndex = selectedIndex selectedIndex = sender.tag let previousVC = viewControllers[previousIndex] // set button to selected state (we'll need this when we have visual design done) if previousIndex == selectedIndex { } else { buttons[selectedIndex].selected = true buttons[previousIndex].selected = false } // remove previous view controller previousVC.willMoveToParentViewController(nil) previousVC.view.removeFromSuperview() previousVC.removeFromParentViewController() let vc = viewControllers[selectedIndex] //calls view will appear addChildViewController(vc) //set view size vc.view.frame = contentView.bounds //add vc contentView.addSubview(vc.view) //calls view did appear vc.didMoveToParentViewController(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
4a877feafb7433d4079c23d397b0803d506b2172
Swift
mariaaeugenia/TesteiOSv2
/SantanderTest/SantanderTest/Scenes/Detail/AccountDetailInteractor.swift
UTF-8
3,586
2.640625
3
[]
no_license
// // AccountDetailInteractor.swift // SantanderTest // // Created by Maria Eugênia Pereira Teixeira on 26/07/20. // Copyright (c) 2020 Maria Eugênia Pereira Teixeira. All rights reserved. // import UIKit protocol AccountDetailBusinessLogic { func retrieveStaments() var height: CGFloat { get } func numberOfRows(in section: Int) -> Int func header(tableView: UITableView, section: Int) -> UIView func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell } protocol AccountDetailDataStore { var user: UserAccount? { get set } } class AccountDetailInteractor: AccountDetailBusinessLogic,AccountDetailDataStore { var user: UserAccount? var presenter: AccountDetailPresentationLogic? var worker: AccountDetailNetworkLogic var statments: [StatementList] var height: CGFloat { return 96.0 } init(with worker: AccountDetailNetworkLogic = AccountDetailWorker()) { self.worker = worker statments = [] } func retrieveStaments() { worker.retrieveStatments(for: 1).done(handleSuccess).catch(handleError).finally { [weak self] in self?.presenter?.shouldPresentLoading(false) } } //MARK: - //MARK: - HANDLE SUCCESS func handleSuccess(response: AccountDetail.Response) { presenter?.shouldPresentLoading(false) if let error = response.error?.message { presenter?.onError(title: Strings.Error.alertTitle, message: error) } else { statments = response.statementList ?? [] presenter?.presentData() } } //MARK: - //MARK: - HANDLE ERROR func handleError(error: Error) { presenter?.onError(title: Strings.Error.alertTitle, message: error.localizedDescription) } func numberOfRows(in section: Int) -> Int { if section == 1 { return statments.count } return 0 } func configureHeaderViewModel(at section: Int) -> AccountDetail.TableViewModel.Section? { if section == 0 { let vm = AccountDetail.TableViewModel.Section(user: user) return vm } return nil } func header(tableView: UITableView, section: Int) -> UIView { if section == 1 { let rect = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 80) let sectionView = StatmentSectionView(frame: rect) sectionView.set(text: Strings.Statment.Section.sectionTitle) return sectionView } let rect = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 230) let headerView = StatmentHeaderView(frame: rect) if let vm = configureHeaderViewModel(at: 0) { headerView.set(vm: vm, handler: logout) } return headerView } func configureViewModel(at indexPath: IndexPath) -> AccountDetail.TableViewModel.Cell? { if indexPath.section == 1 { let statment = statments[indexPath.row] let vm = AccountDetail.TableViewModel.Cell(statment: statment) return vm } return nil } func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(StatementCell.self) if let vm = configureViewModel(at: indexPath) { cell.set(vm: vm) } return cell } return UITableViewCell() } func logout() { presenter?.performLogout() } }
true
671e6d8aee99229ccdbb3705720252b75055eca3
Swift
harry-91/AppStoreOffsiteTest
/AppStoreOffsiteTest/Listing/View/RateDisplayView.swift
UTF-8
5,614
2.859375
3
[]
no_license
// // RateDisplayView.swift // AppStoreOffsiteTest // // Created by HarryPan on 09/09/2017. // Copyright © 2017 HarryPan. All rights reserved. // import Foundation import UIKit class RateDisplayView: UIView { var currentRating: CGFloat = 0 { didSet { setNeedsLayout() layoutIfNeeded() } } fileprivate var padding: CGFloat { return self.bounds.width / 50 } fileprivate lazy var starsView: UIView = { let starsView = UIView(frame: self.bounds) starsView.autoresizingMask = [.flexibleWidth, .flexibleHeight] starsView.backgroundColor = .white self.addSubview(starsView) return starsView }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.red } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.red } override func draw(_ rect: CGRect) { starsView.layer.sublayers?.forEach { $0.removeFromSuperlayer() } let width = (rect.width - 4 * padding) / 5 let height = rect.height > width ? width : rect.height var layers = [CALayer]() for index in 0..<5 { let starRect = CGRect(x: CGFloat(index) * (width + padding), y: (rect.height - height) / 2, width: width, height: height) let filledPercentage = starFilledPercentage(withIndex: index) var starLayer: CALayer! if filledPercentage >= 1 { starLayer = self.starLayer(in: starRect, isFilled: true) } else if filledPercentage <= 0 { starLayer = self.starLayer(in: starRect, isFilled: false) } else { let filledStarLayer = self.starLayer(in: starRect, isFilled: true) let emptyStarLayer = self.starLayer(in: starRect, isFilled: false) let partialStarLayer = CALayer() partialStarLayer.addSublayer(emptyStarLayer) partialStarLayer.addSublayer(filledStarLayer) let newWidth = filledStarLayer.bounds.size.width * CGFloat(filledPercentage) let offset = (filledStarLayer.bounds.size.width - newWidth) / 2 filledStarLayer.bounds.size.width = newWidth filledStarLayer.frame.origin.x -= offset starLayer = partialStarLayer } layers.append(starLayer) } starsView.layer.sublayers = layers } fileprivate func starLayer(in rect: CGRect, isFilled: Bool) -> CALayer { let starLayer = CAShapeLayer() starLayer.frame = rect starLayer.fillColor = isFilled ? UIColor.orange.cgColor : UIColor.clear.cgColor starLayer.strokeColor = UIColor.orange.cgColor starLayer.masksToBounds = true starLayer.isOpaque = true let starPath = drawStarBezier(withOrigin: CGPoint(x: rect.width / 2, y: rect.height / 2), radius: rect.width / 4, pointyness: 2) starLayer.path = starPath.cgPath return starLayer } fileprivate func starFilledPercentage(withIndex index: Int) -> Float { return Float(currentRating - CGFloat(index + 1)) } // MARK: - Draw Polygon fileprivate func degree2radian(_ degree: CGFloat) -> CGFloat { return .pi * degree / 180 } fileprivate func polygonPoints(withSides sides: Int, origin: CGPoint, radius: CGFloat, adjustment: CGFloat = 0) -> [CGPoint] { let angle = degree2radian(360 / CGFloat(sides)) var points = [CGPoint]() var index = sides while points.count <= sides { points.append(CGPoint(x: origin.x - radius * cos(angle * CGFloat(index) + degree2radian(adjustment)), y: origin.y - radius * sin(angle * CGFloat(index) + degree2radian(adjustment)))) index = index - 1 } return points } // MARK: - Draw Star fileprivate func starPath(withOrigin origin: CGPoint, radius: CGFloat, pointyness: CGFloat, startAngle: CGFloat = 0) -> CGPath { let adjustment = startAngle + CGFloat(360 / 5 / 2) let path = CGMutablePath() let polygonPoints = self.polygonPoints(withSides: 5, origin: origin, radius: radius, adjustment: startAngle) let biggerPolygonPoints = self.polygonPoints(withSides: 5, origin: origin, radius: radius * pointyness, adjustment: adjustment) path.move(to: CGPoint(x:polygonPoints[0].x, y:polygonPoints[0].y)) for index in 0..<polygonPoints.count { path.addLine(to: CGPoint(x:biggerPolygonPoints[index].x, y:biggerPolygonPoints[index].y)) path.addLine(to: CGPoint(x:polygonPoints[index].x, y:polygonPoints[index].y)) } path.closeSubpath() return path } fileprivate func drawStarBezier(withOrigin origin: CGPoint, radius: CGFloat, pointyness: CGFloat) -> UIBezierPath { let startAngle = CGFloat(-1 * (360 / 5 / 4)) return UIBezierPath(cgPath: starPath(withOrigin: origin, radius: radius, pointyness: pointyness, startAngle: startAngle)) } }
true
97f9cc9d985fb669b98ebdbdc2b6c3ee5dd4b48f
Swift
Kylta/feed-essential
/EssentialFeed/EssentialFeed/Feed Cache/Infrastructure/CoreData/ManagedFeedImage.swift
UTF-8
1,052
2.796875
3
[]
no_license
// // ManagedFeedImage.swift // EssentialFeed // // Created by Christophe Bugnon on 13/09/2019. // Copyright © 2019 Christophe Bugnon. All rights reserved. // import CoreData @objc(ManagedFeedImage) class ManagedFeedImage: NSManagedObject { @NSManaged var id: UUID @NSManaged var imageDescription: String? @NSManaged var location: String? @NSManaged var url: URL @NSManaged var cache: ManagedCache } extension ManagedFeedImage { static func images(from localFeed: [LocalFeedImage], in context: NSManagedObjectContext) -> NSOrderedSet { return NSOrderedSet(array: localFeed.map { local in let managedFeed = ManagedFeedImage(context: context) managedFeed.id = local.id managedFeed.imageDescription = local.description managedFeed.location = local.location managedFeed.url = local.url return managedFeed }) } var local: LocalFeedImage { return LocalFeedImage(id: id, description: imageDescription, location: location, url: url) } }
true
70d4d255cf1882fb5299b5544df5c801c227855b
Swift
stv-ekushida/ios-simple-chat-demo
/ios-simple-chat-demo/Models/Message.swift
UTF-8
478
2.609375
3
[]
no_license
// // Message.swift // ios-simple-chat-demo // // Created by Eiji Kushida on 2017/06/20. // Copyright © 2017年 Eiji Kushida. All rights reserved. // import Foundation import RealmSwift final class Message: Object { dynamic var messageID = 0 dynamic var message = "" dynamic var updated = Date().now() var postData: String { return updated.dateStyleHHMM() } override static func primaryKey() -> String? { return "messageID" } }
true
d883467686f68c6a1ac63e252d73e97c237e8134
Swift
OlegKol/HappyChildV2
/Celeverl/Network/Operations/Settings/UploadSettings/HCNetworkCameraSettingsUploadModel.swift
UTF-8
1,300
2.53125
3
[]
no_license
// // HCNetworkCameraSettingsUploadModel.swift // HappyChild (mobile) // // Created by Anna on 19.12.2019. // Copyright © 2019 oberon. All rights reserved. // import UIKit class HCNetworkCameraSettingsUploadModel { var userId = "" var type: Int? var startHour: Int? var endHour: Int? var selectedDays: [Int]? var dateStart: String? var dateEnd: String? } extension HCNetworkCameraSettingsUploadModel: HCNetworkBaseRequestModel { var requestParameters: [String : Any] { var params = [String : Any]() params["userId"] = userId params["Type"] = type ?? 0 params["StartHour"] = startHour ?? 0 params["EndHour"] = endHour ?? 24 let stringArray = selectedDays?.map { String($0) } let string = stringArray?.joined(separator: ", ") ?? "null" params["SelectedDays"] = string params["DateStart"] = dateStart != nil ? "\(dateStart!)" : nil params["DateEnd"] = dateEnd != nil ? "\(dateEnd!)" : nil return params } var requestPath: String { return kNetworkUploadCameraSettings } var requestMethod: HCHttpMethod { return .POST } var shouldSendParametrsInBody: Bool { return true } }
true
917a0940c419b6ecfc714f8e87ae9ad156383d2b
Swift
ZhuPeng1314/SelectableButtonDemo
/ZPSelectableButton.swift
UTF-8
1,478
3.375
3
[]
no_license
// // ZPSelectableButton.swift // SelectableButtonDemo // // Created by 鹏 朱 on 15/12/22. // Copyright © 2015年 鹏 朱. All rights reserved. // import UIKit class ZPSelectableButton: UIButton { //真实的选中状态 private var selectedTruely1 = false var selectedTruely:Bool { //selectedTruely暴露给外部,当调用者直接修改该属性时会同时修改UIControl中的selected get { return selectedTruely1 } set (newSelected) { self.selectedTruely1 = newSelected self.selected = newSelected //同时改变UIControl中的selected状态为目标状态 } } // UIControl中的selected只是为了表示当前UI是否应该处于selected UI override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { //让highlight UI能被显示出来,因为selected=true的优先级比highlight=true更高 self.selected = false super.touchesBegan(touches, withEvent: event) } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { self.selected = self.selectedTruely super.touchesCancelled(touches, withEvent: event) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.selectedTruely = !self.selectedTruely //改变真实的选中状态 super.touchesEnded(touches, withEvent: event) } }
true
082c6a0512740121e85d1c79691ba92c50bd594e
Swift
vinaya-krishna/Course-Registration
/assignment_5/Model/Classes.swift
UTF-8
1,399
2.671875
3
[]
no_license
// // Classes.swift // assignment_5 // // Created by vinaya krishna on 11/11/18. // Copyright © 2018 vinaya krishna. All rights reserved. // import Foundation struct Classes:Codable { let id:Int let title:String let fullTitle:String? let instructor:String? let startTime:String? let endTime:String? let dept:String? let subject:String? let courseNo:String? let building:String? let roomNo:String? let days:String? let scheduleNo:String? let description:String? let seats:Int? let enrolled:Int? init(json:[String:Any]) { self.id = json["id"] as! Int self.title = json["title"] as! String self.instructor = json["instructor"] as? String self.startTime = json["startTime"] as? String self.endTime = json["startTime"] as? String self.dept = json["department"] as? String self.subject = json["subject"] as? String self.courseNo = json["course#"] as? String self.building = json["building"] as? String self.roomNo = json["room"] as? String self.days = json["days"] as? String self.fullTitle = json["fullTitle"] as? String self.scheduleNo = json["schedule#"] as? String self.description = json["description"] as? String self.seats = json["seats"] as? Int self.enrolled = json["enrolled"] as? Int } }
true
0ed8f7b1524be0a7aeab87802769c89d6bf4a5bd
Swift
kevinleewy/ChessAR
/iOS/MyProject/Views/OverlayScene.swift
UTF-8
1,312
2.890625
3
[]
no_license
// // OverlayScene.swift // MyProject // // Created by Kevin Lee on 4/13/18. // Copyright © 2018 Kevin Lee. All rights reserved. // import UIKit import SpriteKit class OverlayScene: SKScene { var announcementNode: SKLabelNode! var announcement = "" { didSet { self.announcementNode.text = self.announcement self.announcementNode.run(SKAction.sequence([ SKAction.fadeIn(withDuration: 0.5), SKAction.wait(forDuration: ANNOUNCEMENT_DURATION), SKAction.fadeOut(withDuration: 0.5) ])) } } // MARK: Constants let ANNOUNCEMENT_DURATION = 2.0 //2 seconds override init(size: CGSize) { super.init(size: size) self.backgroundColor = UIColor.clear self.announcementNode = SKLabelNode(text: ":)") self.announcementNode.fontName = "DINAlternate-Bold" self.announcementNode.fontColor = UIColor.white self.announcementNode.fontSize = 24 self.announcementNode.position = CGPoint(x: size.width/2, y: size.height/2 ) self.announcementNode.alpha = 0.0 self.addChild(self.announcementNode) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
true
d1eb2033c4e44a7ca51fe0a1a553c2bdf7387e00
Swift
soracom/soracom-sdk-swift
/Sources/SoracomAPI/AutoGeneratedCode/Requests/Billing/GetBillingPerDay.swift
UTF-8
892
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Request where T == DailyBillResponse { /** Get bill per day. Returns detailed information of billing amounts per day for the specified month. This API only returns the billing amounts that have been finalized. [API Documentation](https://dev.soracom.io/en/docs/api/#!/Billing/getBillingPerDay) */ public class func getBillingPerDay( yyyyMM: String, responseHandler: ResponseHandler<DailyBillResponse>? = nil ) -> Request<DailyBillResponse> { let path = "/bills/\(yyyyMM)/daily" let requestObject = Request<DailyBillResponse>.init(path, responseHandler: responseHandler) requestObject.expectedHTTPStatus = 200 requestObject.method = .get return requestObject } }
true
68a6c237572c6f57a5a9c086eee7d69e5b7f6641
Swift
Aries-Sciences-LLC/Dr.-Foodie
/Dr. Foodie/ViewControllers/SecondaryVCs/NutritionConsumedTodayVC.swift
UTF-8
1,191
2.515625
3
[ "MIT" ]
permissive
// // NutritionConsumedTodayVC.swift // Dr. Foodie // // Created by Ozan Mirza on 11/29/20. // Copyright © 2020 Aries Sciences LLC. All rights reserved. // import UIKit // MARK: IBOutlets & IBActions class NutritionConsumedTodayVC: DRFVC { @IBOutlet weak var dataContainer: NutritionFacts! @IBOutlet weak var moveLeft: UIButton! @IBOutlet weak var moveRight: UIButton! @IBAction func swipedLeft(_ sender: Any) { _ = dataContainer.update(with: .left) } @IBAction func swipedRight(_ sender: Any) { _ = dataContainer.update(with: .right) } @IBAction func movedLeft(_ sender: Any) { pop() swipedLeft(sender) } @IBAction func movedRight(_ sender: Any) { pop() swipedRight(sender) } } // MARK: Methods extension NutritionConsumedTodayVC: DataHandlerVC { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func dataIsIn() { DispatchQueue.main.async { self.dataContainer.set(suggestions: UserNutrition.information(for: .today)) } } }
true
0a4db8b17ab91b85481102c012c88b4034a4afef
Swift
itzderr/iOSAppStore
/AppStore/Search/Views/SearchTrendingTableViewCell.swift
UTF-8
1,141
2.625
3
[]
no_license
// // TrendingTableViewCell.swift // AppStore // // Created by Derrick Park on 2019-05-01. // Copyright © 2019 Derrick Park. All rights reserved. // import UIKit class SearchTrendingTableViewCell: UITableViewCell { // MARK: - Properties let nameLabel: UILabel = { let lb = UILabel(text: "", font: .systemFont(ofSize: 20), textColor: .systemBlue) // default height: 44 lb.constraintHeight(equalToConstant: 44) return lb }() // MARK: - Helper methods func setupStaticCell() { nameLabel.text = "Trending" nameLabel.textColor = .black nameLabel.font = .boldSystemFont(ofSize: 22) } // MARK: - Initializer override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.matchParent(padding: .init(top: 0, left: 16, bottom: 0, right: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(false, animated: animated) } }
true
51a976a880ca391a32bd7ffc457e093ff244f030
Swift
lyg830/Foodie
/Foodie/Search/SearchViewController+CollectionView.swift
UTF-8
4,810
2.59375
3
[]
no_license
// // SearchViewController+CollectionView.swift // Foodie // // Created by Justin Li on 2017-08-17. // Copyright © 2017 Justin Li. All rights reserved. // import UIKit import Kingfisher extension SearchViewController: UICollectionViewDataSource { var sectionInsets: UIEdgeInsets { get { if self.splitViewController?.isCollapsed ?? true { return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) } else { return UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30) } } } var minimumLineSpacing: CGFloat { get { if self.splitViewController?.isCollapsed ?? true { return 15.0 } else { return 20.0 } } } var minimumInteritemSpacing: CGFloat { get { if self.splitViewController?.isCollapsed ?? true { return 15.0 } else { return 20.0 } } } var collectionCellAspectRatio: CGFloat { get { return 1/1.3 } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.businesses.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "businessCollectionCell", for: indexPath) as! BusinessSearchCollectionViewCell if self.businesses.count > indexPath.row { let business = self.businesses[indexPath.row] cell.nameLabel.text = business.name if let location = business.location { let addrArr:[String] = [location.city, location.state, location.country].flatMap{$0} let addr = addrArr.joined(separator: ", ") cell.addrLabel.text = addr } cell.imgView.kf.setImage(with: URL(string: business.imageUrl ?? ""), options: [KingfisherOptionsInfoItem.cacheMemoryOnly, KingfisherOptionsInfoItem.transition(ImageTransition.fade(0.2))]) } return cell } } extension SearchViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var width: CGFloat if self.splitViewController?.isCollapsed ?? true { width = (self.collectionView.frame.width - (sectionInsets.left + sectionInsets.right) - minimumInteritemSpacing)/2.0 } else { width = 200.0 } return CGSize(width: width, height: width/self.collectionCellAspectRatio) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return self.sectionInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return self.minimumLineSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return self.minimumInteritemSpacing } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) guard let detailVC = StoryboardProvider.viewController(from: "BusinessDetail", classType: BusinessDetailViewController.self) as? BusinessDetailViewController, self.businesses.count > indexPath.row else { return } detailVC.business = self.businesses[indexPath.row] self.show(detailVC, sender: self) } } extension SearchViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { let urls = indexPaths.flatMap({ (indexPath) -> URL? in guard self.businesses.count > indexPath.row else { return nil } return URL(string: self.businesses[indexPath.row].imageUrl ?? "") }) let prefetcher = ImagePrefetcher(urls: urls, options: [KingfisherOptionsInfoItem.cacheMemoryOnly]) prefetcher.start() } }
true
8d7a25294d291522dc9f47cc24a79862edd885dd
Swift
akio0911/til
/20201217/20201217.playground/Pages/tryFilter.xcplaygroundpage/Contents.swift
UTF-8
533
3.46875
3
[ "MIT" ]
permissive
//: [Previous](@previous) import Foundation import Combine // tryFilter(_:) | Apple Developer Documentation // https://developer.apple.com/documentation/combine/publisher/tryfilter(_:) struct DivisionByZeroError: Error {} let numbers: [Int] = [1,2,3,4,0,5] let cancellable = numbers.publisher .tryFilter({ if $0 == 0 { throw DivisionByZeroError() } else { return $0 % 2 == 0 } }) .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) }) //: [Next](@next)
true
ba361712a9c8fe8afae4e48c1974d45866cb8979
Swift
pavlobondar/News-feed
/NewsApp/ServiceLayer/Manager/NetworkManager.swift
UTF-8
1,917
2.8125
3
[]
no_license
// // NetworkManager.swift // NewsApp // // Created by Pavel Bondar on 10.06.2020. // Copyright © 2020 Pavel Bondar. All rights reserved. // import Foundation fileprivate func handleNetworkResponse(_ response: HTTPURLResponse) -> APIError { switch response.statusCode { case 200...299: return .success case 401...500: return .authenticationError case 501...599: return .badReguest case 600: return .outdated default: return .failed } } protocol NetworkServiceProtocol { func dataLoader<T: Decodable>(to endPoint: NewsApi, then handler: @escaping (Swift.Result<T, APIError>) -> Void) } struct NetworkManager: NetworkServiceProtocol { static let environment: NetworkEnvironment = .newsAPI static let newsAPIKey = "84a521a08cf141aa8bbe269df5f99439" private let router = NetworkRouter<NewsApi>() func dataLoader<T: Decodable>(to endPoint: NewsApi, then handler: @escaping (Swift.Result<T, APIError>) -> Void) { router.request(endPoint) { (data, response, error) in DispatchQueue.main.async { guard let httpResponse = response as? HTTPURLResponse else { handler(.failure(.badReguest)) return } let result = handleNetworkResponse(httpResponse) switch result { case .success: if let data = data { do { let objects = try JSONDecoder().decode(T.self, from: data) handler(.success(objects)) } catch { handler(.failure(.unableToDecode)) } } else { handler(.failure(.noData)) } default: handler(.failure(result)) } } } } }
true
f7832b6328bc55c9ef68291f0c1725b3fb867c5f
Swift
franklynw/SwiftyCoreAnimation
/CoreAnimation/Layer Properties/CAEmitterLayer/Unanimatable/EmitterCells.swift
UTF-8
802
3.078125
3
[ "MIT" ]
permissive
// // EmitterCells.swift // CoreAnimation // // Created by Franklyn on 08/03/2019. // Copyright © 2019 Franklyn. All rights reserved. // import UIKit /** Wrapper for the CAEmitterLayer's emitterCells property Use with SwiftyCoreAnimation's set/get functions - KeyValueType: [CAEmitterCell] ## Usage Examples ## ```` myLayer.set(EmitterCells([myEmitterCells])) let emitterCells = myLayer.get(EmitterCells.self) ```` Conforms to - - Settable - KeyValueProviding - EmitterLayerProperty */ public struct EmitterCells: EmitterLayerPropertyConformance { public typealias KeyValueType = [CAEmitterCell] public let value: KeyValueType? public static var keyPath: String { return "emitterCells" } public init(_ value: KeyValueType?) { self.value = value } }
true
790164695eada700c6173690a1f87e3a07afe6c4
Swift
liya328/CSSwiftExtension
/CSSwiftExtensionTests/String+CSExtensionTests.swift
UTF-8
713
2.671875
3
[ "MIT" ]
permissive
// // String+CSExtensionTests.swift // CSSwiftExtension // // Created by Chris Hu on 16/6/20. // Copyright © 2016年 icetime17. All rights reserved. // import XCTest class String_ExtensionTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func test_cs_trim() { var s = " hi, \n hello world ".cs_trim() print(s) s = "hello world\n".cs_trim() print(s) } func test_cs_intValue() { print("abc123".cs_intValue()!) print("abc123".cs_stringValue()!) } func testPerformanceExample() { self.measureBlock { } } }
true
f9e9739da494020d9dc9417cb4ebfdd48bc19462
Swift
IgorSkripnik/Test_LightIT
/Test/Presentation/DetailProduct/DetailPresenter.swift
UTF-8
2,474
2.6875
3
[]
no_license
// // DetailPresenter.swift // Test // // Created by Igor Skripnik on 8/31/19. // Copyright © 2019 IS. All rights reserved. // import Foundation protocol DetailPresenterProtocol: class { // func post(_ review: String, with rate: String) func addReviewTapped() func getReviewList(by id: String) func configure(_ cell: ReviewCell, by index: Int) func send(_ review: String, rate: Int) var reviews: ReviewList? { get } var product: Product? { get } } class DetailPresenter: DetailPresenterProtocol { weak private var view: DetailViewProtocol? let networkClient: ProductClient var product: Product? var reviews: ReviewList? { didSet { view?.updateView() } } init(_ interface: DetailViewProtocol, reviewList: ReviewList, prod: Product) { view = interface product = prod networkClient = ProductClient() reviews = reviewList } private func post(_ review: String, with rate: String) { } private func show() { DispatchQueue.main.async { let controller: ControllerType = .reviewViewController if let view = controller.instantiateViewController() as? ReviewViewController { view.presenter = self self.view?.show(view) } } } func send(_ review: String, rate: Int) { guard let prodId = product?.id else { return } let endpoint = ProductEndpoint.review(rate: rate, review: review, prodId: String(prodId)) networkClient.enterData(endpoint: endpoint) {[weak self] _ in self?.getReviewList(by: String(prodId)) } } func getReviewList(by id: String) { let endpoint = ProductEndpoint.reviews(productId: String(id)) networkClient.reviews(endpoint: endpoint) {[weak self] either in guard let self = self else { return } switch either { case .success(let reviews): self.reviews = reviews case .error(let error): print(error) } } } func addReviewTapped() { show() } func configure(_ cell: ReviewCell, by index: Int) { guard let review = reviews?[index] else { return } cell.reitingView.rating = Double(review.rate ?? 0) cell.nameLbl.text = review.created_by?.username cell.reviewLbl.text = review.text } }
true
b54e680ed83a3c86c88788f805d36b316432353a
Swift
zjyhll/SwiftUIViewsMasteryDemo
/SwiftUIViewsMasteryDemo/SwiftUIViewsMasteryDemo/Stepper/StepperIntroudction.swift
UTF-8
1,971
3.609375
4
[ "MIT" ]
permissive
// // StepperIntroudction.swift // TestPadding // // Created by RecherJ on 2021/7/13. // import SwiftUI struct StepperIntroudction: View { @State private var stepperValue = 1 @State private var values = [0, 1] var body: some View { VStack(spacing: 20) { Text("Stepper") .font(.largeTitle) Text("Introudction") .font(.title) .foregroundColor(.gray) Text("The Stepper can be bound to a variable like this:") .frame(maxWidth: .infinity) .padding() .background(Color.blue) .foregroundColor(.white) Stepper(value: $stepperValue) { Text("Bound Stepper: \(stepperValue)") } .padding(.horizontal) Divider() Image(systemName: "bolt.fill") .font(.title) .foregroundColor(.yellow) Text("Or you can run code on the increment and decrement events:") .frame(maxWidth: .infinity) .padding() .background(Color.blue) .foregroundColor(Color.white) .font(.title) Stepper( onIncrement: { values.append(values.count) }, onDecrement: { values.removeLast() }, label: { Text("onIncrement and onDecrement") }) .padding(.horizontal) HStack { ForEach(values, id: \.self) { value in Image(systemName: "\(value).circle.fill") } } .font(.title) .foregroundColor(.green) } .font(.title) } } struct StepperIntroudction_Previews: PreviewProvider { static var previews: some View { StepperIntroudction() } }
true
e41c4df39d9b55c6e0618cb49b3d3070756b6d44
Swift
rvoulon/MemeMe
/MemeMe/Meme.swift
UTF-8
554
2.625
3
[]
no_license
// // Meme.swift // MemeMe // // Created by Roberta Voulon on 2015-12-09. // Copyright © 2015 Roberta Voulon. All rights reserved. // import Foundation import UIKit struct Meme { var upperText: String? var bottomText: String? var sourceImage: UIImage? var memedImage: UIImage! // init(upperText: String, bottomText: String, sourceImage: UIImage, memedImage: UIImage) { // self.upperText = upperText // self.bottomText = bottomText // self.sourceImage = sourceImage // self.memedImage = memedImage // } }
true
7b7e407c45195b5edc062cc50cf68116dca76f75
Swift
betty-pan/DrinksOrderApp
/DrinksOrderApp/Model/Menu.swift
UTF-8
836
2.84375
3
[]
no_license
// // Menu.swift // DrinksOrderApp // // Created by Betty Pan on 2021/4/24. // import Foundation struct Menu:Codable { let feed:Feed } struct Feed:Codable { let entry: [DrinkData] } struct DrinkData:Codable { let drink:StringType let priceM:StringType let priceL:StringType let description:StringType let imageUrl:ImageURL enum CodingKeys: String, CodingKey { case drink = "gsx$drinks" case priceM = "gsx$pricem" case priceL = "gsx$pricel" case description = "gsx$description" case imageUrl = "gsx$imageurl" } } struct ImageURL:Codable { let url:URL enum CodingKeys: String, CodingKey { case url = "$t" } } struct StringType:Codable { let value:String enum CodingKeys: String, CodingKey { case value = "$t" } }
true
6ad3cbc321474c9214a666cc449d79e28a4d0828
Swift
djalfirevic/SwiftUI-Playground
/Big Mountain Studio/SwiftUI Data/SwiftUI_Data/EnvironmentObject/EnvironmentObject_Intro.swift
UTF-8
2,123
3.734375
4
[]
no_license
// Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio import SwiftUI // You're using a class that conforms to ObservableObject so you can bind to properties within it class NameInfo: ObservableObject { @Published var name: String = "" } struct EnvironmentObject_Intro: View { var body: some View { TabView { TabViewOne() .tabItem { Image(systemName: "1.circle") Text("One") } TabViewTwo() .tabItem { Image(systemName: "2.circle") Text("Two") } } .environmentObject(NameInfo()) // The environment object is added to the PARENT view .font(.title) } } struct TabViewOne: View { @EnvironmentObject var nameInfo: NameInfo var body: some View { VStack { Text("Tab 1") .font(.largeTitle) HeaderView("@EnvironmentObject", subtitle: "Introduction", desc: "Use the environmentObject modifier to add ObservableObjects to parent views.", back: .purple, textColor: .white) Spacer() TextField("Add a name", text: $nameInfo.name) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding(.horizontal) Spacer() } } } struct TabViewTwo: View { @EnvironmentObject var nameData: NameInfo var body: some View { VStack { Text("Tab 2") .font(.largeTitle) HeaderView("@EnvironmentObject", subtitle: "Introduction", desc: "This view can access the environment object by using the @EnvironmentObject property wrapper.", back: .purple, textColor: .white) Spacer() Text("The name you entered on Tab 1 was:") .padding() Text("\(nameData.name)") .bold() Spacer() } } } struct EnvironmentObject_Intro_Previews: PreviewProvider { static var previews: some View { EnvironmentObject_Intro() } }
true
27c275c64058c1b804c72cf844c3228b75f736e2
Swift
VesperHan/VSWeiBo
/VSWeiboCircle/VSWeiboCircle/Classes/Main/OAuth/UserAccountViewModel.swift
UTF-8
1,093
2.625
3
[]
no_license
// // UserAccountTool.swift // VSWeiboCircle // // Created by Vesperlynd on 2016/12/9. // Copyright © 2016年 Vesperlynd. All rights reserved. // import UIKit class UserAccountViewModel { static let shareIntance = UserAccountViewModel() var userAccount : UserAccount? //计算属性 var accountPath:String{ //读取路径 let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return (accountPath as NSString).appendingPathComponent("account.plist") } var isLogin :Bool{ if userAccount == nil { return false } guard let expiresDate = userAccount?.expires_date else { return false } return expiresDate.compare(Date()) == ComparisonResult.orderedDescending } //重写init方法 创建对象即可读取init方法 init() { //读取信息 userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? UserAccount } }
true
60873823d045738e0afe4734df821199182e4100
Swift
deblinaalways/special-octo-engine
/Kuliza/Cells/PortfolioTableViewCell.swift
UTF-8
640
2.625
3
[]
no_license
// // PortfolioTableViewCell.swift // Kuliza // // Created by Deblina Das on 04/01/18. // Copyright © 2018 Deblinas. All rights reserved. // import UIKit class PortfolioTableViewCell: UITableViewCell { @IBOutlet var headerLabel: UILabel! @IBOutlet var rightContentLabel: UILabel! @IBOutlet var leftContentLabel: UILabel! func configure(data: PortfolioData) { headerLabel.text = data.header rightContentLabel.text = data.rightContent leftContentLabel.text = data.leftContent } } struct PortfolioData { var header: String! var leftContent: String! var rightContent: String! }
true
9e41bc9e6904cca11545d6b5c35365e73983059c
Swift
ducban1108/PickerViewDemo
/PickerViewDemo/ViewController.swift
UTF-8
931
2.78125
3
[]
no_license
// // ViewController.swift // PickerViewDemo // // Created by Just Kidding on 4/14/19. // Copyright © 2019 Just Kidding. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { let ages : [Int] = [18,19,20,21,22] @IBOutlet weak var pickerView: UIPickerView! override func viewDidLoad() { super.viewDidLoad() pickerView.delegate = self pickerView.dataSource = self pickerView.selectRow(2, inComponent: 0, animated: true) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return ages.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(ages[row]) } }
true
714af678905ac6694a97e9a1436fe8b212cfb0e4
Swift
bibekdari/testSample
/SampleTestProj/LocationManager.swift
UTF-8
3,085
2.859375
3
[]
no_license
// // LocationManager.swift // SampleTestProj // // Created by bibek timalsina on 1/7/17. // Copyright © 2017 bibek. All rights reserved. // import Foundation import CoreLocation protocol LocationManagerDelegate { var thresholdDistance: Double {get} } class LocationManager: NSObject { struct Constants { let locationUpdated = "LocationMangerLocationUpdated" let locationThresholdDistanceMet = "LocationManagerThresholdDistanceMet" } static let shared: LocationManager = LocationManager() let geoCoder = CLGeocoder() var delegate: LocationManagerDelegate? var currentLocation: CLLocation? { didSet { let constants = Constants() fireNotification(name: constants.locationUpdated) if oldValue == nil && currentLocation != nil { fiftyMeterLocation = currentLocation } checkIfLocationCrossed() } } var fiftyMeterLocation: CLLocation? let manager: CLLocationManager? override init() { manager = CLLocationManager() super.init() manager?.requestAlwaysAuthorization() manager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters manager?.delegate = self manager?.startUpdatingLocation() } func checkIfLocationCrossed() { let constants = Constants() guard let oldFiftyMeterLocation = fiftyMeterLocation, let newLocation = currentLocation, let thresholdDistance = delegate?.thresholdDistance else {return} let distance = oldFiftyMeterLocation.distance(from: newLocation) // in meters if distance >= thresholdDistance { fireNotification(name: constants.locationThresholdDistanceMet, userInfo: nil) fiftyMeterLocation = newLocation } } func fireNotification(name: String, userInfo: [String: Any]? = nil) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: nil, userInfo: userInfo) } func distanceToCurrentLocation(from location: CLLocation) -> Double { return currentLocation?.distance(from: location) ?? 0.0 } func reverseGeocodeCurrentLocation(_ completion: @escaping CLGeocodeCompletionHandler) { guard let currentLocation = currentLocation else {return} self.reverseGeoCode(location: currentLocation, completion: completion) } func reverseGeoCode(location: CLLocation, completion: @escaping CLGeocodeCompletionHandler) { geoCoder.reverseGeocodeLocation(location, completionHandler: completion) } } extension LocationManager: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.currentLocation = locations.last } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("error updating location: \(error.localizedDescription)") } }
true
8480ecfb1e03a38468220b3f07358b6959a8c0fa
Swift
laclys/swift_practice
/UITableViewTest/UITableViewTest/ViewController.swift
UTF-8
2,205
3
3
[]
no_license
// // ViewController.swift // UITableViewTest // // Created by lac on 2017/11/27. // Copyright © 2017年 lac. All rights reserved. // import UIKit class Product: NSObject { var name:String? var price:String? var ImageName:String? var subTitle:String? } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var dataArray: Array<String>? override func viewDidLoad() { super.viewDidLoad() // 对数据源进行初始化 dataArray = ["第一行", "第二行", "第三行", "第四行", "第五行"] // 创建UITableView实例 let tableView = UITableView(frame: self.view.frame, style: .plain) // 注册cell tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "TableViewCellId") self.view.addSubview(tableView) // 设置数据源与代理 tableView.delegate = self tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 设置列表有多少行 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray!.count } // 设置每行数据的数据载体Cell视图 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 根据注册的Cell类Id值获取到载体Cell let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellId", for: indexPath) // 进行标题设置 cell.textLabel?.text = dataArray?[indexPath.row] return cell } // 设置分组列表的分区数 func numberOfSections(in tableView: UITableView) -> Int { return 2 } // 设置分区头部标题 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "头部~@" } // 设置分区尾部 func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "这里是尾部" } }
true
9f11cfa4a82124617c3b2504a05cdc2182e91a8f
Swift
insight-ios/Messenger
/Messenger/Model/Chatroom.swift
UTF-8
1,644
3
3
[]
no_license
// // Chatroom.swift // Messenger // // Created by SutieDev on 19/04/2019. // Copyright © 2019 insightCell. All rights reserved. // import Foundation enum ChatMemberType { case oneToOne case oneToTwo case oneToThree case oneToMulti } struct Chatroom { var membersIDs: [String] var chatroomID: String? let memberType: ChatMemberType var messagesIDs: [String]? init(membersIDs: [String], chatroomID: String?, messagesIDs: [String]?) { self.membersIDs = membersIDs if chatroomID != nil { self.chatroomID = chatroomID } else { self.chatroomID = ChatroomStorage.shared.createChatroomID() } self.messagesIDs = messagesIDs switch membersIDs.count - 1 { case 1: self.memberType = .oneToOne case 2: self.memberType = .oneToTwo case 3: self.memberType = .oneToThree default : self.memberType = .oneToMulti } } init?(dict: [String: Any], documentID: String) { guard let membersIDs = dict["membersIDs"] as? [String], let messagesIDs = dict["messagesIDs"] as? [String] else { return nil } self.init(membersIDs: membersIDs, chatroomID: documentID, messagesIDs: messagesIDs) } func toDictionary() -> [String: Any] { let dic: [String: Any] = [ "membersIDs": membersIDs, "messagesIDs": messagesIDs ] return dic } mutating func setChatroomID(id: String) { self.chatroomID = id } }
true
a89817a8a70b3ce1206ac42766d5608e076e019f
Swift
JoshuaKozlo/gameswithgold
/GamesWithGold/CommentInputContainerVIew.swift
UTF-8
3,717
2.59375
3
[]
no_license
// // CommentInputContainerVIew.swift // GamesWithGold // // Created by joshua kozlowski on 5/1/17. // Copyright © 2017 joshua kozlowski. All rights reserved. // import UIKit class CommentInputContainerView: UIView, UITextFieldDelegate { var commentsLogController: CommentsCollectionViewController? { didSet { sendButton.addTarget(commentsLogController, action: #selector(CommentsCollectionViewController.handleSend), for: .touchUpInside) } } lazy var inputTextField: UITextField = { let textField = UITextField() textField.placeholder = "Enter comment..." textField.translatesAutoresizingMaskIntoConstraints = false textField.spellCheckingType = .no textField.autocorrectionType = .no textField.delegate = self textField.returnKeyType = UIReturnKeyType.send return textField }() let sendButton = UIButton(type: .system) func textFieldShouldReturn(_ textField: UITextField) -> Bool { commentsLogController?.handleSend() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.characters.count + string.characters.count - range.length return newLength <= 255 // Bool } func textFieldDidChange(_ textField: UITextField) { let text = textField.text if text != nil && text?.isEmpty == false { sendButton.isEnabled = true } else { sendButton.isEnabled = false } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white sendButton.setTitle("Send", for: .normal) sendButton.translatesAutoresizingMaskIntoConstraints = false addSubview(sendButton) // x, y, h, w sendButton.rightAnchor.constraint(equalTo: rightAnchor).isActive = true sendButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true sendButton.heightAnchor.constraint(equalTo: heightAnchor).isActive = true sendButton.isEnabled = false addSubview(self.inputTextField) // x, y, h, w self.inputTextField.leftAnchor.constraint(equalTo: leftAnchor, constant: 8).isActive = true self.inputTextField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true self.inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true self.inputTextField.heightAnchor.constraint(equalTo: heightAnchor).isActive = true self.inputTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) self.inputTextField.enablesReturnKeyAutomatically = true let separatorLineView = UIView() separatorLineView.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1) separatorLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(separatorLineView) // x, y, h , w separatorLineView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true separatorLineView.topAnchor.constraint(equalTo: topAnchor).isActive = true separatorLineView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true separatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
f20b11c8a76d8acadb70d50a7ac8e0c945899ed3
Swift
Love4684/EquationKit
/Sources/EquationKit/Term/TermProtocol.swift
UTF-8
2,555
2.90625
3
[ "Apache-2.0" ]
permissive
// // TermProtocol.swift // EquationKit // // Created by Alexander Cyon on 2018-08-24. // Copyright © 2018 Sajjon. All rights reserved. // import Foundation public protocol TermProtocol: Algebraic, Negatable, AbsoluteConvertible, Comparable, CustomDebugStringConvertible where ExponentiationType.NumberType == Self.NumberType { associatedtype ExponentiationType: ExponentiationProtocol var coefficient: NumberType { get } var exponentiations: [ExponentiationType] { get } init?(exponentiations: [ExponentiationType], sorting: [SortingWithinTerm<NumberType>], coefficient: NumberType) } // MARK: - Convenience Initializers public extension TermProtocol { init?(exponentiations: [ExponentiationType], sorting: [SortingWithinTerm<NumberType>] = SortingWithinTerm<NumberType>.defaultArray, coefficient: NumberType = .one) { self.init(exponentiations: exponentiations, sorting: sorting, coefficient: coefficient) } init?(exponentiation: ExponentiationType, coefficient: NumberType) { self.init(exponentiations: [exponentiation], coefficient: coefficient) } init?(_ exponentiations: ExponentiationType..., coefficient: NumberType) { self.init(exponentiations: exponentiations, coefficient: coefficient) } init(exponentiation: ExponentiationType) { self.init(exponentiations: [exponentiation], coefficient: .one)! } init(_ exponentiations: ExponentiationType...) { self.init(exponentiations: exponentiations, coefficient: .one)! } init(_ variable: VariableStruct<NumberType>) { self.init(exponentiation: ExponentiationType(variable)) } init(_ variables: [VariableStruct<NumberType>]) { self.init(exponentiations: variables.map { ExponentiationType($0) })! } init(_ variables: VariableStruct<NumberType>...) { self.init(variables) } } // MARK: - Public Extensions public extension TermProtocol { var isNegative: Bool { return coefficient.isNegative } func contains(variable: VariableStruct<NumberType>) -> Bool { return exponentiations.map { $0.variable }.contains(variable) } var highestExponent: NumberType { return exponentiations.sorted(by: .descendingExponent)[0].exponent } } // MARK: - Internal Extensions internal extension TermProtocol { var signString: String { return isNegative ? "-" : "+" } var variableNames: String { return exponentiations.map { $0.variable.name }.joined() } }
true
b14ade310981f6eb960f4dc667eb780051b3069d
Swift
frkncngz/moya-generator
/Sources/moya-generator/extensions.swift
UTF-8
710
3.328125
3
[]
no_license
// // File.swift // // // Created by Furkan Cengiz on 30.09.2019. // import Foundation extension String { static var tab = "\t" static var newline = "\n" static func tab(count: Int) -> String { return String(repeating: "\t", count: count) } func tabbed(count: Int) -> String { if count == 0 { return self } else { return "\(String.tab)\(self)".tabbed(count: count - 1) } } func newlined() -> String { return "\(String.newline)\(self)" } func substring(with nsRange: NSRange) -> Substring? { guard let range = Range(nsRange, in: self) else { return nil } return self[range] } }
true
d6f1119efdaf7b44a3a23d32deaa3e4ac074863b
Swift
vladislav-t/AFNutils
/AFNutils/Classes/Services/LocaleService.swift
UTF-8
928
2.84375
3
[ "MIT" ]
permissive
// // LocaleService.swift // AFNutils // // Created by vladislav timoftica on 4/22/19. // import Foundation extension DefaultsKeys { static let localeLanguage = DefaultsKey<String>("localeLanguage") } final class LocaleService { static var defaultLang = "en" static var Lang: String = UserDefaults.standard[.localeLanguage] ?? defaultLang { didSet { updateLocaleController(locale: Lang) UserDefaults.standard[.localeLanguage] = Lang } } static func updateLocaleController(_ controller: UIViewController? = UIApplication.presentedViewController(), locale: String = Lang) { let subviews = controller?.view.allSubViewsOf(type: UIView.self) for view in subviews ?? [] { if !((view as? XIBLocalizable)?.localizedKey?.isEmpty ?? true) { (view as? XIBLocalizable)?.localizedLang = locale } } } }
true
1ba394282bdc898fb4b0dd858b28b2a4af5e562e
Swift
SoftwareVerde/utopia-ios
/Utopia/Utopia/WebViewDelegate.swift
UTF-8
655
2.59375
3
[]
no_license
import Foundation import UIKit open class WebViewDelegate : NSObject, UIWebViewDelegate { fileprivate var _shouldOpenLinksInWebView : Bool = true open func setShouldOpenLinksInWebView(_ shouldOpenLinksInWebView: Bool) { _shouldOpenLinksInWebView = shouldOpenLinksInWebView } open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if (_shouldOpenLinksInWebView) { return true } if (navigationType == .linkClicked) { UIApplication.shared.openURL(request.url!) return false } return true } }
true
6995faafcfa5edad6bd46e388676db640d083691
Swift
CoderGLEric/AmazingSnow
/Very Important project/Entity/Menultem.swift
UTF-8
2,105
2.765625
3
[]
no_license
// // Menultem.swift // Very Important project // // Created by 耿雷 on 16/2/25. // Copyright © 2016年 coderGL. All rights reserved. // import UIKit let meuColors = [ UIColor(red: 00/255, green: 41/255, blue: 82/255, alpha: 1.0), UIColor(red: 11/255, green: 0x8D/255, blue: 0xF0/255, alpha: 1.0), UIColor(red: 95/255, green: 15/255, blue: 56/255, alpha: 1.0), UIColor(red: 0xFF/255, green: 0x4B/255, blue: 68/255, alpha: 1.0), UIColor(red: 207/255, green: 34/255, blue: 156/255, alpha: 1.0), UIColor(red: 14/255, green: 88/255, blue: 149/255, alpha: 1.0), UIColor(red: 15/255, green: 193/255, blue: 231/255, alpha: 1.0), UIColor(red: 43/255, green: 0xA3/255, blue: 67/255, alpha: 1.0), UIColor(red: 0x1C/255, green: 0x0C/255, blue: 0x2A/255, alpha: 1.0) ] let imgs = [ UIImage(named: "xh"), UIImage(named: "work"), UIImage(named: "project"), UIImage(named: "personal"), UIImage(named: "skills"), ] enum ResumeInfomation:String{ case BaseInfo = "基本资料" case Work = "工作经历" case Project = "职业意向" case Personal = "个人简介" case Skills = "教育经历" } class Menultem { let title : String let symbol : UIImage let color : UIColor init (symbol: UIImage, color: UIColor, title : String){ self.symbol = symbol self.title = title self.color = color } static var sharedItems:[Menultem]{ var items = [Menultem]() items.append(Menultem(symbol: imgs[0]!, color: meuColors[0], title:ResumeInfomation.BaseInfo.rawValue)) items.append(Menultem(symbol: imgs[1]!, color: meuColors[1], title: ResumeInfomation.Work.rawValue)) items.append(Menultem(symbol: imgs[2]!, color: meuColors[2], title: ResumeInfomation.Project.rawValue)) items.append(Menultem(symbol: imgs[3]!, color: meuColors[3], title: ResumeInfomation.Personal.rawValue)) items.append(Menultem(symbol: imgs[4]!, color: meuColors[4], title: ResumeInfomation.Skills.rawValue)) return items } }
true
74faf3afa89c43bc87130f8a1adce1aa126ea9f0
Swift
nyjsl/Acfun
/Acfun/exts/UIViewExt.swift
UTF-8
783
2.9375
3
[]
no_license
// // UIViewExt.swift // Acfun // // Created by 魏星 on 2017/2/7. // Copyright © 2017年 wx. All rights reserved. // import Foundation extension UIView{ func borderWithRoundCorner(cornerRadius: CGFloat = 5,borderWidth: CGFloat = 0.5,borderColor: CGColor = UIColor.gray.cgColor){ roundCorner(cornerRadius: cornerRadius) coloredBorder(borderWidth: borderWidth, borderColor: borderColor) } func roundCorner(cornerRadius: CGFloat){ self.layer.masksToBounds = true self.layer.cornerRadius = cornerRadius //圆角 } func coloredBorder(borderWidth: CGFloat,borderColor: CGColor ){ self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor //边框 } }
true
b65d13669453eff39506c2f07a8b4349a96e3dfe
Swift
hanifsgy/AppStore
/AppStore/FeaturedAppsController.swift
UTF-8
1,254
2.546875
3
[]
no_license
// // ViewController.swift // AppStore // // Created by Hanif Sugiyanto on 8/25/16. // Copyright © 2016 Extrainteger. All rights reserved. // import UIKit class FeaturedAppsController: UICollectionViewController, UICollectionViewDelegateFlowLayout { private let cellId = "cellId" override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = UIColor.whiteColor() collectionView?.registerClass(CategoryCell.self, forCellWithReuseIdentifier: cellId) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) return cell } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } // use FlowDelegate for sizeItemAtIndex func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(view.frame.width, 230) } }
true
add2dd344041a4644109ee5167a2c71cb915bc83
Swift
joseflamas/ProHub
/ProHub/ProHub/Source/Shared/Managers/DataManager.swift
UTF-8
6,102
2.640625
3
[]
no_license
// // DataManager.swift // ProHub // // Created by Guillermo Irigoyen on 11/21/18. // Copyright © 2018 Guillermo Irigoyen. All rights reserved. // import Foundation // Lists protocol DataManagerPRListDataDelegate { func PRListInformationObtained(list: [PullRequest] ) } // Detail protocol DataManagerPRDiffInformationDelegate { func PRDiffObtained(diff: PullRequestDiff) } /// Data Manager /// - comment: Centralized place to handle persistent an ephimeral data /// Initialized by the Application Manager final class DataManager { private(set) var pullRequests : [PullRequest] = [PullRequest]() private(set) var pullRequestDiff : PullRequestDiff? var listsDelegate : DataManagerPRListDataDelegate? var diffDelegate : DataManagerPRDiffInformationDelegate? /// Initializers init(){ print("Initializing Data Manager ...") } } extension DataManager { /// JSON func getInitialData() { /// Pull Requests REQUESTMANAGER.delegate = self getPullRequestFromRepository(owner: DEFAULT_REPOSITORY_OWNER, repo: DEFAULT_REPOSITORY_NAME) } func getPullRequestFromRepository(owner: String, repo: String, state: String = "open" ){ pullRequests.removeAll() /// Pull Requests /// https://api.github.com/repos/magicalpanda/MagicalRecord/pulls let prURL = "https://api.github.com/repos/\(owner)/\(repo)/pulls?state=\(state)" VIEWCOORDINATOR.presentActivityIndicator(message: "REQUESTING PULL REQUESTS") REQUESTMANAGER.simpleRequestTo(to:prURL) } func getPullRequestDiff(owner: String, repo: String, number: String){ /// Pull Request Diff /// https://patch-diff.githubusercontent.com/raw/magicalpanda/MagicalRecord/pull/1122.diff let diffURL = "https://patch-diff.githubusercontent.com/raw/\(owner)/\(repo)/pull/\(number).diff" VIEWCOORDINATOR.presentActivityIndicator(message: "REQUESTING DIFF") REQUESTMANAGER.simpleRequestTo(to: diffURL, forResponseFormat: .raw) } } extension DataManager : SimpleRequestManagerDelegate { func simpleRequestInProgress(type: ResponseFormatType, stage: RequestState){ VIEWCOORDINATOR.updateActivityMessage(message: "Request stage: \(stage.string)") } func simpleRequestResponseObtained(response: HTTPURLResponse) { /// DEBUG HEADERS print("REQUEST MANAGER: \(response?.description ?? "REQUEST MANAGER: NO RESPONSE")") } func simpleRequestDataObtained(type: ResponseFormatType, data: Data) { switch type { case .json: jsonDataToObject(data: data) case .raw: rawDataToString(data: data) } } func simpleRequestDataNotFound(type: ResponseFormatType, message: String){ VIEWCOORDINATOR.updateActivityMessage(message: message) VIEWCOORDINATOR.removeActivityIndicator() } } extension DataManager { /// To get Pull Requests from repo func jsonDataToObject(data: Data){ print("\n\nDATA MANAGER: Pull Requests JSON Object\n\n") let jsonData = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) // print("\(jsonData)\n\n") // TO-DO: Replace Struct with a Codable Object? let prArray : Array<Dictionary<String,AnyObject>> = jsonData as! Array<Dictionary<String,AnyObject>> for pr in prArray { let author = pr["user"] as! Dictionary<String,AnyObject> let head = pr["head"] as! Dictionary<String,AnyObject> let base = pr["base"] as! Dictionary<String,AnyObject> let pullRequest : PullRequest = PullRequest(pullId: pr["id"] as! Int, pullNumber: pr["number"] as! Int, pullTitle: pr["title"] as! String, pullState: pr["state"] as! String, idAuthor: author["id"] as! Int, nameAuthor: author["login"] as! String, association: pr["author_association"] as! String, labelHead: head["label"] as! String, labelBase: base["label"] as! String ) pullRequests.append(pullRequest) } print("Number of pull requests: \(pullRequests.count)") if pullRequests.count > 0 { print(pullRequests.first!) print("\n") VIEWCOORDINATOR.removeActivityIndicator() // lists data delegate listsDelegate?.PRListInformationObtained(list: pullRequests) // Get First Diff getPullRequestDiff(owner: DEFAULT_REPOSITORY_OWNER, repo: DEFAULT_REPOSITORY_NAME, number: String(pullRequests.first!.pullRequestNumber)) } else { VIEWCOORDINATOR.removeActivityIndicator() print("NO PULL REQUESTS FOUND \n") } } /// RAW /// To get Diff data func rawDataToString(data: Data){ print("\n\nDATA MANAGER: Compounded Pull Diff\n\n") let rawData = NSString(data: data, encoding: String.Encoding.utf8.rawValue) print("\(rawData!)\n\n") let diff = PullRequestDiff(content: rawData! as String) pullRequestDiff = diff VIEWCOORDINATOR.removeActivityIndicator() // detail delegate diffDelegate?.PRDiffObtained(diff: pullRequestDiff!) } }
true
4c97e1d45444802f1f25bdf10617eff889af7a9f
Swift
wyd2004/LeetCode-Swift
/LeetCode-Swift/90. 子集 II/subsetsWithDup.swift
UTF-8
718
2.859375
3
[]
no_license
// // subsetsWithDup.swift // LeetCode-Swift // // Created by 王一丁 on 2020/3/27. // Copyright © 2020 yidingw. All rights reserved. // import Foundation func subsetsWithDup(_ nums: [Int]) -> [[Int]] { let nums = nums.sorted() var reslut = Array<[Int]>.init() func backtrack(_ nums: [Int], _ track: inout [Int], _ k: Int) { reslut.append(Array.init(track)) for i in k..<nums.count { if i > k && nums[i] == nums[i - 1] { continue } track.append(nums[i]) backtrack(nums, &track, i + 1) track.removeLast() } } var track = Array<Int>.init() backtrack(nums, &track, 0) return reslut }
true
ff74e024bedbf3f99ab10da14544c3435d73dbb0
Swift
Ghzonk/SampleDeviceManager
/SampleDeviceManager/AddDeviceViewController.swift
UTF-8
2,965
2.625
3
[]
no_license
// // AddDeviceViewController.swift // JnJCodingChallenge // // Created by Justin Hur on 7/1/17. // Copyright © 2017 Jong Hur. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class AddDeviceViewController: UIViewController { @IBOutlet weak var deviceText: UITextField! @IBOutlet weak var osText: UITextField! @IBOutlet weak var manufacturerText: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// /// Saves a new device to sever and local storage, then return to previous view. /// If there is missing information, it will notify user. /// @IBAction func saveNewDevice(_ sender: UIBarButtonItem) { // Validate entries and show alert if information is missing if !deviceText.hasText || !osText.hasText || !manufacturerText.hasText { let alert = UIAlertController(title: "Incomplete", message: "Please enter all information.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) return } // Save a new device, and go back to previous view. let deviceRequest = DeviceSynchronizedRequest() deviceRequest.addNewDevice(forDevice: deviceText.text!, withOS: osText.text!, byManufacturer: manufacturerText.text!, complete: {(complete, device) in _ = self.navigationController?.popViewController(animated: true) if let tableVC = self.navigationController?.viewControllers.last as? DeviceTableViewController { tableVC.appendDevice(device: device) } }) } /// /// Cancels adding new device, and go back to previous view. /// If there is any information entered, it shows a confirmation alert. /// @IBAction func cancelAddDevice(_ sender: UIBarButtonItem) { if deviceText.hasText || osText.hasText || manufacturerText.hasText { // Confirmation Alert let alert = UIAlertController(title: "Go Back", message: "All data will be lost. Are you sure?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in _ = self.navigationController?.popViewController(animated: true) })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { _ = self.navigationController?.popViewController(animated: true) } } }
true
c9e1f4a45c7004651df88801ffc1d197ff8065ed
Swift
kmsaboor22/playground
/Numbers.playground/Contents.swift
UTF-8
667
3.828125
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) print("The maximun Int value is \(Int.max).") print("The minimun Int value is \(Int.min)") print("The maximun value for a 32-bit integer is \(Int32.max)") print("The minimun value for a 32-bit integer is \(Int32.min)") print("The maximun UInt value is \(UInt.max)") print("The minimun UInt value is \(UInt.min)") print("The maximun value for a 32-bit unsigned integar is \(UInt32.max)") print("The minimun value for a 32-bit unsigned integar is \(UInt32.min)") print(45 + 67) print(99/2) print(99%2)
true
408bdb8c0a313187b946ad126df49926d1ddceb4
Swift
InventoryBox/inventorybox_iOS
/inventorybox_iOS/inventorybox_iOS/Sources/Models/IvExchange/ProductExchangeInformation.swift
UTF-8
726
2.671875
3
[ "CC-BY-4.0" ]
permissive
// // ProductExchangeInformation.swift // inventorybox_iOS // // Created by 이재용 on 2020/07/10. // Copyright © 2020 jaeyong Lee. All rights reserved. // import Foundation struct ProductExchangeInformation { var ivImageName: String var ivHeart: Bool var ivPrice: String var ivDistance: String var ivName: String var ivLife: String var ivDate: String init(imageName: String, heart: Bool, price: String, distance: String, name: String, life: String, date: String) { self.ivImageName = imageName self.ivHeart = heart self.ivPrice = price self.ivDistance = distance self.ivName = name self.ivLife = life self.ivDate = date } }
true
fa378ad0178a70e76278cb46f30da9ed0520fbf4
Swift
moonbuck/SignalProcessing
/chords/main.swift
UTF-8
563
2.53125
3
[]
no_license
// // main.swift // chords // // Created by Jason Cardwell on 1/6/18. // Copyright © 2018 Moondeer Studios. All rights reserved. // import Foundation import SignalProcessing let arguments = Arguments() switch arguments.command { case .name, .index: guard let pattern = arguments.pattern else { fatalError("Expected a pattern or an early exit.") } if let root = arguments.root { dumpInfo(for: pattern, with: root, pitchesOnly: arguments.pitchesOnly) } else { dumpInfo(for: pattern) } case .help: fatalError("Expected an early exit.") }
true
8c7be37ea62441151839141662fb8b62ba955deb
Swift
martin-lalev/FlooidTableView
/FlooidTableView/Source/TableCellProvider.ResultBuilder.swift
UTF-8
1,371
2.84375
3
[ "MIT" ]
permissive
// // TableCellProvider.ResultBuilder.swift // FlooidTableView // // Created by Martin Lalev on 11/07/2021. // Copyright © 2021 Martin Lalev. All rights reserved. // import UIKit public protocol TableViewCellArrayConvertible { func items() -> [TableCellProvider] } extension TableCellProvider: TableViewCellArrayConvertible { public func items() -> [TableCellProvider] { [self] } } extension Array: TableViewCellArrayConvertible where Element == TableCellProvider { public func items() -> [TableCellProvider] { self } } @resultBuilder public struct TableViewCellsArrayBuilder { public static func buildBlock(_ components: TableViewCellArrayConvertible ...) -> TableViewCellArrayConvertible { components.flatMap { $0.items() } } public static func buildIf(_ component: TableViewCellArrayConvertible?) -> TableViewCellArrayConvertible { component ?? [TableCellProvider]() } public static func buildEither(first: TableViewCellArrayConvertible) -> TableViewCellArrayConvertible { first } public static func buildEither(second: TableViewCellArrayConvertible) -> TableViewCellArrayConvertible { second } } public extension TableSectionProvider { init(_ identifier: String, @TableViewCellsArrayBuilder _ viewBuilder: () -> TableViewCellArrayConvertible) { self.init(identifier: identifier, cellProviders: viewBuilder().items()) } }
true
51b5eb622b44b251d0f169e2e23ae067ca8a027f
Swift
soxjke/Scoper
/Example/Tests/ScopeSpec.swift
UTF-8
4,106
2.59375
3
[ "MIT" ]
permissive
// // ScopeSpec.swift // Scoper_Example // // Created by Petro Korienev on 4/8/18. // Copyright © 2018 CocoaPods. All rights reserved. // import Quick import Nimble @testable import Scoper class ScopeSpec: QuickSpec { private struct Constants { static let helloWorldString = "Hello world" } override func spec() { let before: DefaultScope.Worker = { _ in } let beforeEach: DefaultScope.Worker = { _ in } let after: DefaultScope.Worker = { _ in } let afterEach: DefaultScope.Worker = { _ in } describe("builder") { it("should init with blocks from builder") { let beforeCallSpy = CallSpy.makeCallSpy(f1: before) let beforeEachCallSpy = CallSpy.makeCallSpy(f1: beforeEach) let afterCallSpy = CallSpy.makeCallSpy(f1: after) let afterEachCallSpy = CallSpy.makeCallSpy(f1: afterEach) let scope = DefaultScope.Builder() .before(beforeCallSpy.1) .beforeEach(beforeEachCallSpy.1) .after(afterCallSpy.1) .afterEach(afterEachCallSpy.1) .build() scope.variables.before?(DefaultContext()) scope.variables.beforeEach?(DefaultContext()) scope.variables.after?(DefaultContext()) scope.variables.afterEach?(DefaultContext()) expect(beforeCallSpy.0.callCount) == 1 expect(beforeEachCallSpy.0.callCount) == 1 expect(afterCallSpy.0.callCount) == 1 expect(afterEachCallSpy.0.callCount) == 1 } it("should init with values from builder") { let scope = DefaultScope.Builder() .name(Constants.helloWorldString) .options(TestOptions.basic) .build() expect(scope.variables.name) == Constants.helloWorldString expect(scope.variables.options) == TestOptions.basic } it("should init with test cases from builder") { let testCase1 = DefaultTestCase.Builder().build() let testCase2 = DefaultTestCase.Builder().build() let testCase3 = DefaultTestCase.Builder().build() let scope = DefaultScope.Builder() .testCase(testCase1) .testCase(testCase2) .testCase(testCase3) .build() expect(scope.variables.testCases).to(contain([testCase1, testCase2, testCase3])) } it("should init with test cases and nested scopes from builder") { let testCase1 = DefaultTestCase.Builder().build() let testCase2 = DefaultTestCase.Builder().build() let testCase3 = DefaultTestCase.Builder().build() let nestedScope = DefaultScope.Builder() .testCase(testCase1) .testCase(testCase2) .build() let scope = DefaultScope.Builder() .testCase(testCase3) .nestedScope(nestedScope) .build() expect(scope.variables.testCases).to(contain([testCase3])) expect(scope.variables.scopes).to(contain([nestedScope])) expect(scope.variables.scopes.first?.variables.testCases).to(contain([testCase1, testCase2])) } it("should init with correct default name when not specified") { expect(UUID(uuidString: DefaultScope.Builder().build().variables.name)).toNot(beNil()) } it("should init with basic options when not specified") { expect(DefaultScope.Builder().build().variables.options) == TestOptions.basic } } } }
true
930e19b46ad041d841755c2587540bcf9c039bf7
Swift
CodeKul/Blancco-Swift-iOS-Corporate-May-2020
/iOSDemos/CustomTableViewCell/CustomTableViewCell/Player.swift
UTF-8
448
2.921875
3
[]
no_license
// // Player.swift // CustomTableViewCell // // Created by Apple on 12/05/20. // Copyright © 2020 Codekul. All rights reserved. // import Foundation class Player { var name: String var team: String var image: String var skill: String init(name: String, team: String, image: String, skill: String) { self.name = name self.team = team self.image = image self.skill = skill } }
true
e10888fba081340f7868e791dc783609811f0f21
Swift
sophiakc/Tumblr
/Tumblr/TapBarViewController.swift
UTF-8
5,020
2.71875
3
[ "Apache-2.0" ]
permissive
// // TapBarViewController.swift // Tumblr // // Created by Sophia KC on 07/11/2016. // Copyright © 2016 Sophia KC. All rights reserved. // import UIKit class TapBarViewController: UIViewController { // Outlets // behaves like a container @IBOutlet weak var contentView: UIView! @IBOutlet var buttons: [UIButton]! // Outlets for the VC to be presented in contentView // Variables var homeViewController: UIViewController! var searchViewController: UIViewController! var composeViewController: UIViewController! var accountViewController: UIViewController! var activityViewController: UIViewController! var tapBarViewController: UIViewController! // Define a variable for an array to hold the ViewControllers var viewControllers: [UIViewController]! var selectedIndex: Int = 0 var fadeTransition: FadeTransition! override func viewDidLoad() { super.viewDidLoad() let main = UIStoryboard(name: "Main", bundle: nil) // instantiate each ViewController by referencing main and the particular ViewController's Storyboard ID // Reminder: instantiate == performing segue homeViewController = main.instantiateViewController(withIdentifier: "HomeViewController") searchViewController = main.instantiateViewController(withIdentifier: "SearchViewController") accountViewController = main.instantiateViewController(withIdentifier: "AccountViewController") activityViewController = main.instantiateViewController(withIdentifier: "ActivityViewController") viewControllers = [homeViewController, searchViewController, accountViewController, activityViewController] // set the button state and call the didPressTab method. We will plug in buttons[selectedIndex] as arguments in the didPressTab method to specify the initial button, since we haven't actually "tapped" a button yet and there is no sender to access. buttons[selectedIndex].isSelected = true didPressTab(buttons[selectedIndex]) } @IBAction func didPressTab(_ sender: UIButton) { //----------- Get Access to the Previous and Current Tab Button // keep track of the previous button let previousIndex = selectedIndex // tag value of which ever button was tapped selectedIndex = sender.tag //----------- Remove the Previous ViewController and Set Button State // access previous button and set it to the non-selected state buttons[previousIndex].isSelected = false // use previousIndex to access the previous ViewController from the viewControllers array let previousVC = viewControllers[previousIndex] // Remove the previous ViewController previousVC.willMove(toParentViewController: nil) previousVC.view.removeFromSuperview() previousVC.removeFromParentViewController() //----------- Add the New ViewController and Set Button State. // access your current selected button and set it to the selected state sender.isSelected = true // use selectedIndex to access the current ViewController from the viewControllers array let vc = viewControllers[selectedIndex] // Add the new ViewController. (Calls the viewWillAppear method of the ViewController you are adding) addChildViewController(vc) // Adjust the size of the ViewController view you are adding to match the contentView of your tabBarViewController and add it as a subView of the contentView. vc.view.frame = contentView.bounds contentView.addSubview(vc.view) // Call the viewDidAppear method of the ViewController you are adding using didMove(toParentViewController: self). vc.didMove(toParentViewController: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Access the ViewController that you will be transitioning too, a.k.a, the destinationViewController let destinationViewController = segue.destination // Set the modal presentation style of your destinationViewController to be custom destinationViewController.modalPresentationStyle = UIModalPresentationStyle.custom // Create a new instance of your fadeTransition. fadeTransition = FadeTransition() // Tell the destinationViewController's transitioning delegate to look in fadeTransition for transition instructions. destinationViewController.transitioningDelegate = fadeTransition // Adjust the transition duration. (seconds) fadeTransition.duration = 1.0 print("fadeIn called") } }
true
622a7f35b6e2de233929e056fbed50e2c090d9d3
Swift
narizzo/SwiftKit
/Source/Shared/LocalizedString.swift
UTF-8
1,272
3.171875
3
[ "MIT" ]
permissive
import Foundation /// Struct that can be used to treat localized strings as first-class objects public struct LocalizedString: StringLiteralConvertible { public typealias StringLiteralType = Swift.StringLiteralType public typealias ExtendedGraphemeClusterLiteralType = Swift.ExtendedGraphemeClusterType public typealias UnicodeScalarLiteralType = UnicodeScalarType /// The final, localized string public let string: String /// Initialize with a localization identifier public init(_ identifier: String) { self.string = NSLocalizedString(identifier, comment: "") } /// Initialize with a localization identifier and format arguments public init(identifier: String, arguments: CVarArgType...) { self.string = String(format: NSLocalizedString(identifier, comment: ""), arguments: arguments) } // MARK: - StringLiteralConvertible public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: value) } }
true
2c984e57bae8e5012a0a6adb663df31ebe95d810
Swift
juliafriberg/hangman
/Hangman/GameViewModel.swift
UTF-8
961
3.140625
3
[]
no_license
import UIKit protocol GameViewModel { var delegate: GameDelegate { get set } var hangman: HangmanGame { get set } func startGame() func guess(_ character: Character) func getGuessedWord() -> String func getGameInfoToDisplay() -> String func gameIsOver() -> Bool func showGameOverDialog() func partsToDraw() -> [HangmanDrawingPart] } extension GameViewModel { func guess(_ character: Character) { hangman.guess(character) delegate.updateUI() } func getGuessedWord() -> String { return hangman.guessedWord } func partsToDraw() -> [HangmanDrawingPart] { return hangman.partsToDraw() } func gameIsOver() -> Bool { return hangman.hasWon() || hangman.numberOfWrongGuesses() >= hangman.difficulty.maxWrongGuesses } } protocol GameDelegate { func resetUI() func show(_ alertController: UIAlertController) func updateUI() }
true
765ec27bdea99a7c23c39784466be32be2af80f2
Swift
romanmz/spritekit-reference
/SpriteKit Reference/Tile Maps/SKTileMapNode.swift
UTF-8
3,429
2.953125
3
[]
no_license
// // SKTileMapNode.swift // SpriteKit Reference // // Created by Roman Martinez on 18/3/18. // Copyright © 2018 Roman Martinez. All rights reserved. // import UIKit import SpriteKit class MySKTileMapNode: SKTileMapNode { // Tile maps allow you to create layers with repeatable sprites in a more efficient way than manually creating and positioning individual sprite nodes // they can be arranged in rectangular, hexagonal or isometric grids /* // Init shortcuts // ------------------------------ init(tileSet:columns:rows:tileSize:tileGroupLayout:) // Automatically fills the tile map with a given array of tile groups, filled row by row starting at 0,0 SKTileMapNode.tileMapNodes(tileSet:columns:rows:tileSize:from:tileTypeNoiseMapThresholds:) // Type method. Generate many map nodes from a given tile set and GKNoiseMap ??? */ // [custom initializer to avoid overriding the default ones] convenience init(test: String) { self.init() // [objects to be used later to test properties and methods] guard let isometricSet = SKTileSet(named: "Sample Isometric Tile Set") else { return } let mapTileSize = CGSize(width: 128, height: 64) let grassGroup = isometricSet.tileGroups[0] let waterGroup = isometricSet.tileGroups[3] let grassCenter1 = grassGroup.rules[1].tileDefinitions[0] // Tile map properties // ------------------------------ tileSet = isometricSet // get/set the tile set the map should use tileSize = mapTileSize // get/set the size of each individual tile numberOfColumns = 3 // get/set the total amount of columns on the tile map numberOfRows = 3 // get/set the total amount of rows on the tile map let _ = mapSize // get the total size of the tile map anchorPoint = CGPoint.zero // get/set the normalized anchor point of the node. Defaults to (0.5, 0.5) // Filling the map // ------------------------------ enableAutomapping = true // get/set whether or not to update neighbouring tiles automatically after each call to setTileGroup() fill(with: waterGroup) // fills the entire map using a given tile group setTileGroup(waterGroup, forColumn: 1, row: 0) // fills a single tile using a given tile group (if automapping is enabled uses a fitting definition, otherwise use center) setTileGroup(grassGroup, andTileDefinition: grassCenter1, forColumn: 1, row: 2) // fills a single tile with a specific tile definition // Getting tile info // ------------------------------ tileGroup(atColumn: 1, row: 1) // returns the tile group currently placed at a given index tileDefinition(atColumn: 1, row: 1) // returns the tile definition currently placed at a given index centerOfTile(atColumn: 1, row: 1) // returns the coordinates of the center of a given map index tileRowIndex(fromPosition: CGPoint.zero) // returns the row index that contains a given coordinate tileColumnIndex(fromPosition: CGPoint.zero) // returns the column index that contains a given coordinate /* // Colour and lightning // ------------------------------ // Same as in sprite nodes: color: UIColor colorBlendFactor: CGFloat blendMode: SKBlendMode lightingBitMask: UInt32 // Adding shaders // ------------------------------ // Same as in sprite nodes: shader: SKShader? attributeValues: [String: SKAttributeValue] setValue(_:forAttribute:) value(forAttributeNamed:) */ } }
true
14dd7e50f69f4283f2ca6344d745b6f862a40ec4
Swift
daltonclaybrook/music-room-ios
/MusicRoom/SplashViewController.swift
UTF-8
1,058
2.546875
3
[ "MIT" ]
permissive
// // ViewController.swift // MusicRoom // // Created by Dalton Claybrook on 10/31/16. // Copyright © 2016 Claybrook Software. All rights reserved. // import UIKit import Firebase let SignInSegue = "SignInSegue" let HomeSegue = "HomeSegue" class SplashViewController: UIViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SignInSegue, let navController = segue.destination as? UINavigationController, let signInController = navController.topViewController as? SignInViewController { signInController.delegate = self } } } extension SplashViewController: SignInViewControllerDelegate { func signInViewControllerSignedIn(_ controller: SignInViewController) { dismiss(animated: true) { self.performSegue(withIdentifier: HomeSegue, sender: nil) } } func signInViewControllerCancelled(_ controller: SignInViewController) { dismiss(animated: true, completion: nil) } }
true
ad767b9a588fc0a60103d04558e4e9f5778c65a1
Swift
fajdof/GithubSearch
/GithubSearch/Services/Networking/GithubRouter.swift
UTF-8
1,171
2.78125
3
[]
no_license
// // GithubRouter.swift // GithubSearch // // Created by Filip Fajdetic on 01/07/2017. // Copyright © 2017 Filip Fajdetic. All rights reserved. // import Foundation import Alamofire enum GithubRouter: URLRequestConvertible, AlamofireRouter { static let baseURLString = "https://api.github.com" case Get(path: String, params: [String: AnyObject]?) var method: HTTPMethod { switch self { case .Get(_, _): return HTTPMethod.get } } var params: [String: AnyObject]? { switch self { case .Get(_, let params): return params } } var url: URL { switch self { case .Get(let path, _): return URL(string: GithubRouter.baseURLString + path)! } } var encoding: ParameterEncoding { return URLEncoding.default } var headers: [String: String]? { return nil } func asURLRequest() throws -> URLRequest { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue return try encoding.encode(urlRequest, with: params) } }
true
34c00aaede33fea834a66adb8b9ea3ba169a14d2
Swift
loredeluca/MyMoney
/MyMoney/MyMoney/LatestTransactions.swift
UTF-8
4,531
3.015625
3
[]
no_license
// // LatestTransactions.swift // MyMoney // // Created by Lorenzo De Luca on 29/01/2021. // import SwiftUI extension ContentView{ struct LastTransaction: View { @ObservedObject var c: Controls @ObservedObject var w: Wallet_Obs var body: some View { VStack{ TitleTransaction() ButtonsTransaction(c: c) ListTransactions(c: c, w: w) } } } } struct TitleTransaction: View { var body: some View{ Text("Transazioni recenti") .fontWeight(.bold) .font(.system(size: 20, weight: .bold, design: .rounded)) .padding(.init(top: 0, leading: 0, bottom:0 , trailing: 200)) .offset(y: 5) Spacer().frame(height: 10) } } struct ButtonsTransaction: View { @ObservedObject var c: Controls var body: some View{ HStack{ //bottone 1 Button(action: { c.didTapAllW() }, label: { Text("Totale") }) .frame(width: 70, height: 30) .foregroundColor(Color.black) .background(c.didTapW[0] ? Color.blue : Color.gray)//.opacity(0.7) .clipShape(RoundedRectangle(cornerRadius: 15.0)) //bottone 2 Button(action: { c.didTapInW() }, label: { Text("Entrate") }) .frame(width: 70, height: 30) .foregroundColor(Color.black) .background(c.didTapW[1] ? Color.green : Color.gray)//.opacity(0.7) .clipShape(RoundedRectangle(cornerRadius: 15.0)) //bottone 3 Button(action: { c.didTapOutW() }, label: { Text("Uscite") }) .frame(width: 70, height: 30) .foregroundColor(Color.black) .background(c.didTapW[2] ? Color.red : Color.gray)//.opacity(0.7) .clipShape(RoundedRectangle(cornerRadius: 15.0)) } .frame(width: 380, alignment: .leading) Spacer().frame(height:10) } } struct ListTransactions: View{ @ObservedObject var c: Controls @ObservedObject var w: Wallet_Obs var body: some View{ ScrollView(.vertical) { VStack(spacing: 5) { if w.getCountImage()>0{ //controllo se c'è almeno un elemento ForEach(w.newoperation.reversed(), id: \.self) { value in //mostra Tutte le transazioni if c.didTapW[0]{ transactionView(value: value, w: w) } //mostra le Entrate if c.didTapW[1] && w.getImage(value: w.newoperation.firstIndex(of: value)!) == "chevron.up.circle.fill"{ transactionView(value: value, w: w) } //mostra le Uscite if c.didTapW[2] && w.getImage(value: w.newoperation.firstIndex(of: value)!) == "chevron.down.circle.fill"{ transactionView(value: value, w: w) } } } } } .edgesIgnoringSafeArea(.all) } } struct transactionView: View{ var value : String @ObservedObject var w : Wallet_Obs var body: some View{ HStack{ Image(systemName: "\(w.getImage(value: w.newoperation.firstIndex(of: value)!))" as String) .foregroundColor(w.getImage(value: w.newoperation.firstIndex(of: value)!) == "chevron.up.circle.fill" ? Color.green : Color.red) .frame(maxWidth: 600, alignment: .leading) .offset(x:20, y: -5) VStack{ Text("\(w.getName(value: w.newoperation.firstIndex(of: value)!))" as String) //\(w.getName(value: w.newoperation.firstIndex(of: value)!)) per aggiungere il nome dell'op .frame(maxWidth: 300, alignment: .leading) .offset(x:-127, y: 0) Text("\(w.getCategory(value: w.newoperation.firstIndex(of: value)!)) - \(w.getDate(value: w.newoperation.firstIndex(of: value)!))") .font(.system(size: 14)) .frame(maxWidth: 600, alignment: .leading) .offset(x:-127, y: 0) } Text("\(value)" as String) .offset(x:-10, y: 0) } Divider().offset(x: 0, y: -5) } }
true